aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java22
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/ModelServiceTest.java95
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java107
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfConceptGetterImplTest.java37
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java225
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java78
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java51
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java57
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java201
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java10
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java8
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java22
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java38
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java5
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java6
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfNameVersion.java5
-rw-r--r--models-dao/src/test/java/org/onap/policy/models/dao/DaoMiscTest.java32
-rw-r--r--models-dao/src/test/java/org/onap/policy/models/dao/DummyReferenceEntity.java3
-rw-r--r--models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java171
-rw-r--r--models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseInfo.java2
-rw-r--r--models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java49
-rw-r--r--models-interactions/model-actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProviderTest.java94
-rw-r--r--models-interactions/model-actors/actor.sdnc/src/test/java/org/onap/policy/controlloop/actor/sdnc/SdncActorServiceProviderTest.java25
-rw-r--r--models-interactions/model-actors/actor.sdnr/src/main/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProvider.java1
-rw-r--r--models-interactions/model-actors/actor.sdnr/src/test/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProviderTest.java14
-rw-r--r--models-interactions/model-actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SoActorServiceProvider.java55
-rw-r--r--models-interactions/model-actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java25
-rw-r--r--models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java8
-rw-r--r--models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java63
-rw-r--r--models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/ActorServiceProviderTest.java9
-rw-r--r--models-interactions/model-impl/aai/src/main/java/org/onap/policy/aai/AaiManager.java10
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiCqResponseTest.java18
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiManagerTest.java48
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqCloudRegionTest.java8
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertiesTest.java8
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertyTest.java8
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java25
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInstanceFiltersTest.java8
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemTest.java64
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemsTest.java47
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqNamedQueryTest.java9
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqQueryParametersTest.java9
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqRequestTest.java9
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseTest.java33
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseWrapperTest.java59
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqServiceInstanceTest.java8
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqTenantTest.java8
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVServerTest.java9
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java9
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfInstanceTest.java15
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTest.java15
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTypeTest.java9
-rw-r--r--models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/util/AaiExceptionTest.java8
-rw-r--r--models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/CommonHeaderTest.java49
-rw-r--r--models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/RequestTest.java19
-rw-r--r--models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/ResponseStatusTest.java19
-rw-r--r--models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/AppcLcmTest.java48
-rw-r--r--models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmCommonHeaderTest.java28
-rw-r--r--models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmRequestTest.java19
-rw-r--r--models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmResponseStatusTest.java10
-rw-r--r--models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmWrapperTest.java46
-rw-r--r--models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptor.java7
-rw-r--r--models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/properties/CdsServerProperties.java1
-rw-r--r--models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptorTest.java6
-rw-r--r--models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/CdsProcessorGrpcClientTest.java8
-rw-r--r--models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/ControlLoopNotificationTest.java2
-rw-r--r--models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/params/ControlLoopParamsTest.java12
-rw-r--r--models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceInstanceTest.java22
-rw-r--r--models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceTest.java9
-rw-r--r--models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceInstanceTest.java22
-rw-r--r--models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceTest.java9
-rw-r--r--models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java3
-rw-r--r--models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/util/Serialization.java8
-rw-r--r--models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/DemoTest.java20
-rw-r--r--models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java93
-rw-r--r--models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciCommonHeader.java3
-rw-r--r--models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciRequest.java5
-rw-r--r--models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciCommonHeaderTest.java20
-rw-r--r--models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciRequestTest.java11
-rw-r--r--models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciResponseTest.java7
-rw-r--r--models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciStatusTest.java11
-rw-r--r--models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciWrapperTest.java47
-rw-r--r--models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/SdnrTest.java9
-rw-r--r--models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java1
-rw-r--r--models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoDummyServer.java18
-rw-r--r--models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java326
-rw-r--r--models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoRequestInfoTest.java24
-rw-r--r--models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoResponseWrapperTest.java8
-rw-r--r--models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java9
-rw-r--r--models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/DemoTest.java14
-rw-r--r--models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java84
-rw-r--r--models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java201
-rw-r--r--models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java18
-rw-r--r--models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java55
-rw-r--r--models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java44
-rw-r--r--models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java25
-rw-r--r--models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java66
-rw-r--r--models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java82
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java7
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java65
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java78
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java1006
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java61
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java37
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java32
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java239
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java36
-rw-r--r--models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java52
-rw-r--r--models-interactions/model-yaml/src/test/resources/v1.0.0/test_evil.yaml4
-rw-r--r--models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java4
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java91
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java7
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java7
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageUtils.java4
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java33
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpSubGroupTest.java34
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java27
-rw-r--r--models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java4
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java68
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java3
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java1
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeFilterTest.java50
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java1
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java81
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java78
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/ToscaServiceTemplateMappingTest.java67
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java4
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java3
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java60
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java47
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java13
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java37
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java10
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java47
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchemaTest.java46
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEventFilterTest.java92
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModelTest.java77
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java47
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java18
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java85
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java47
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java93
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java86
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java9
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTimeIntervalTest.java104
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java62
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTriggerTest.java143
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java3
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java79
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java166
-rw-r--r--models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java148
151 files changed, 3251 insertions, 3962 deletions
diff --git a/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java b/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java
index 664e3ddbc..af9e61e2f 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -32,24 +33,27 @@ import org.onap.policy.models.errors.concepts.ErrorResponse;
public class ExceptionsTest {
+ private static final String STRING_TEXT = "String";
+ private static final String MESSAGE = "Message";
+
@Test
public void test() {
- assertNotNull(new PfModelException(Response.Status.OK, "Message"));
- assertNotNull(new PfModelException(Response.Status.OK, "Message", "String"));
- assertNotNull(new PfModelException(Response.Status.OK, "Message", new IOException()));
- assertNotNull(new PfModelException(Response.Status.OK, "Message", new IOException(), "String"));
+ assertNotNull(new PfModelException(Response.Status.OK, MESSAGE));
+ assertNotNull(new PfModelException(Response.Status.OK, MESSAGE, STRING_TEXT));
+ assertNotNull(new PfModelException(Response.Status.OK, MESSAGE, new IOException()));
+ assertNotNull(new PfModelException(Response.Status.OK, MESSAGE, new IOException(), STRING_TEXT));
String key = "A String";
PfModelException ae =
- new PfModelException(Response.Status.OK, "Message", new IOException("IO exception message"), key);
+ new PfModelException(Response.Status.OK, MESSAGE, new IOException("IO exception message"), key);
ErrorResponse errorResponse = ae.getErrorResponse();
assertEquals("Message\nIO exception message", String.join("\n", errorResponse.getErrorDetails()));
assertEquals(key, ae.getObject());
- assertNotNull(new PfModelRuntimeException(Response.Status.OK, "Message"));
- assertNotNull(new PfModelRuntimeException(Response.Status.OK, "Message", "String"));
- assertNotNull(new PfModelRuntimeException(Response.Status.OK, "Message", new IOException()));
- assertNotNull(new PfModelRuntimeException(Response.Status.OK, "Message", new IOException(), "String"));
+ assertNotNull(new PfModelRuntimeException(Response.Status.OK, MESSAGE));
+ assertNotNull(new PfModelRuntimeException(Response.Status.OK, MESSAGE, STRING_TEXT));
+ assertNotNull(new PfModelRuntimeException(Response.Status.OK, MESSAGE, new IOException()));
+ assertNotNull(new PfModelRuntimeException(Response.Status.OK, MESSAGE, new IOException(), STRING_TEXT));
String rkey = "A String";
PfModelRuntimeException re = new PfModelRuntimeException(Response.Status.OK, "Runtime Message",
diff --git a/models-base/src/test/java/org/onap/policy/models/base/ModelServiceTest.java b/models-base/src/test/java/org/onap/policy/models/base/ModelServiceTest.java
index 0e790d3dc..1b7a996ed 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/ModelServiceTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/ModelServiceTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,86 +21,58 @@
package org.onap.policy.models.base;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import org.junit.Test;
import org.onap.policy.models.base.testconcepts.DummyPfModel;
public class ModelServiceTest {
+ private static final String MODEL_KEY_IS_NULL = "modelKey is marked @NonNull but is null";
+ private static final String MODEL_NAME = "ModelName";
+
@Test
public void testModelService() {
PfModelService.clear();
assertFalse(PfModelService.existsModel("NonExistantName"));
- try {
- PfModelService.getModel("NonExistantName");
- } catch (final Exception e) {
- assertEquals("Model for name NonExistantName not found in model service", e.getMessage());
- }
+ assertThatThrownBy(() -> PfModelService.getModel("NonExistantName"))
+ .hasMessage("Model for name NonExistantName not found in model service");
- PfModelService.registerModel("ModelName", new DummyPfModel());
- assertTrue(PfModelService.existsModel("ModelName"));
- assertNotNull(PfModelService.getModel("ModelName"));
+ PfModelService.registerModel(MODEL_NAME, new DummyPfModel());
+ assertTrue(PfModelService.existsModel(MODEL_NAME));
+ assertNotNull(PfModelService.getModel(MODEL_NAME));
- PfModelService.deregisterModel("ModelName");
+ PfModelService.deregisterModel(MODEL_NAME);
- assertFalse(PfModelService.existsModel("ModelName"));
- try {
- PfModelService.getModel("ModelName");
- } catch (final Exception e) {
- assertEquals("Model for name ModelName not found in model service", e.getMessage());
- }
+ assertFalse(PfModelService.existsModel(MODEL_NAME));
+ assertThatThrownBy(() -> PfModelService.getModel(MODEL_NAME))
+ .hasMessage("Model for name ModelName not found in model service");
- PfModelService.registerModel("ModelName", new DummyPfModel());
- assertTrue(PfModelService.existsModel("ModelName"));
- assertNotNull(PfModelService.getModel("ModelName"));
+ PfModelService.registerModel(MODEL_NAME, new DummyPfModel());
+ assertTrue(PfModelService.existsModel(MODEL_NAME));
+ assertNotNull(PfModelService.getModel(MODEL_NAME));
PfModelService.clear();
- assertFalse(PfModelService.existsModel("ModelName"));
- try {
- PfModelService.getModel("ModelName");
- } catch (final Exception e) {
- assertEquals("Model for name ModelName not found in model service", e.getMessage());
- }
-
- try {
- PfModelService.registerModel(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("modelKey is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- PfModelService.registerModel("nullModelName", null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("model is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- PfModelService.registerModel(null, new DummyPfModel());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("modelKey is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- PfModelService.deregisterModel(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("modelKey is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- PfModelService.getModel(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("modelKey is marked @NonNull but is null", exc.getMessage());
- }
+ assertFalse(PfModelService.existsModel(MODEL_NAME));
+ assertThatThrownBy(() -> PfModelService.getModel(MODEL_NAME))
+ .hasMessage("Model for name ModelName not found in model service");
+
+ assertThatThrownBy(() -> PfModelService.registerModel(null, null))
+ .hasMessage(MODEL_KEY_IS_NULL);
+
+ assertThatThrownBy(() -> PfModelService.registerModel("nullModelName", null))
+ .hasMessage("model is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> PfModelService.registerModel(null, new DummyPfModel()))
+ .hasMessage(MODEL_KEY_IS_NULL);
+
+ assertThatThrownBy(() -> PfModelService.deregisterModel(null))
+ .hasMessage(MODEL_KEY_IS_NULL);
+
+ assertThatThrownBy(() -> PfModelService.getModel(null)).hasMessage(MODEL_KEY_IS_NULL);
}
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java
index 4ad7c0f9e..984d2b9d3 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -25,7 +26,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@@ -33,7 +33,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
-
import org.junit.Test;
import org.onap.policy.models.base.testconcepts.DummyAuthorativeConcept;
import org.onap.policy.models.base.testconcepts.DummyBadPfConceptContainer;
@@ -48,6 +47,13 @@ import org.onap.policy.models.base.testconcepts.DummyPfConceptSub;
*/
public class PfConceptContainerTest {
+ private static final String NAME2 = "name2";
+ private static final String NAME1 = "name1";
+ private static final String NAME0 = "name0";
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+ private static final String DUMMY_VALUE = "Dummy";
+ private static final String VERSION0 = "0.0.1";
+
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testConceptContainer() {
@@ -63,51 +69,28 @@ public class PfConceptContainerTest {
container = new DummyPfConceptContainer(new PfConceptKey(), new TreeMap<PfConceptKey, DummyPfConcept>());
assertNotNull(container);
- try {
- new PfConceptContainer((PfConceptKey) null, null);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- container = new DummyPfConceptContainer((PfConceptKey) null, null);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- container = new DummyPfConceptContainer(new PfConceptKey(), null);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("conceptMap is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- container = new DummyPfConceptContainer(null, new TreeMap<PfConceptKey, DummyPfConcept>());
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- container.getKey().setName("Dummy");
+ assertThatThrownBy(() -> new PfConceptContainer((PfConceptKey) null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new DummyPfConceptContainer((PfConceptKey) null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new DummyPfConceptContainer(new PfConceptKey(), null))
+ .hasMessage("conceptMap is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new DummyPfConceptContainer(null, new TreeMap<PfConceptKey, DummyPfConcept>()))
+ .hasMessage(KEY_IS_NULL);
+
+ container.getKey().setName(DUMMY_VALUE);
DummyPfConceptContainer clonedContainer = new DummyPfConceptContainer(container);
assertNotNull(clonedContainer);
- assertEquals("Dummy", clonedContainer.getKey().getName());
+ assertEquals(DUMMY_VALUE, clonedContainer.getKey().getName());
- try {
- DummyPfConceptContainer conceptContainter = null;
- container = new DummyPfConceptContainer(conceptContainter);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new DummyPfConceptContainer((DummyPfConceptContainer) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
List<PfKey> keyList = container.getKeys();
assertEquals(1, keyList.size());
- PfConceptKey conceptKey = new PfConceptKey("Key", "0.0.1");
+ PfConceptKey conceptKey = new PfConceptKey("Key", VERSION0);
Map<PfConceptKey, DummyPfConcept> conceptMap = new TreeMap<>();
conceptMap.put(conceptKey, new DummyPfConcept(conceptKey));
@@ -117,7 +100,7 @@ public class PfConceptContainerTest {
clonedContainer = new DummyPfConceptContainer(container);
assertNotNull(clonedContainer);
- assertEquals("Dummy", clonedContainer.getKey().getName());
+ assertEquals(DUMMY_VALUE, clonedContainer.getKey().getName());
assertEquals(2, clonedContainer.getKeys().size());
assertEquals(clonedContainer, container);
@@ -130,12 +113,8 @@ public class PfConceptContainerTest {
assertEquals(0, container.compareTo(clonedContainer));
- try {
- container.copyTo(null);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ final DummyPfConceptContainer container2 = container;
+ assertThatThrownBy(() -> container2.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertFalse(container.compareTo(null) == 0);
assertEquals(0, container.compareTo(container));
@@ -147,20 +126,16 @@ public class PfConceptContainerTest {
testContainer.getKey().setVersion(container.getKey().getVersion());
assertEquals(0, container.compareTo(testContainer));
- PfConceptKey testConceptKey = new PfConceptKey("TestKey", "0.0.1");
+ PfConceptKey testConceptKey = new PfConceptKey("TestKey", VERSION0);
testContainer.getConceptMap().put(testConceptKey, new DummyPfConcept(testConceptKey));
assertFalse(container.compareTo(testContainer) == 0);
- try {
- container.validate(null);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ final DummyPfConceptContainer container3 = container;
+ assertThatThrownBy(() -> container3.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
DummyPfConceptContainer validateContainer = new DummyPfConceptContainer();
assertFalse(validateContainer.validate(new PfValidationResult()).isOk());
- validateContainer.setKey(new PfConceptKey("VCKey", "0.0.1"));
+ validateContainer.setKey(new PfConceptKey("VCKey", VERSION0));
assertFalse(validateContainer.validate(new PfValidationResult()).isOk());
validateContainer.getConceptMap().put(testConceptKey, new DummyPfConcept(testConceptKey));
@@ -197,9 +172,9 @@ public class PfConceptContainerTest {
@Test
public void testAuthorative() {
Map<String, DummyAuthorativeConcept> dacMap = new LinkedHashMap<>();
- dacMap.put("name0", new DummyAuthorativeConcept("name0", "1.2.3", "Hello"));
- dacMap.put("name1", new DummyAuthorativeConcept(PfKey.NULL_KEY_NAME, PfKey.NULL_KEY_VERSION, "Hi"));
- dacMap.put("name2", new DummyAuthorativeConcept("name2", "1.2.3", "Howdy"));
+ dacMap.put(NAME0, new DummyAuthorativeConcept(NAME0, "1.2.3", "Hello"));
+ dacMap.put(NAME1, new DummyAuthorativeConcept(PfKey.NULL_KEY_NAME, PfKey.NULL_KEY_VERSION, "Hi"));
+ dacMap.put(NAME2, new DummyAuthorativeConcept(NAME2, "1.2.3", "Howdy"));
List<Map<String, DummyAuthorativeConcept>> authorativeList = new ArrayList<>();
authorativeList.add(dacMap);
@@ -213,19 +188,17 @@ public class PfConceptContainerTest {
List<Map<String, DummyAuthorativeConcept>> outMapList = container.toAuthorative();
- assertEquals(dacMap.get("name1"), outMapList.get(0).get("NULL"));
- assertEquals(dacMap.get("name0").getDescription(), outMapList.get(1).get("name0").getDescription());
- assertEquals(dacMap.get("name2"), outMapList.get(2).get("name2"));
+ assertEquals(dacMap.get(NAME1), outMapList.get(0).get("NULL"));
+ assertEquals(dacMap.get(NAME0).getDescription(), outMapList.get(1).get(NAME0).getDescription());
+ assertEquals(dacMap.get(NAME2), outMapList.get(2).get(NAME2));
DummyBadPfConceptContainer badContainer = new DummyBadPfConceptContainer();
- assertThatThrownBy(() -> {
- badContainer.fromAuthorative(authorativeList);
- }).hasMessage("failed to instantiate instance of container concept class");
+ assertThatThrownBy(() -> badContainer.fromAuthorative(authorativeList))
+ .hasMessage("failed to instantiate instance of container concept class");
authorativeList.clear();
- assertThatThrownBy(() -> {
- container.fromAuthorative(authorativeList);
- }).hasMessage("An incoming list of concepts must have at least one entry");
+ assertThatThrownBy(() -> container.fromAuthorative(authorativeList))
+ .hasMessage("An incoming list of concepts must have at least one entry");
}
@Test(expected = NullPointerException.class)
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfConceptGetterImplTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfConceptGetterImplTest.java
index ae5b2ff2b..b373e419f 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfConceptGetterImplTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfConceptGetterImplTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,15 +21,14 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.TreeSet;
-
import org.junit.Test;
/**
@@ -36,6 +36,9 @@ import org.junit.Test;
*/
public class PfConceptGetterImplTest {
+ private static final String VERSION002 = "0.0.2";
+ private static final String VERSION001 = "0.0.1";
+
@Test
public void testPfConceptGetterImpl() {
NavigableMap<PfConceptKey, PfConceptKey> keyMap = new TreeMap<>();
@@ -43,54 +46,42 @@ public class PfConceptGetterImplTest {
PfConceptGetterImpl<PfConceptKey> getter = new PfConceptGetterImpl<>(keyMap);
assertNotNull(getter);
- PfConceptKey keyA = new PfConceptKey("A", "0.0.1");
+ PfConceptKey keyA = new PfConceptKey("A", VERSION001);
assertNull(getter.get(keyA));
- try {
- getter.get((String)null);
- fail("test should throw an exception here");
- }
- catch (Exception getException) {
- assertEquals("conceptKeyName may not be null", getException.getMessage());
- }
+ assertThatThrownBy(() -> getter.get((String) null)).hasMessage("conceptKeyName may not be null");
assertNull(getter.get("W"));
- PfConceptKey keyZ = new PfConceptKey("Z", "0.0.1");
+ PfConceptKey keyZ = new PfConceptKey("Z", VERSION001);
keyMap.put(keyZ, keyZ);
assertNull(getter.get("W"));
- PfConceptKey keyW001 = new PfConceptKey("W", "0.0.1");
+ PfConceptKey keyW001 = new PfConceptKey("W", VERSION001);
keyMap.put(keyW001, keyW001);
assertEquals(keyW001, getter.get("W"));
- PfConceptKey keyW002 = new PfConceptKey("W", "0.0.2");
+ PfConceptKey keyW002 = new PfConceptKey("W", VERSION002);
keyMap.put(keyW002, keyW002);
assertEquals(keyW002, getter.get("W"));
keyMap.remove(keyZ);
assertEquals(keyW002, getter.get("W"));
- try {
- getter.get((String)null, "0.0.1");
- fail("test should throw an exception here");
- }
- catch (Exception getException) {
- assertEquals("conceptKeyName may not be null", getException.getMessage());
- }
+ assertThatThrownBy(() -> getter.get((String) null, VERSION001)).hasMessage("conceptKeyName may not be null");
- assertEquals(keyW002, getter.get("W", "0.0.2"));
+ assertEquals(keyW002, getter.get("W", VERSION002));
assertEquals(keyW002, getter.get("W", (String)null));
assertEquals(new TreeSet<PfConceptKey>(keyMap.values()), getter.getAll(null));
assertEquals(new TreeSet<PfConceptKey>(keyMap.values()), getter.getAll(null, null));
assertEquals(keyW001, getter.getAll("W", null).iterator().next());
- assertEquals(keyW002, getter.getAll("W", "0.0.2").iterator().next());
+ assertEquals(keyW002, getter.getAll("W", VERSION002).iterator().next());
assertEquals(0, getter.getAll("A", null).size());
assertEquals(0, getter.getAll("Z", null).size());
keyMap.put(keyZ, keyZ);
- assertEquals(keyW002, getter.getAll("W", "0.0.2").iterator().next());
+ assertEquals(keyW002, getter.getAll("W", VERSION002).iterator().next());
}
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java
index 13541b84e..9ef1aeb75 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,45 +21,40 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.lang.reflect.Field;
-
import org.junit.Test;
-
import org.onap.policy.models.base.PfKey.Compatibility;
import org.onap.policy.models.base.testconcepts.DummyPfConcept;
import org.onap.policy.models.base.testconcepts.DummyPfKey;
public class PfKeyTest {
+ private static final String OTHER_IS_NULL = "otherKey is marked @NonNull but is null";
+ private static final String ID_IS_NULL = "id is marked @NonNull but is null";
+ private static final String VERSION123 = "1.2.3";
+ private static final String VERSION100 = "1.0.0";
+ private static final String VERSION001 = "0.0.1";
+
@Test
public void testConceptKey() {
- try {
- new PfConceptKey("some bad key id");
- fail("This test should throw an exception");
- } catch (IllegalArgumentException e) {
- assertEquals(
- "parameter \"id\": value \"some bad key id\", "
- + "does not match regular expression \"" + PfKey.KEY_ID_REGEXP + "\"",
- e.getMessage());
- }
-
- try {
- new PfConceptKey((PfConceptKey) null);
- fail("This test should throw an exception");
- } catch (Exception e) {
- assertEquals("copyConcept is marked @NonNull but is null", e.getMessage());
- }
+ assertThatIllegalArgumentException().isThrownBy(() -> new PfConceptKey("some bad key id"))
+ .withMessage("parameter \"id\": value \"some bad key id\", "
+ + "does not match regular expression \"" + PfKey.KEY_ID_REGEXP + "\"");
+
+ assertThatThrownBy(() -> new PfConceptKey((PfConceptKey) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
PfConceptKey someKey0 = new PfConceptKey();
assertEquals(PfConceptKey.getNullKey(), someKey0);
- PfConceptKey someKey1 = new PfConceptKey("name", "0.0.1");
+ PfConceptKey someKey1 = new PfConceptKey("name", VERSION001);
PfConceptKey someKey2 = new PfConceptKey(someKey1);
PfConceptKey someKey3 = new PfConceptKey(someKey1.getId());
assertEquals(someKey1, someKey2);
@@ -94,12 +90,7 @@ public class PfKeyTest {
assertTrue(PfConceptKey.getNullKey().isNullKey());
- try {
- PfConceptKey.getNullKey().matchesId(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("id is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> PfConceptKey.getNullKey().matchesId(null)).hasMessage(ID_IS_NULL);
assertEquals(Compatibility.DIFFERENT, someKey0.getCompatibility(new DummyPfKey()));
assertEquals(Compatibility.DIFFERENT, someKey0.getCompatibility(someKey1));
@@ -141,130 +132,79 @@ public class PfKeyTest {
assertEquals(0, someKey7.compareTo(someKey1));
assertEquals(-12, someKey7.compareTo(someKey0));
- try {
- someKey0.compareTo(null);
- fail("test should throw an exception here");
- } catch (NullPointerException e) {
- assertEquals("otherObj is marked @NonNull but is null", e.getMessage());
- }
+ assertThatThrownBy(() -> someKey0.compareTo(null)).isInstanceOf(NullPointerException.class)
+ .hasMessage("otherObj is marked @NonNull but is null");
assertEquals(0, someKey0.compareTo(someKey0));
assertEquals(266127751, someKey0.compareTo(new DummyPfKey()));
assertFalse(someKey0.equals(null));
assertTrue(someKey0.equals(someKey0));
- assertFalse(((PfKey) someKey0).equals(new DummyPfKey()));
+ assertFalse(someKey0.equals(new DummyPfKey()));
}
@Test
public void testNullArguments() {
- try {
- new PfConceptKey((String) null);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("id is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new PfConceptKey((PfConceptKey) null);
- fail("id is marked @NonNull but is null");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new PfConceptKey(null, null);
- fail("id is marked @NonNull but is null");
- } catch (Exception exc) {
- assertEquals("name is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new PfConceptKey("name", null);
- fail("id is marked @NonNull but is null");
- } catch (Exception exc) {
- assertEquals("version is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new PfConceptKey(null, "0.0.1");
- fail("id is marked @NonNull but is null");
- } catch (Exception exc) {
- assertEquals("name is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- PfConceptKey key = new PfConceptKey("AKey", "0.0.1");
- key.isCompatible(null);
- fail("id is marked @NonNull but is null");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new PfConceptKey((String) null)).hasMessage(ID_IS_NULL);
+
+ assertThatThrownBy(() -> new PfConceptKey((PfConceptKey) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new PfConceptKey(null, null)).hasMessage("name is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new PfConceptKey("name", null)).hasMessage("version is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new PfConceptKey(null, VERSION001)).hasMessage("name is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new PfConceptKey("AKey", VERSION001).isCompatible(null)).hasMessage(OTHER_IS_NULL);
}
@Test
- public void testValidation() {
- PfConceptKey testKey = new PfConceptKey("TheKey", "0.0.1");
+ public void testValidation() throws Exception {
+ PfConceptKey testKey = new PfConceptKey("TheKey", VERSION001);
assertEquals("TheKey:0.0.1", testKey.getId());
- try {
- Field nameField = testKey.getClass().getDeclaredField("name");
- nameField.setAccessible(true);
- nameField.set(testKey, "Key Name");
- PfValidationResult validationResult = new PfValidationResult();
- testKey.validate(validationResult);
- nameField.set(testKey, "TheKey");
- nameField.setAccessible(false);
- assertEquals(
- "name invalid-parameter name with value Key Name "
- + "does not match regular expression " + PfKey.NAME_REGEXP,
- validationResult.getMessageList().get(0).getMessage());
- } catch (Exception validationException) {
- fail("test should not throw an exception");
- }
-
- try {
- Field versionField = testKey.getClass().getDeclaredField("version");
- versionField.setAccessible(true);
- versionField.set(testKey, "Key Version");
- PfValidationResult validationResult = new PfValidationResult();
- testKey.validate(validationResult);
- versionField.set(testKey, "0.0.1");
- versionField.setAccessible(false);
- assertEquals(
- "version invalid-parameter version with value Key Version "
- + "does not match regular expression " + PfKey.VERSION_REGEXP,
- validationResult.getMessageList().get(0).getMessage());
- } catch (Exception validationException) {
- fail("test should not throw an exception");
- }
+ Field nameField = testKey.getClass().getDeclaredField("name");
+ nameField.setAccessible(true);
+ nameField.set(testKey, "Key Name");
+ PfValidationResult validationResult = new PfValidationResult();
+ testKey.validate(validationResult);
+ nameField.set(testKey, "TheKey");
+ nameField.setAccessible(false);
+ assertEquals(
+ "name invalid-parameter name with value Key Name "
+ + "does not match regular expression " + PfKey.NAME_REGEXP,
+ validationResult.getMessageList().get(0).getMessage());
+
+ Field versionField = testKey.getClass().getDeclaredField("version");
+ versionField.setAccessible(true);
+ versionField.set(testKey, "Key Version");
+ PfValidationResult validationResult2 = new PfValidationResult();
+ testKey.validate(validationResult2);
+ versionField.set(testKey, VERSION001);
+ versionField.setAccessible(false);
+ assertEquals(
+ "version invalid-parameter version with value Key Version "
+ + "does not match regular expression " + PfKey.VERSION_REGEXP,
+ validationResult2.getMessageList().get(0).getMessage());
}
@Test
public void testkeynewerThan() {
- PfConceptKey key1 = new PfConceptKey("Key1", "1.2.3");
-
- try {
- key1.isNewerThan(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- key1.isNewerThan(new PfReferenceKey());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("org.onap.policy.models.base.PfReferenceKey is not "
- + "an instance of org.onap.policy.models.base.PfConceptKey", exc.getMessage());
- }
+ PfConceptKey key1 = new PfConceptKey("Key1", VERSION123);
+
+ assertThatThrownBy(() -> key1.isNewerThan(null)).hasMessage(OTHER_IS_NULL);
+
+ assertThatThrownBy(() -> key1.isNewerThan(new PfReferenceKey()))
+ .hasMessage("org.onap.policy.models.base.PfReferenceKey is not "
+ + "an instance of org.onap.policy.models.base.PfConceptKey");
assertFalse(key1.isNewerThan(key1));
- PfConceptKey key1a = new PfConceptKey("Key1a", "1.2.3");
+ PfConceptKey key1a = new PfConceptKey("Key1a", VERSION123);
assertFalse(key1.isNewerThan(key1a));
- PfConceptKey key1b = new PfConceptKey("Key0", "1.2.3");
+ PfConceptKey key1b = new PfConceptKey("Key0", VERSION123);
assertTrue(key1.isNewerThan(key1b));
key1a.setName("Key1");
@@ -274,51 +214,42 @@ public class PfKeyTest {
assertTrue(key1.isNewerThan(key1a));
key1a.setVersion("2.2.3");
assertFalse(key1.isNewerThan(key1a));
- key1a.setVersion("1.2.3");
+ key1a.setVersion(VERSION123);
assertFalse(key1.isNewerThan(key1a));
key1a.setVersion("1.1.3");
assertTrue(key1.isNewerThan(key1a));
key1a.setVersion("1.3.3");
assertFalse(key1.isNewerThan(key1a));
- key1a.setVersion("1.2.3");
+ key1a.setVersion(VERSION123);
assertFalse(key1.isNewerThan(key1a));
key1a.setVersion("1.2.2");
assertTrue(key1.isNewerThan(key1a));
key1a.setVersion("1.2.4");
assertFalse(key1.isNewerThan(key1a));
- key1a.setVersion("1.2.3");
+ key1a.setVersion(VERSION123);
assertFalse(key1.isNewerThan(key1a));
- key1.setVersion("1.0.0");
+ key1.setVersion(VERSION100);
assertFalse(key1.isNewerThan(key1a));
- key1a.setVersion("1.0.0");
+ key1a.setVersion(VERSION100);
assertFalse(key1.isNewerThan(key1a));
PfReferenceKey refKey = new PfReferenceKey();
- try {
- refKey.isNewerThan(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- refKey.isNewerThan(new PfConceptKey());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("org.onap.policy.models.base.PfConceptKey is not "
- + "an instance of org.onap.policy.models.base.PfReferenceKey", exc.getMessage());
- }
+ assertThatThrownBy(() -> refKey.isNewerThan(null)).hasMessage(OTHER_IS_NULL);
+
+ assertThatThrownBy(() -> refKey.isNewerThan(new PfConceptKey()))
+ .hasMessage("org.onap.policy.models.base.PfConceptKey is not "
+ + "an instance of org.onap.policy.models.base.PfReferenceKey");
assertFalse(refKey.isNewerThan(refKey));
}
@Test
public void testmajorMinorPatch() {
- PfConceptKey key = new PfConceptKey("Key", "1.0.0");
+ PfConceptKey key = new PfConceptKey("Key", VERSION100);
assertEquals(1, key.getMajorVersion());
assertEquals(0, key.getMinorVersion());
assertEquals(0, key.getPatchVersion());
@@ -328,7 +259,7 @@ public class PfKeyTest {
assertEquals(2, key.getMinorVersion());
assertEquals(0, key.getPatchVersion());
- key = new PfConceptKey("Key", "1.2.3");
+ key = new PfConceptKey("Key", VERSION123);
assertEquals(1, key.getMajorVersion());
assertEquals(2, key.getMinorVersion());
assertEquals(3, key.getPatchVersion());
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java
index 68494309c..f7d1d9a5f 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,12 +21,12 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import org.junit.Test;
import org.onap.policy.models.base.PfKey.Compatibility;
@@ -33,19 +34,16 @@ import org.onap.policy.models.base.testconcepts.DummyPfConceptKeySub;
public class PfKeyUseTest {
- @SuppressWarnings("unlikely-arg-type")
+ private static final String OTHER_KEY_IS_NULL = "otherKey is marked @NonNull but is null";
+
@Test
public void testKeyUse() {
assertNotNull(new PfKeyUse());
assertNotNull(new PfKeyUse(new PfConceptKey()));
assertNotNull(new PfKeyUse(new PfReferenceKey()));
- try {
- new PfKeyUse((PfKeyUse) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new PfKeyUse((PfKeyUse) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
PfConceptKey key = new PfConceptKey("Key", "0.0.1");
PfKeyUse keyUse = new PfKeyUse();
@@ -57,12 +55,7 @@ public class PfKeyUseTest {
assertEquals(Compatibility.IDENTICAL, keyUse.getCompatibility(key));
- try {
- key.getCompatibility(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> key.getCompatibility(null)).hasMessage(OTHER_KEY_IS_NULL);
assertTrue(keyUse.isCompatible(key));
@@ -94,58 +87,25 @@ public class PfKeyUseTest {
PfValidationResult resultNull = new PfValidationResult();
assertEquals(false, keyUseNull.validate(resultNull).isValid());
- try {
- keyUse.setKey(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- keyUse.getCompatibility(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- keyUse.isCompatible(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- keyUse.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("result is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> keyUse.setKey(null)).hasMessage("key is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> keyUse.getCompatibility(null)).hasMessage(OTHER_KEY_IS_NULL);
+
+ assertThatThrownBy(() -> keyUse.isCompatible(null)).hasMessage(OTHER_KEY_IS_NULL);
+
+ assertThatThrownBy(() -> keyUse.validate(null)).hasMessage("result is marked @NonNull but is null");
PfKeyUse testKeyUse = new PfKeyUse(new DummyPfConceptKeySub(new PfConceptKey()));
PfKeyUse targetKeyUse = new PfKeyUse(key);
- try {
- keyUse.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> keyUse.copyTo(null)).hasMessage("target is marked @NonNull but is null");
- try {
+ assertThatThrownBy(() -> {
testKeyUse.copyTo(targetKeyUse);
keyUse.isCompatible(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("error copying concept key: Some error message", exc.getMessage());
- }
-
- try {
- keyUse.isNewerThan(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
+ }).hasMessage("error copying concept key: Some error message");
+
+ assertThatThrownBy(() -> keyUse.isNewerThan(null)).hasMessage(OTHER_KEY_IS_NULL);
assertEquals(false, testKeyUse.isNewerThan(keyUse));
assertEquals(false, testKeyUse.isNewerThan(testKeyUse));
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java
index cf7c41f6b..2f4a1beb9 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java
@@ -1,7 +1,7 @@
-package org.onap.policy.models.base;
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -19,11 +19,13 @@ package org.onap.policy.models.base;
* ============LICENSE_END=========================================================
*/
+package org.onap.policy.models.base;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import org.junit.Test;
import org.onap.policy.models.base.testconcepts.DummyPfModel;
@@ -35,28 +37,21 @@ import org.onap.policy.models.base.testconcepts.DummyPfModel;
*/
public class PfModelTest {
+ private static final String VERSION001 = "0.0.1";
+
@Test
public void testPfModel() {
assertNotNull(new DummyPfModel());
assertNotNull(new DummyPfModel(new PfConceptKey()));
assertNotNull(new DummyPfModel(new DummyPfModel()));
- try {
- new DummyPfModel((PfConceptKey)null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- DummyPfModel nullModel = null;
- new DummyPfModel(nullModel);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- DummyPfModel dpm = new DummyPfModel(new PfConceptKey("modelKey", "0.0.1"));
+ assertThatThrownBy(() -> new DummyPfModel((PfConceptKey) null))
+ .hasMessage("key is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new DummyPfModel((DummyPfModel) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ DummyPfModel dpm = new DummyPfModel(new PfConceptKey("modelKey", VERSION001));
DummyPfModel dpmClone = new DummyPfModel(dpm);
assertEquals(dpm, dpmClone);
@@ -65,12 +60,7 @@ public class PfModelTest {
dpmClone.clean();
assertEquals(dpm, dpmClone);
- try {
- dpm.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> dpm.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(0, dpm.compareTo(dpmClone));
assertEquals(-1, dpm.compareTo(null));
@@ -80,16 +70,11 @@ public class PfModelTest {
@Test
public void testPfModelValidation() {
- PfConceptKey dpmKey = new PfConceptKey("modelKey", "0.0.1");
+ PfConceptKey dpmKey = new PfConceptKey("modelKey", VERSION001);
DummyPfModel dpm = new DummyPfModel(dpmKey);
assertTrue(dpm.validate(new PfValidationResult()).isValid());
- try {
- dpm.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> dpm.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
dpm.setKey(PfConceptKey.getNullKey());
assertFalse(dpm.validate(new PfValidationResult()).isValid());
@@ -102,7 +87,7 @@ public class PfModelTest {
dpm.getKeyList().clear();
assertTrue(dpm.validate(new PfValidationResult()).isValid());
- PfConceptKey goodCKey = new PfConceptKey("goodCKey", "0.0.1");
+ PfConceptKey goodCKey = new PfConceptKey("goodCKey", VERSION001);
PfReferenceKey goodRKey = new PfReferenceKey(goodCKey, "goodLocalName");
dpm.getKeyList().add(goodCKey);
@@ -129,7 +114,7 @@ public class PfModelTest {
dpm.getKeyList().add(goodRKeyUse);
assertTrue(dpm.validate(new PfValidationResult()).isValid());
- PfConceptKey badCKey = new PfConceptKey("badCKey", "0.0.1");
+ PfConceptKey badCKey = new PfConceptKey("badCKey", VERSION001);
PfKeyUse badCKeyUse = new PfKeyUse(badCKey);
dpm.getKeyList().add(badCKeyUse);
assertFalse(dpm.validate(new PfValidationResult()).isValid());
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java
index 291a7d402..d1ba3a418 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java
@@ -42,37 +42,44 @@ import org.onap.policy.models.base.testconcepts.DummyPfObjectFilter;
*/
public class PfObjectFilterTest {
+ private static final String NAME1 = "name1";
+ private static final String NAME0 = "name0";
+ private static final String HELLO = "Hello";
+ private static final String DESCRIPTION1 = "Desc 1";
+ private static final String VERSION100 = "1.0.0";
+ private static final String VERSION002 = "0.0.2";
+
@Test
public void testPfObjectInterface() {
DummyPfObject do0 = new DummyPfObject();
- do0.setName("name0");
- do0.setVersion("1.0.0");
+ do0.setName(NAME0);
+ do0.setVersion(VERSION100);
do0.setDescription("desc0 ");
DummyPfObject do1 = new DummyPfObject();
- do1.setName("name0");
+ do1.setName(NAME0);
do1.setVersion("0.0.1");
- do1.setDescription("Desc 1");
+ do1.setDescription(DESCRIPTION1);
DummyPfObject do2 = new DummyPfObject();
- do2.setName("name0");
- do2.setVersion("0.0.2");
- do2.setDescription("Desc 1");
+ do2.setName(NAME0);
+ do2.setVersion(VERSION002);
+ do2.setDescription(DESCRIPTION1);
DummyPfObject do3 = new DummyPfObject();
- do3.setName("name1");
+ do3.setName(NAME1);
do3.setVersion("0.0.1");
do3.setDescription("desc0 ");
DummyPfObject do4 = new DummyPfObject();
- do4.setName("name1");
+ do4.setName(NAME1);
do4.setVersion("0.1.2");
- do4.setDescription("Desc 1");
+ do4.setDescription(DESCRIPTION1);
DummyPfObject do5 = new DummyPfObject();
do5.setName("aaaaa");
- do5.setVersion("0.0.2");
- do5.setDescription("Desc 1");
+ do5.setVersion(VERSION002);
+ do5.setDescription(DESCRIPTION1);
List<DummyPfObject> doList = new ArrayList<>();
doList.add(do0);
@@ -83,20 +90,20 @@ public class PfObjectFilterTest {
doList.add(do5);
DummyPfObjectFilter dof = new DummyPfObjectFilter();
- assertFalse(dof.filterString("Hello", "Goodbye"));
- assertTrue(dof.filterString("Hello", "Hello"));
+ assertFalse(dof.filterString(HELLO, "Goodbye"));
+ assertTrue(dof.filterString(HELLO, HELLO));
- assertEquals(false, dof.filterString("Hello", "Goodbye"));
- assertEquals(true, dof.filterString("Hello", "Hello"));
- assertEquals(true, dof.filterString("Hello", null));
+ assertEquals(false, dof.filterString(HELLO, "Goodbye"));
+ assertEquals(true, dof.filterString(HELLO, HELLO));
+ assertEquals(true, dof.filterString(HELLO, null));
List<DummyPfObject> latestVersionList = dof.latestVersionFilter(doList);
assertEquals(3, latestVersionList.size());
assertEquals("aaaaa", latestVersionList.get(0).getName());
- assertEquals("0.0.2", latestVersionList.get(0).getVersion());
- assertEquals("name0", latestVersionList.get(1).getName());
- assertEquals("1.0.0", latestVersionList.get(1).getVersion());
- assertEquals("name1", latestVersionList.get(2).getName());
+ assertEquals(VERSION002, latestVersionList.get(0).getVersion());
+ assertEquals(NAME0, latestVersionList.get(1).getName());
+ assertEquals(VERSION100, latestVersionList.get(1).getVersion());
+ assertEquals(NAME1, latestVersionList.get(2).getName());
assertEquals("0.1.2", latestVersionList.get(2).getVersion());
latestVersionList.remove(2);
@@ -106,17 +113,17 @@ public class PfObjectFilterTest {
MyFilter filter = new MyFilter();
- assertEquals(true, filter.filterString(null, "Hello"));
+ assertEquals(true, filter.filterString(null, HELLO));
DummyPfObject doNullVersion = new DummyPfObject();
do5.setName("bbbbb");
- assertEquals(false, filter(filter::filterStringPred, DummyPfObject::getVersion, doNullVersion, "1.0.0"));
+ assertEquals(false, filter(filter::filterStringPred, DummyPfObject::getVersion, doNullVersion, VERSION100));
assertEquals(false, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, "1"));
assertEquals(false, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, "2.0.0"));
assertEquals(true, filter(filter::filterStringPred, DummyPfObject::getVersion, doNullVersion, null));
assertEquals(true, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, null));
- assertEquals(true, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, "1.0.0"));
+ assertEquals(true, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, VERSION100));
assertEquals(false, filter(filter::filterPrefixPred, DummyPfObject::getVersion, doNullVersion, "1."));
assertEquals(false, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.1"));
@@ -126,7 +133,7 @@ public class PfObjectFilterTest {
assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, null));
assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1."));
assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.0."));
- assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.0.0"));
+ assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, VERSION100));
assertEquals(false, filter(filter::filterRegexpPred, DummyPfObject::getVersion, doNullVersion, "1[.].*"));
assertEquals(false, filter(filter::filterRegexpPred, DummyPfObject::getVersion, do0, "2[.].*"));
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java
index f1d181040..21b82fcf1 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,42 +21,43 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.lang.reflect.Field;
-
import org.junit.Test;
public class PfReferenceKeyTest {
+ private static final String PARENT_LOCAL_NAME = "ParentLocalName";
+ private static final String NPKLN = "NPKLN";
+ private static final String LOCAL_NAME = "LocalName";
+ private static final String VERSION002 = "0.0.2";
+ private static final String VERSION001 = "0.0.1";
+
@Test
public void testPfReferenceKey() {
assertNotNull(new PfReferenceKey());
assertNotNull(new PfReferenceKey(new PfConceptKey()));
- assertNotNull(new PfReferenceKey(new PfConceptKey(), "LocalName"));
+ assertNotNull(new PfReferenceKey(new PfConceptKey(), LOCAL_NAME));
assertNotNull(new PfReferenceKey(new PfReferenceKey()));
- assertNotNull(new PfReferenceKey(new PfReferenceKey(), "LocalName"));
- assertNotNull(new PfReferenceKey(new PfConceptKey(), "ParentLocalName", "LocalName"));
- assertNotNull(new PfReferenceKey("ParentKeyName", "0.0.1", "LocalName"));
- assertNotNull(new PfReferenceKey("ParentKeyName", "0.0.1", "ParentLocalName", "LocalName"));
+ assertNotNull(new PfReferenceKey(new PfReferenceKey(), LOCAL_NAME));
+ assertNotNull(new PfReferenceKey(new PfConceptKey(), PARENT_LOCAL_NAME, LOCAL_NAME));
+ assertNotNull(new PfReferenceKey("ParentKeyName", VERSION001, LOCAL_NAME));
+ assertNotNull(new PfReferenceKey("ParentKeyName", VERSION001, PARENT_LOCAL_NAME, LOCAL_NAME));
assertNotNull(new PfReferenceKey("ParentKeyName:0.0.1:ParentLocalName:LocalName"));
assertEquals(PfReferenceKey.getNullKey().getKey(), PfReferenceKey.getNullKey());
assertEquals("NULL:0.0.0:NULL:NULL", PfReferenceKey.getNullKey().getId());
- try {
- new PfReferenceKey(new PfConceptKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("parameter \"localName\" is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new PfReferenceKey(new PfConceptKey(), null))
+ .hasMessage("parameter \"localName\" is null");
PfReferenceKey testReferenceKey = new PfReferenceKey();
- testReferenceKey.setParentConceptKey(new PfConceptKey("PN", "0.0.1"));
+ testReferenceKey.setParentConceptKey(new PfConceptKey("PN", VERSION001));
assertEquals("PN:0.0.1", testReferenceKey.getParentConceptKey().getId());
assertEquals(0, testReferenceKey.getMajorVersion());
@@ -65,27 +67,23 @@ public class PfReferenceKeyTest {
assertEquals(1, testReferenceKey.getKeys().size());
assertFalse(testReferenceKey.isNullKey());
- testReferenceKey.setParentReferenceKey(new PfReferenceKey("PN", "0.0.1", "LN"));
+ testReferenceKey.setParentReferenceKey(new PfReferenceKey("PN", VERSION001, "LN"));
assertEquals("PN:0.0.1:NULL:LN", testReferenceKey.getParentReferenceKey().getId());
testReferenceKey.setParentKeyName("NPKN");
assertEquals("NPKN", testReferenceKey.getParentKeyName());
- testReferenceKey.setParentKeyVersion("0.0.1");
- assertEquals("0.0.1", testReferenceKey.getParentKeyVersion());
+ testReferenceKey.setParentKeyVersion(VERSION001);
+ assertEquals(VERSION001, testReferenceKey.getParentKeyVersion());
- testReferenceKey.setParentLocalName("NPKLN");
- assertEquals("NPKLN", testReferenceKey.getParentLocalName());
+ testReferenceKey.setParentLocalName(NPKLN);
+ assertEquals(NPKLN, testReferenceKey.getParentLocalName());
testReferenceKey.setLocalName("NLN");
assertEquals("NLN", testReferenceKey.getLocalName());
- try {
- testReferenceKey.isCompatible(null);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("otherKey is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> testReferenceKey.isCompatible(null))
+ .hasMessage("otherKey is marked @NonNull but is null");
assertFalse(testReferenceKey.isCompatible(PfConceptKey.getNullKey()));
assertFalse(testReferenceKey.isCompatible(PfReferenceKey.getNullKey()));
@@ -110,110 +108,85 @@ public class PfReferenceKeyTest {
assertTrue(testReferenceKey.equals(testReferenceKey));
assertTrue(testReferenceKey.equals(clonedReferenceKey));
assertFalse(testReferenceKey.equals("Hello"));
- assertFalse(testReferenceKey.equals(new PfReferenceKey("PKN", "0.0.2", "PLN", "LN")));
- assertFalse(testReferenceKey.equals(new PfReferenceKey("NPKN", "0.0.2", "PLN", "LN")));
- assertFalse(testReferenceKey.equals(new PfReferenceKey("NPKN", "0.0.1", "PLN", "LN")));
- assertFalse(testReferenceKey.equals(new PfReferenceKey("NPKN", "0.0.1", "NPLN", "LN")));
- assertTrue(testReferenceKey.equals(new PfReferenceKey("NPKN", "0.0.1", "NPKLN", "NLN")));
+ assertFalse(testReferenceKey.equals(new PfReferenceKey("PKN", VERSION002, "PLN", "LN")));
+ assertFalse(testReferenceKey.equals(new PfReferenceKey("NPKN", VERSION002, "PLN", "LN")));
+ assertFalse(testReferenceKey.equals(new PfReferenceKey("NPKN", VERSION001, "PLN", "LN")));
+ assertFalse(testReferenceKey.equals(new PfReferenceKey("NPKN", VERSION001, "NPLN", "LN")));
+ assertTrue(testReferenceKey.equals(new PfReferenceKey("NPKN", VERSION001, NPKLN, "NLN")));
assertEquals(0, testReferenceKey.compareTo(testReferenceKey));
assertEquals(0, testReferenceKey.compareTo(clonedReferenceKey));
assertNotEquals(0, testReferenceKey.compareTo(new PfConceptKey()));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("PKN", "0.0.2", "PLN", "LN")));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", "0.0.2", "PLN", "LN")));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", "0.0.1", "PLN", "LN")));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", "0.0.1", "NPLN", "LN")));
- assertEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", "0.0.1", "NPKLN", "NLN")));
+ assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("PKN", VERSION002, "PLN", "LN")));
+ assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION002, "PLN", "LN")));
+ assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION001, "PLN", "LN")));
+ assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION001, "NPLN", "LN")));
+ assertEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION001, NPKLN, "NLN")));
assertFalse(testReferenceKey.equals(null));
- try {
- testReferenceKey.copyTo(null);
- fail("test should throw an exception here");
- } catch (Exception iae) {
- assertEquals("target may not be null", iae.getMessage());
- }
-
- try {
- testReferenceKey.copyTo(new PfConceptKey("Key", "0.0.1"));
- fail("test should throw an exception here");
- } catch (Exception iae) {
- assertEquals("org.onap.policy.models.base.PfConceptKey"
- + " is not an instance of org.onap.policy.models.base.PfReferenceKey", iae.getMessage());
- }
+ assertThatThrownBy(() -> testReferenceKey.copyTo(null)).hasMessage("target may not be null");
+
+ assertThatThrownBy(() -> testReferenceKey.copyTo(new PfConceptKey("Key", VERSION001)))
+ .hasMessage("org.onap.policy.models.base.PfConceptKey"
+ + " is not an instance of org.onap.policy.models.base.PfReferenceKey");
PfReferenceKey targetRefKey = new PfReferenceKey();
assertEquals(testReferenceKey, testReferenceKey.copyTo(targetRefKey));
}
@Test
- public void testValidation() {
+ public void testValidation() throws Exception {
PfReferenceKey testReferenceKey = new PfReferenceKey();
- testReferenceKey.setParentConceptKey(new PfConceptKey("PN", "0.0.1"));
+ testReferenceKey.setParentConceptKey(new PfConceptKey("PN", VERSION001));
assertEquals("PN:0.0.1", testReferenceKey.getParentConceptKey().getId());
- try {
- Field parentNameField = testReferenceKey.getClass().getDeclaredField("parentKeyName");
- parentNameField.setAccessible(true);
- parentNameField.set(testReferenceKey, "Parent Name");
- PfValidationResult validationResult = new PfValidationResult();
- testReferenceKey.validate(validationResult);
- parentNameField.set(testReferenceKey, "ParentName");
- parentNameField.setAccessible(false);
- assertEquals(
- "parentKeyName invalid-parameter parentKeyName with value Parent Name "
- + "does not match regular expression " + PfKey.NAME_REGEXP,
- validationResult.getMessageList().get(0).getMessage());
- } catch (Exception validationException) {
- fail("test should not throw an exception");
- }
-
- try {
- Field parentVersionField = testReferenceKey.getClass().getDeclaredField("parentKeyVersion");
- parentVersionField.setAccessible(true);
- parentVersionField.set(testReferenceKey, "Parent Version");
- PfValidationResult validationResult = new PfValidationResult();
- testReferenceKey.validate(validationResult);
- parentVersionField.set(testReferenceKey, "0.0.1");
- parentVersionField.setAccessible(false);
- assertEquals(
- "parentKeyVersion invalid-parameter parentKeyVersion with value Parent Version "
- + "does not match regular expression " + PfKey.VERSION_REGEXP,
- validationResult.getMessageList().get(0).getMessage());
- } catch (Exception validationException) {
- fail("test should not throw an exception");
- }
-
- try {
- Field parentLocalNameField = testReferenceKey.getClass().getDeclaredField("parentLocalName");
- parentLocalNameField.setAccessible(true);
- parentLocalNameField.set(testReferenceKey, "Parent Local Name");
- PfValidationResult validationResult = new PfValidationResult();
- testReferenceKey.validate(validationResult);
- parentLocalNameField.set(testReferenceKey, "ParentLocalName");
- parentLocalNameField.setAccessible(false);
- assertEquals(
- "parentLocalName invalid-parameter parentLocalName with value "
- + "Parent Local Name does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
- validationResult.getMessageList().get(0).getMessage());
- } catch (Exception validationException) {
- fail("test should not throw an exception");
- }
-
- try {
- Field localNameField = testReferenceKey.getClass().getDeclaredField("localName");
- localNameField.setAccessible(true);
- localNameField.set(testReferenceKey, "Local Name");
- PfValidationResult validationResult = new PfValidationResult();
- testReferenceKey.validate(validationResult);
- localNameField.set(testReferenceKey, "LocalName");
- localNameField.setAccessible(false);
- assertEquals(
- "localName invalid-parameter localName with value Local Name "
- + "does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
- validationResult.getMessageList().get(0).getMessage());
- } catch (Exception validationException) {
- fail("test should not throw an exception");
- }
+ Field parentNameField = testReferenceKey.getClass().getDeclaredField("parentKeyName");
+ parentNameField.setAccessible(true);
+ parentNameField.set(testReferenceKey, "Parent Name");
+ PfValidationResult validationResult = new PfValidationResult();
+ testReferenceKey.validate(validationResult);
+ parentNameField.set(testReferenceKey, "ParentName");
+ parentNameField.setAccessible(false);
+ assertEquals(
+ "parentKeyName invalid-parameter parentKeyName with value Parent Name "
+ + "does not match regular expression " + PfKey.NAME_REGEXP,
+ validationResult.getMessageList().get(0).getMessage());
+
+ Field parentVersionField = testReferenceKey.getClass().getDeclaredField("parentKeyVersion");
+ parentVersionField.setAccessible(true);
+ parentVersionField.set(testReferenceKey, "Parent Version");
+ PfValidationResult validationResult2 = new PfValidationResult();
+ testReferenceKey.validate(validationResult2);
+ parentVersionField.set(testReferenceKey, VERSION001);
+ parentVersionField.setAccessible(false);
+ assertEquals(
+ "parentKeyVersion invalid-parameter parentKeyVersion with value Parent Version "
+ + "does not match regular expression " + PfKey.VERSION_REGEXP,
+ validationResult2.getMessageList().get(0).getMessage());
+
+ Field parentLocalNameField = testReferenceKey.getClass().getDeclaredField("parentLocalName");
+ parentLocalNameField.setAccessible(true);
+ parentLocalNameField.set(testReferenceKey, "Parent Local Name");
+ PfValidationResult validationResult3 = new PfValidationResult();
+ testReferenceKey.validate(validationResult3);
+ parentLocalNameField.set(testReferenceKey, PARENT_LOCAL_NAME);
+ parentLocalNameField.setAccessible(false);
+ assertEquals(
+ "parentLocalName invalid-parameter parentLocalName with value "
+ + "Parent Local Name does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
+ validationResult3.getMessageList().get(0).getMessage());
+
+ Field localNameField = testReferenceKey.getClass().getDeclaredField("localName");
+ localNameField.setAccessible(true);
+ localNameField.set(testReferenceKey, "Local Name");
+ PfValidationResult validationResult4 = new PfValidationResult();
+ testReferenceKey.validate(validationResult4);
+ localNameField.set(testReferenceKey, LOCAL_NAME);
+ localNameField.setAccessible(false);
+ assertEquals(
+ "localName invalid-parameter localName with value Local Name "
+ + "does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
+ validationResult4.getMessageList().get(0).getMessage());
}
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java
index 339ee9d1b..bd55dcd9a 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java
@@ -36,13 +36,15 @@ import org.junit.Test;
*/
public class PfUtilsTest {
+ private static final String HELLO = "hello";
+
@Test
public void testCompareObjects() {
assertEquals(0, PfUtils.compareObjects(null, null));
- assertEquals(-1, PfUtils.compareObjects("hello", null));
- assertEquals(1, PfUtils.compareObjects(null, "hello"));
- assertFalse(PfUtils.compareObjects("hello", "goodbye") == 0);
- assertEquals(0, PfUtils.compareObjects("hello", "hello"));
+ assertEquals(-1, PfUtils.compareObjects(HELLO, null));
+ assertEquals(1, PfUtils.compareObjects(null, HELLO));
+ assertFalse(PfUtils.compareObjects(HELLO, "goodbye") == 0);
+ assertEquals(0, PfUtils.compareObjects(HELLO, HELLO));
}
@Test
diff --git a/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java b/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java
index 391e7333b..120ddbff9 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java
@@ -3,6 +3,7 @@
* ONAP Policy Models
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -35,6 +36,7 @@ import org.junit.Before;
import org.junit.Test;
public class ValidatedTest {
+ private static final String COLLECTION_TEXT = "collection";
private static final String ERROR_MESSAGE = "error message";
private static final String COLLECTION_FIELD = "coll";
private static final String VALID_VALUE = "abc123";
@@ -236,7 +238,7 @@ public class ValidatedTest {
@Test
public void testValidateCollectionNotNull() {
PfValidationResult result = new PfValidationResult();
- result = validated.validateCollectionNotNull(this, "collection", null, result);
+ result = validated.validateCollectionNotNull(this, COLLECTION_TEXT, null, result);
assertTrue(result.isValid());
assertEquals(0, result.getMessageList().size());
@@ -273,7 +275,7 @@ public class ValidatedTest {
@Test
public void testValidateCollection() {
PfValidationResult result = new PfValidationResult();
- result = validated.validateCollection(this, "collection", null, result);
+ result = validated.validateCollection(this, COLLECTION_TEXT, null, result);
assertTrue(result.isValid());
assertEquals(0, result.getMessageList().size());
@@ -310,7 +312,7 @@ public class ValidatedTest {
@Test
public void testValidateConceptCollection() {
PfValidationResult result = new PfValidationResult();
- result = validated.validateConceptCollection(this, "collection", null, result);
+ result = validated.validateConceptCollection(this, COLLECTION_TEXT, null, result);
assertTrue(result.isValid());
assertEquals(0, result.getMessageList().size());
diff --git a/models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java b/models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java
index 0d4f2a7ee..ef0d8d609 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -30,6 +31,9 @@ import org.onap.policy.models.base.PfValidationResult.ValidationResult;
public class ValidationTest {
+ private static final String HELLO = "hello";
+ private static final String SOME_MESSAGE = "Some message";
+
@Test
public void test() {
PfValidationResult result = new PfValidationResult();
@@ -43,47 +47,47 @@ public class ValidationTest {
assertNotNull(result.getMessageList());
PfValidationMessage vmess0 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.VALID, "Some message");
+ ValidationResult.VALID, SOME_MESSAGE);
result.addValidationMessage(vmess0);
assertTrue(result.isOk());
assertTrue(result.isValid());
assertEquals(PfValidationResult.ValidationResult.VALID, result.getValidationResult());
assertNotNull(result.getMessageList());
- assertNotNull("hello", result.toString());
+ assertNotNull(HELLO, result.toString());
PfValidationMessage vmess1 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.OBSERVATION, "Some message");
+ ValidationResult.OBSERVATION, SOME_MESSAGE);
result.addValidationMessage(vmess1);
assertTrue(result.isOk());
assertTrue(result.isValid());
assertEquals(PfValidationResult.ValidationResult.OBSERVATION, result.getValidationResult());
assertNotNull(result.getMessageList());
- assertNotNull("hello", result.toString());
+ assertNotNull(HELLO, result.toString());
PfValidationMessage vmess2 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.WARNING, "Some message");
+ ValidationResult.WARNING, SOME_MESSAGE);
result.addValidationMessage(vmess2);
assertFalse(result.isOk());
assertTrue(result.isValid());
assertEquals(PfValidationResult.ValidationResult.WARNING, result.getValidationResult());
assertNotNull(result.getMessageList());
- assertNotNull("hello", result.toString());
+ assertNotNull(HELLO, result.toString());
PfValidationMessage vmess3 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.INVALID, "Some message");
+ ValidationResult.INVALID, SOME_MESSAGE);
result.addValidationMessage(vmess3);
assertFalse(result.isOk());
assertFalse(result.isValid());
assertEquals(PfValidationResult.ValidationResult.INVALID, result.getValidationResult());
assertNotNull(result.getMessageList());
- assertNotNull("hello", result.toString());
+ assertNotNull(HELLO, result.toString());
assertEquals(PfValidationResult.ValidationResult.INVALID, result.getMessageList().get(3).getValidationResult());
- assertEquals("Some message", result.getMessageList().get(3).getMessage());
+ assertEquals(SOME_MESSAGE, result.getMessageList().get(3).getMessage());
assertEquals(PfConceptKey.class.getCanonicalName(), result.getMessageList().get(3).getObservedClass());
assertEquals(PfConceptKey.getNullKey(), result.getMessageList().get(3).getObservedKey());
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java
index 5e74fb2f9..6cb44e6b5 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -48,23 +49,6 @@ public class DummyPfConcept extends PfConcept implements PfAuthorative<DummyAuth
private String description;
- @Override
- public DummyAuthorativeConcept toAuthorative() {
- DummyAuthorativeConcept dac = new DummyAuthorativeConcept();
- dac.setName(key.getName());
- dac.setVersion(key.getVersion());
- dac.setDescription(description);
-
- return dac;
- }
-
- @Override
- public void fromAuthorative(DummyAuthorativeConcept dac) {
- key.setName(dac.getName());
- key.setVersion(dac.getVersion());
- description = dac.getDescription();
- }
-
/**
* The Default Constructor creates a {@link DummyPfConcept} object with a null key.
*/
@@ -91,9 +75,25 @@ public class DummyPfConcept extends PfConcept implements PfAuthorative<DummyAuth
}
@Override
+ public DummyAuthorativeConcept toAuthorative() {
+ DummyAuthorativeConcept dac = new DummyAuthorativeConcept();
+ dac.setName(key.getName());
+ dac.setVersion(key.getVersion());
+ dac.setDescription(description);
+
+ return dac;
+ }
+
+ @Override
+ public void fromAuthorative(DummyAuthorativeConcept dac) {
+ key.setName(dac.getName());
+ key.setVersion(dac.getVersion());
+ description = dac.getDescription();
+ }
+
+ @Override
public List<PfKey> getKeys() {
- final List<PfKey> keyList = getKey().getKeys();
- return keyList;
+ return getKey().getKeys();
}
@Override
diff --git a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java
index f485b0d0f..944c1e602 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -74,7 +75,7 @@ public class DummyPfKey extends PfKey {
@Override
public void clean() {
-
+ // nothing to do
}
@Override
@@ -84,7 +85,7 @@ public class DummyPfKey extends PfKey {
@Override
public String toString() {
- return null;
+ return "";
}
@Override
diff --git a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java
index 199a37f59..4a30f593f 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -50,7 +51,7 @@ public class DummyPfModel extends PfModel {
public DummyPfModel() {
super();
super.setKey(new PfConceptKey());
- this.keyList = new ArrayList<PfKey>();
+ this.keyList = new ArrayList<>();
}
/**
@@ -61,7 +62,7 @@ public class DummyPfModel extends PfModel {
*/
public DummyPfModel(final PfConceptKey key) {
super(key);
- this.keyList = new ArrayList<PfKey>();
+ this.keyList = new ArrayList<>();
}
/**
@@ -86,6 +87,7 @@ public class DummyPfModel extends PfModel {
@Override
public void register() {
+ // nothing to do
}
@Override
diff --git a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfNameVersion.java b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfNameVersion.java
index 23179d7de..792ac3c06 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfNameVersion.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfNameVersion.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -31,6 +32,6 @@ import org.onap.policy.models.base.PfNameVersion;
*/
@Data
public class DummyPfNameVersion implements PfNameVersion {
- public String name;
- public String version;
+ private String name;
+ private String version;
}
diff --git a/models-dao/src/test/java/org/onap/policy/models/dao/DaoMiscTest.java b/models-dao/src/test/java/org/onap/policy/models/dao/DaoMiscTest.java
index 4dd70cee9..419714924 100644
--- a/models-dao/src/test/java/org/onap/policy/models/dao/DaoMiscTest.java
+++ b/models-dao/src/test/java/org/onap/policy/models/dao/DaoMiscTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,20 +21,19 @@
package org.onap.policy.models.dao;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import java.util.Properties;
-
import org.junit.Test;
-import org.onap.policy.models.dao.DaoParameters;
-import org.onap.policy.models.dao.PfDaoFactory;
import org.onap.policy.models.dao.converters.CDataConditioner;
import org.onap.policy.models.dao.converters.Uuid2String;
public class DaoMiscTest {
+ private static final String SOMEWHERE_OVER_THE_RAINBOW = "somewhere.over.the.rainbow";
+
@Test
public void testUuid2StringMopUp() {
final Uuid2String uuid2String = new Uuid2String();
@@ -49,23 +49,13 @@ public class DaoMiscTest {
public void testDaoFactory() {
final DaoParameters daoParameters = new DaoParameters();
- daoParameters.setPluginClass("somewhere.over.the.rainbow");
- try {
- new PfDaoFactory().createPfDao(daoParameters);
- fail("test shold throw an exception here");
- } catch (final Exception e) {
- assertEquals("Policy Framework DAO class not found for DAO plugin \"somewhere.over.the.rainbow\"",
- e.getMessage());
- }
+ daoParameters.setPluginClass(SOMEWHERE_OVER_THE_RAINBOW);
+ assertThatThrownBy(() -> new PfDaoFactory().createPfDao(daoParameters)).hasMessage(
+ "Policy Framework DAO class not found for DAO plugin \"somewhere.over.the.rainbow\"");
daoParameters.setPluginClass("java.lang.String");
- try {
- new PfDaoFactory().createPfDao(daoParameters);
- fail("test shold throw an exception here");
- } catch (final Exception e) {
- assertEquals("Specified DAO plugin class \"java.lang.String\" " + "does not implement the PfDao interface",
- e.getMessage());
- }
+ assertThatThrownBy(() -> new PfDaoFactory().createPfDao(daoParameters)).hasMessage(
+ "Specified DAO plugin class \"java.lang.String\" " + "does not implement the PfDao interface");
}
@Test
@@ -80,8 +70,8 @@ public class DaoMiscTest {
pars.setPersistenceUnit("Kansas");
assertEquals("Kansas", pars.getPersistenceUnit());
- pars.setPluginClass("somewhere.over.the.rainbow");
- assertEquals("somewhere.over.the.rainbow", pars.getPluginClass());
+ pars.setPluginClass(SOMEWHERE_OVER_THE_RAINBOW);
+ assertEquals(SOMEWHERE_OVER_THE_RAINBOW, pars.getPluginClass());
assertEquals("DAOParameters [pluginClass=somewhere.over.the.rainbow, "
+ "persistenceUnit=Kansas, jdbcProperties={name=Dorothy}]", pars.toString());
diff --git a/models-dao/src/test/java/org/onap/policy/models/dao/DummyReferenceEntity.java b/models-dao/src/test/java/org/onap/policy/models/dao/DummyReferenceEntity.java
index 044a63dc5..aad2aa5bc 100644
--- a/models-dao/src/test/java/org/onap/policy/models/dao/DummyReferenceEntity.java
+++ b/models-dao/src/test/java/org/onap/policy/models/dao/DummyReferenceEntity.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -116,6 +117,6 @@ public class DummyReferenceEntity extends PfConcept {
final DummyReferenceEntity other = (DummyReferenceEntity) otherObj;
- return new Double(doubleValue).compareTo(new Double(other.doubleValue));
+ return Double.compare(doubleValue, other.doubleValue);
}
}
diff --git a/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java b/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java
index 74d06369a..e7a505d1f 100644
--- a/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java
+++ b/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,11 +21,11 @@
package org.onap.policy.models.dao;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
@@ -32,21 +33,27 @@ import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
-
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.base.PfReferenceKey;
-import org.onap.policy.models.dao.DaoParameters;
-import org.onap.policy.models.dao.PfDao;
-import org.onap.policy.models.dao.PfDaoFactory;
import org.onap.policy.models.dao.impl.DefaultPfDao;
/**
* JUnit test class.
*/
public class EntityTest {
+ private static final String DESCRIPTION2 = "key description 2";
+ private static final String DESCRIPTION1 = "key description 1";
+ private static final String DESCRIPTION0 = "key description 0";
+ private static final String ENTITY0 = "Entity0";
+ private static final String UUID2 = "00000000-0000-0000-0000-000000000002";
+ private static final String UUID1 = "00000000-0000-0000-0000-000000000001";
+ private static final String UUID0 = "00000000-0000-0000-0000-000000000000";
+ private static final String VERSION003 = "0.0.3";
+ private static final String VERSION002 = "0.0.2";
+ private static final String VERSION001 = "0.0.1";
private PfDao pfDao;
@Test
@@ -65,34 +72,20 @@ public class EntityTest {
pfDao = new PfDaoFactory().createPfDao(daoParameters);
- try {
- pfDao.init(null);
- fail("Test should throw an exception here");
- } catch (final Exception e) {
- assertEquals("Policy Framework persistence unit parameter not set", e.getMessage());
- }
+ assertThatThrownBy(() -> pfDao.init(null)).hasMessage("Policy Framework persistence unit parameter not set");
- try {
- pfDao.init(daoParameters);
- fail("Test should throw an exception here");
- } catch (final Exception e) {
- assertEquals("Policy Framework persistence unit parameter not set", e.getMessage());
- }
+ assertThatThrownBy(() -> pfDao.init(daoParameters))
+ .hasMessage("Policy Framework persistence unit parameter not set");
daoParameters.setPluginClass("somewhere.over.the.rainbow");
daoParameters.setPersistenceUnit("Dorothy");
- try {
- pfDao.init(daoParameters);
- fail("Test should throw an exception here");
- } catch (final Exception e) {
- assertEquals("Creation of Policy Framework persistence unit \"Dorothy\" failed", e.getMessage());
- }
- try {
- pfDao.create(new PfConceptKey());
- fail("Test should throw an exception here");
- } catch (final Exception e) {
- assertEquals("Policy Framework DAO has not been initialized", e.getMessage());
- }
+
+ assertThatThrownBy(() -> pfDao.init(daoParameters))
+ .hasMessage("Creation of Policy Framework persistence unit \"Dorothy\" failed");
+
+ assertThatThrownBy(() -> pfDao.create(new PfConceptKey()))
+ .hasMessage("Policy Framework DAO has not been initialized");
+
pfDao.close();
}
@@ -167,15 +160,15 @@ public class EntityTest {
}
private void testAllOps() {
- final PfConceptKey aKey0 = new PfConceptKey("A-KEY0", "0.0.1");
- final PfConceptKey aKey1 = new PfConceptKey("A-KEY1", "0.0.1");
- final PfConceptKey aKey2 = new PfConceptKey("A-KEY2", "0.0.1");
+ final PfConceptKey aKey0 = new PfConceptKey("A-KEY0", VERSION001);
+ final PfConceptKey aKey1 = new PfConceptKey("A-KEY1", VERSION001);
+ final PfConceptKey aKey2 = new PfConceptKey("A-KEY2", VERSION001);
final DummyConceptEntity keyInfo0 = new DummyConceptEntity(aKey0,
- UUID.fromString("00000000-0000-0000-0000-000000000000"), "key description 0");
+ UUID.fromString(UUID0), DESCRIPTION0);
final DummyConceptEntity keyInfo1 = new DummyConceptEntity(aKey1,
- UUID.fromString("00000000-0000-0000-0000-000000000001"), "key description 1");
+ UUID.fromString(UUID1), DESCRIPTION1);
final DummyConceptEntity keyInfo2 = new DummyConceptEntity(aKey2,
- UUID.fromString("00000000-0000-0000-0000-000000000002"), "key description 2");
+ UUID.fromString(UUID2), DESCRIPTION2);
pfDao.create(keyInfo0);
@@ -189,69 +182,69 @@ public class EntityTest {
assertTrue(keyInfoBack0.equals(keyInfoBack1));
final DummyConceptEntity keyInfoBack2 =
- pfDao.getConcept(DummyConceptEntity.class, new PfConceptKey("A-KEY3", "0.0.1"));
+ pfDao.getConcept(DummyConceptEntity.class, new PfConceptKey("A-KEY3", VERSION001));
assertNull(keyInfoBack2);
- final Set<DummyConceptEntity> keyInfoSetIn = new TreeSet<DummyConceptEntity>();
+ final Set<DummyConceptEntity> keyInfoSetIn = new TreeSet<>();
keyInfoSetIn.add(keyInfo1);
keyInfoSetIn.add(keyInfo2);
pfDao.createCollection(keyInfoSetIn);
- Set<DummyConceptEntity> keyInfoSetOut = new TreeSet<DummyConceptEntity>(pfDao.getAll(DummyConceptEntity.class));
+ Set<DummyConceptEntity> keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class));
keyInfoSetIn.add(keyInfo0);
assertTrue(keyInfoSetIn.equals(keyInfoSetOut));
pfDao.delete(keyInfo1);
keyInfoSetIn.remove(keyInfo1);
- keyInfoSetOut = new TreeSet<DummyConceptEntity>(pfDao.getAll(DummyConceptEntity.class));
+ keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class));
assertTrue(keyInfoSetIn.equals(keyInfoSetOut));
pfDao.deleteCollection(keyInfoSetIn);
- keyInfoSetOut = new TreeSet<DummyConceptEntity>(pfDao.getAll(DummyConceptEntity.class));
+ keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class));
assertEquals(0, keyInfoSetOut.size());
keyInfoSetIn.add(keyInfo0);
keyInfoSetIn.add(keyInfo1);
keyInfoSetIn.add(keyInfo0);
pfDao.createCollection(keyInfoSetIn);
- keyInfoSetOut = new TreeSet<DummyConceptEntity>(pfDao.getAll(DummyConceptEntity.class));
+ keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class));
assertTrue(keyInfoSetIn.equals(keyInfoSetOut));
pfDao.delete(DummyConceptEntity.class, aKey0);
- keyInfoSetOut = new TreeSet<DummyConceptEntity>(pfDao.getAll(DummyConceptEntity.class));
+ keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class));
assertEquals(2, keyInfoSetOut.size());
assertEquals(2, pfDao.size(DummyConceptEntity.class));
- final Set<PfConceptKey> keySetIn = new TreeSet<PfConceptKey>();
+ final Set<PfConceptKey> keySetIn = new TreeSet<>();
keySetIn.add(aKey1);
keySetIn.add(aKey2);
final int deletedCount = pfDao.deleteByConceptKey(DummyConceptEntity.class, keySetIn);
assertEquals(2, deletedCount);
- keyInfoSetOut = new TreeSet<DummyConceptEntity>(pfDao.getAll(DummyConceptEntity.class));
+ keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class));
assertEquals(0, keyInfoSetOut.size());
keyInfoSetIn.add(keyInfo0);
keyInfoSetIn.add(keyInfo1);
keyInfoSetIn.add(keyInfo0);
pfDao.createCollection(keyInfoSetIn);
- keyInfoSetOut = new TreeSet<DummyConceptEntity>(pfDao.getAll(DummyConceptEntity.class));
+ keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class));
assertTrue(keyInfoSetIn.equals(keyInfoSetOut));
pfDao.deleteAll(DummyConceptEntity.class);
assertEquals(0, pfDao.size(DummyConceptEntity.class));
- final PfConceptKey owner0Key = new PfConceptKey("Owner0", "0.0.1");
- final PfConceptKey owner1Key = new PfConceptKey("Owner1", "0.0.1");
- final PfConceptKey owner2Key = new PfConceptKey("Owner2", "0.0.1");
- final PfConceptKey owner3Key = new PfConceptKey("Owner3", "0.0.1");
- final PfConceptKey owner4Key = new PfConceptKey("Owner4", "0.0.1");
- final PfConceptKey owner5Key = new PfConceptKey("Owner5", "0.0.1");
+ final PfConceptKey owner0Key = new PfConceptKey("Owner0", VERSION001);
+ final PfConceptKey owner1Key = new PfConceptKey("Owner1", VERSION001);
+ final PfConceptKey owner2Key = new PfConceptKey("Owner2", VERSION001);
+ final PfConceptKey owner3Key = new PfConceptKey("Owner3", VERSION001);
+ final PfConceptKey owner4Key = new PfConceptKey("Owner4", VERSION001);
+ final PfConceptKey owner5Key = new PfConceptKey("Owner5", VERSION001);
- pfDao.create(new DummyReferenceEntity(new PfReferenceKey(owner0Key, "Entity0"), 100.0));
+ pfDao.create(new DummyReferenceEntity(new PfReferenceKey(owner0Key, ENTITY0), 100.0));
pfDao.create(new DummyReferenceEntity(new PfReferenceKey(owner0Key, "Entity1"), 101.0));
pfDao.create(new DummyReferenceEntity(new PfReferenceKey(owner0Key, "Entity2"), 102.0));
pfDao.create(new DummyReferenceEntity(new PfReferenceKey(owner0Key, "Entity3"), 103.0));
@@ -269,34 +262,34 @@ public class EntityTest {
pfDao.create(new DummyReferenceEntity(new PfReferenceKey(owner5Key, "EntityF"), 115.0));
TreeSet<DummyReferenceEntity> testEntitySetOut =
- new TreeSet<DummyReferenceEntity>(pfDao.getAll(DummyReferenceEntity.class));
+ new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class));
assertEquals(16, testEntitySetOut.size());
- testEntitySetOut = new TreeSet<DummyReferenceEntity>(pfDao.getAll(DummyReferenceEntity.class, owner0Key));
+ testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner0Key));
assertEquals(5, testEntitySetOut.size());
- testEntitySetOut = new TreeSet<DummyReferenceEntity>(pfDao.getAll(DummyReferenceEntity.class, owner1Key));
+ testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner1Key));
assertEquals(3, testEntitySetOut.size());
- testEntitySetOut = new TreeSet<DummyReferenceEntity>(pfDao.getAll(DummyReferenceEntity.class, owner2Key));
+ testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner2Key));
assertEquals(2, testEntitySetOut.size());
- testEntitySetOut = new TreeSet<DummyReferenceEntity>(pfDao.getAll(DummyReferenceEntity.class, owner3Key));
+ testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner3Key));
assertEquals(1, testEntitySetOut.size());
- testEntitySetOut = new TreeSet<DummyReferenceEntity>(pfDao.getAll(DummyReferenceEntity.class, owner4Key));
+ testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner4Key));
assertEquals(1, testEntitySetOut.size());
- testEntitySetOut = new TreeSet<DummyReferenceEntity>(pfDao.getAll(DummyReferenceEntity.class, owner5Key));
+ testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner5Key));
assertEquals(4, testEntitySetOut.size());
- assertNotNull(pfDao.get(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, "Entity0")));
- assertNotNull(pfDao.getConcept(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, "Entity0")));
+ assertNotNull(pfDao.get(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, ENTITY0)));
+ assertNotNull(pfDao.getConcept(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, ENTITY0)));
assertNull(pfDao.get(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, "Entity1000")));
assertNull(pfDao.getConcept(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, "Entity1000")));
- pfDao.delete(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, "Entity0"));
+ pfDao.delete(DummyReferenceEntity.class, new PfReferenceKey(owner0Key, ENTITY0));
- final Set<PfReferenceKey> rKeySetIn = new TreeSet<PfReferenceKey>();
+ final Set<PfReferenceKey> rKeySetIn = new TreeSet<>();
rKeySetIn.add(new PfReferenceKey(owner4Key, "EntityB"));
rKeySetIn.add(new PfReferenceKey(owner5Key, "EntityD"));
@@ -307,24 +300,24 @@ public class EntityTest {
}
private void testVersionOps() {
- final PfConceptKey aKey0 = new PfConceptKey("AAA0", "0.0.1");
- final PfConceptKey aKey1 = new PfConceptKey("AAA0", "0.0.2");
- final PfConceptKey aKey2 = new PfConceptKey("AAA0", "0.0.3");
- final PfConceptKey bKey0 = new PfConceptKey("BBB0", "0.0.1");
- final PfConceptKey bKey1 = new PfConceptKey("BBB0", "0.0.2");
- final PfConceptKey bKey2 = new PfConceptKey("BBB0", "0.0.3");
+ final PfConceptKey aKey0 = new PfConceptKey("AAA0", VERSION001);
+ final PfConceptKey aKey1 = new PfConceptKey("AAA0", VERSION002);
+ final PfConceptKey aKey2 = new PfConceptKey("AAA0", VERSION003);
+ final PfConceptKey bKey0 = new PfConceptKey("BBB0", VERSION001);
+ final PfConceptKey bKey1 = new PfConceptKey("BBB0", VERSION002);
+ final PfConceptKey bKey2 = new PfConceptKey("BBB0", VERSION003);
final DummyConceptEntity keyInfo0 = new DummyConceptEntity(aKey0,
- UUID.fromString("00000000-0000-0000-0000-000000000000"), "key description 0");
+ UUID.fromString(UUID0), DESCRIPTION0);
final DummyConceptEntity keyInfo1 = new DummyConceptEntity(aKey1,
- UUID.fromString("00000000-0000-0000-0000-000000000001"), "key description 1");
+ UUID.fromString(UUID1), DESCRIPTION1);
final DummyConceptEntity keyInfo2 = new DummyConceptEntity(aKey2,
- UUID.fromString("00000000-0000-0000-0000-000000000002"), "key description 2");
+ UUID.fromString(UUID2), DESCRIPTION2);
final DummyConceptEntity keyInfo3 = new DummyConceptEntity(bKey0,
- UUID.fromString("00000000-0000-0000-0000-000000000000"), "key description 0");
+ UUID.fromString(UUID0), DESCRIPTION0);
final DummyConceptEntity keyInfo4 = new DummyConceptEntity(bKey1,
- UUID.fromString("00000000-0000-0000-0000-000000000001"), "key description 1");
+ UUID.fromString(UUID1), DESCRIPTION1);
final DummyConceptEntity keyInfo5 = new DummyConceptEntity(bKey2,
- UUID.fromString("00000000-0000-0000-0000-000000000002"), "key description 2");
+ UUID.fromString(UUID2), DESCRIPTION2);
pfDao.create(keyInfo0);
pfDao.create(keyInfo1);
@@ -339,24 +332,24 @@ public class EntityTest {
}
private void testgetFilteredOps() {
- final PfConceptKey aKey0 = new PfConceptKey("AAA0", "0.0.1");
- final PfConceptKey aKey1 = new PfConceptKey("AAA0", "0.0.2");
- final PfConceptKey aKey2 = new PfConceptKey("AAA0", "0.0.3");
- final PfConceptKey bKey0 = new PfConceptKey("BBB0", "0.0.1");
- final PfConceptKey bKey1 = new PfConceptKey("BBB0", "0.0.2");
- final PfConceptKey bKey2 = new PfConceptKey("BBB0", "0.0.3");
+ final PfConceptKey aKey0 = new PfConceptKey("AAA0", VERSION001);
+ final PfConceptKey aKey1 = new PfConceptKey("AAA0", VERSION002);
+ final PfConceptKey aKey2 = new PfConceptKey("AAA0", VERSION003);
+ final PfConceptKey bKey0 = new PfConceptKey("BBB0", VERSION001);
+ final PfConceptKey bKey1 = new PfConceptKey("BBB0", VERSION002);
+ final PfConceptKey bKey2 = new PfConceptKey("BBB0", VERSION003);
final DummyConceptEntity keyInfo0 = new DummyConceptEntity(aKey0,
- UUID.fromString("00000000-0000-0000-0000-000000000000"), "key description 0");
+ UUID.fromString(UUID0), DESCRIPTION0);
final DummyConceptEntity keyInfo1 = new DummyConceptEntity(aKey1,
- UUID.fromString("00000000-0000-0000-0000-000000000001"), "key description 1");
+ UUID.fromString(UUID1), DESCRIPTION1);
final DummyConceptEntity keyInfo2 = new DummyConceptEntity(aKey2,
- UUID.fromString("00000000-0000-0000-0000-000000000002"), "key description 2");
+ UUID.fromString(UUID2), DESCRIPTION2);
final DummyConceptEntity keyInfo3 = new DummyConceptEntity(bKey0,
- UUID.fromString("00000000-0000-0000-0000-000000000000"), "key description 0");
+ UUID.fromString(UUID0), DESCRIPTION0);
final DummyConceptEntity keyInfo4 = new DummyConceptEntity(bKey1,
- UUID.fromString("00000000-0000-0000-0000-000000000001"), "key description 1");
+ UUID.fromString(UUID1), DESCRIPTION1);
final DummyConceptEntity keyInfo5 = new DummyConceptEntity(bKey2,
- UUID.fromString("00000000-0000-0000-0000-000000000002"), "key description 2");
+ UUID.fromString(UUID2), DESCRIPTION2);
pfDao.create(keyInfo0);
pfDao.create(keyInfo1);
@@ -368,7 +361,7 @@ public class EntityTest {
assertEquals(6, pfDao.getFiltered(DummyConceptEntity.class, null, null).size());
assertEquals(3, pfDao.getFiltered(DummyConceptEntity.class, "AAA0", null).size());
assertEquals(3, pfDao.getFiltered(DummyConceptEntity.class, "BBB0", null).size());
- assertEquals(1, pfDao.getFiltered(DummyConceptEntity.class, "BBB0", "0.0.3").size());
- assertEquals(6, pfDao.getFiltered(DummyConceptEntity.class, null, "0.0.3").size());
+ assertEquals(1, pfDao.getFiltered(DummyConceptEntity.class, "BBB0", VERSION003).size());
+ assertEquals(6, pfDao.getFiltered(DummyConceptEntity.class, null, VERSION003).size());
}
}
diff --git a/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseInfo.java b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseInfo.java
index ed7104b04..70ebbef33 100644
--- a/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseInfo.java
+++ b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseInfo.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -25,6 +26,7 @@ package org.onap.policy.models.errors.concepts;
*
* @author Liam Fallon (liam.fallon@est.tech)
*/
+@FunctionalInterface
public interface ErrorResponseInfo {
/**
diff --git a/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java
index b917406cd..553dfde9b 100644
--- a/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java
+++ b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java
@@ -24,12 +24,10 @@ package org.onap.policy.controlloop.actor.appc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.time.Instant;
import java.util.HashMap;
import java.util.UUID;
-
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -51,6 +49,12 @@ import org.slf4j.LoggerFactory;
public class AppcServiceProviderTest {
+ private static final String GENERIC_VNF_ID = "generic-vnf.vnf-id";
+
+ private static final String MODIFY_CONFIG = "ModifyConfig";
+
+ private static final String JSON_OUTPUT = "JSON Output: \n";
+
private static final Logger logger = LoggerFactory.getLogger(AppcServiceProviderTest.class);
private static final VirtualControlLoopEvent onsetEvent;
@@ -85,7 +89,7 @@ public class AppcServiceProviderTest {
/* Construct an operation with an APPC actor and ModifyConfig operation. */
operation = new ControlLoopOperation();
operation.setActor("APPC");
- operation.setOperation("ModifyConfig");
+ operation.setOperation(MODIFY_CONFIG);
operation.setTarget("VNF");
operation.setEnd(Instant.now());
operation.setSubRequestId("1");
@@ -97,7 +101,7 @@ public class AppcServiceProviderTest {
policy.setActor("APPC");
policy.setTarget(new Target(TargetType.VNF));
policy.getTarget().setResourceID("Eace933104d443b496b8.nodes.heat.vpg");
- policy.setRecipe("ModifyConfig");
+ policy.setRecipe(MODIFY_CONFIG);
policy.setPayload(null);
policy.setRetry(2);
policy.setTimeout(300);
@@ -106,14 +110,11 @@ public class AppcServiceProviderTest {
/**
* Set up before test class.
+ * @throws Exception if the A&AI simulator cannot be started
*/
@BeforeClass
- public static void setUpSimulator() {
- try {
- Util.buildAaiSim();
- } catch (Exception e) {
- fail(e.getMessage());
- }
+ public static void setUpSimulator() throws Exception {
+ Util.buildAaiSim();
}
/**
@@ -142,12 +143,12 @@ public class AppcServiceProviderTest {
/* An action is required and cannot be null */
assertNotNull(appcRequest.getAction());
- assertEquals("ModifyConfig", appcRequest.getAction());
+ assertEquals(MODIFY_CONFIG, appcRequest.getAction());
/* A payload is required and cannot be null */
assertNotNull(appcRequest.getPayload());
- assertTrue(appcRequest.getPayload().containsKey("generic-vnf.vnf-id"));
- assertNotNull(appcRequest.getPayload().get("generic-vnf.vnf-id"));
+ assertTrue(appcRequest.getPayload().containsKey(GENERIC_VNF_ID));
+ assertNotNull(appcRequest.getPayload().get(GENERIC_VNF_ID));
assertTrue(appcRequest.getPayload().containsKey(KEY1));
assertTrue(appcRequest.getPayload().containsKey(KEY2));
@@ -155,14 +156,14 @@ public class AppcServiceProviderTest {
/* Print out request as json to make sure serialization works */
String jsonRequest = Serialization.gsonPretty.toJson(appcRequest);
- logger.debug("JSON Output: \n" + jsonRequest);
+ logger.debug(JSON_OUTPUT + jsonRequest);
/* The JSON string must contain the following fields */
assertTrue(jsonRequest.contains("CommonHeader"));
assertTrue(jsonRequest.contains("Action"));
- assertTrue(jsonRequest.contains("ModifyConfig"));
+ assertTrue(jsonRequest.contains(MODIFY_CONFIG));
assertTrue(jsonRequest.contains("Payload"));
- assertTrue(jsonRequest.contains("generic-vnf.vnf-id"));
+ assertTrue(jsonRequest.contains(GENERIC_VNF_ID));
assertTrue(jsonRequest.contains(KEY1));
assertTrue(jsonRequest.contains(KEY2));
assertTrue(jsonRequest.contains(SUBKEY));
@@ -173,7 +174,7 @@ public class AppcServiceProviderTest {
appcResponse.getStatus().setDescription("AppC success");
/* Print out request as json to make sure serialization works */
String jsonResponse = Serialization.gsonPretty.toJson(appcResponse);
- logger.debug("JSON Output: \n" + jsonResponse);
+ logger.debug(JSON_OUTPUT + jsonResponse);
}
@Test
@@ -191,32 +192,32 @@ public class AppcServiceProviderTest {
/* An action is required and cannot be null */
assertNotNull(appcRequest.getAction());
- assertEquals("ModifyConfig", appcRequest.getAction());
+ assertEquals(MODIFY_CONFIG, appcRequest.getAction());
/* A payload is required and cannot be null */
assertNotNull(appcRequest.getPayload());
- assertTrue(appcRequest.getPayload().containsKey("generic-vnf.vnf-id"));
- assertNotNull(appcRequest.getPayload().get("generic-vnf.vnf-id"));
+ assertTrue(appcRequest.getPayload().containsKey(GENERIC_VNF_ID));
+ assertNotNull(appcRequest.getPayload().get(GENERIC_VNF_ID));
logger.debug("APPC Request: \n" + appcRequest.toString());
/* Print out request as json to make sure serialization works */
String jsonRequest = Serialization.gsonPretty.toJson(appcRequest);
- logger.debug("JSON Output: \n" + jsonRequest);
+ logger.debug(JSON_OUTPUT + jsonRequest);
/* The JSON string must contain the following fields */
assertTrue(jsonRequest.contains("CommonHeader"));
assertTrue(jsonRequest.contains("Action"));
- assertTrue(jsonRequest.contains("ModifyConfig"));
+ assertTrue(jsonRequest.contains(MODIFY_CONFIG));
assertTrue(jsonRequest.contains("Payload"));
- assertTrue(jsonRequest.contains("generic-vnf.vnf-id"));
+ assertTrue(jsonRequest.contains(GENERIC_VNF_ID));
Response appcResponse = new Response(appcRequest);
appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue());
appcResponse.getStatus().setDescription("AppC success");
/* Print out request as json to make sure serialization works */
String jsonResponse = Serialization.gsonPretty.toJson(appcResponse);
- logger.debug("JSON Output: \n" + jsonResponse);
+ logger.debug(JSON_OUTPUT + jsonResponse);
}
@Test
diff --git a/models-interactions/model-actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProviderTest.java b/models-interactions/model-actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProviderTest.java
index da95611d4..7b48387a4 100644
--- a/models-interactions/model-actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProviderTest.java
+++ b/models-interactions/model-actors/actor.appclcm/src/test/java/org/onap/policy/controlloop/actor/appclcm/AppcLcmActorServiceProviderTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* AppcServiceProviderTest
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,17 +24,14 @@ package org.onap.policy.controlloop.actor.appclcm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import java.time.Instant;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.UUID;
-
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.onap.policy.aai.util.AaiException;
import org.onap.policy.appclcm.LcmCommonHeader;
import org.onap.policy.appclcm.LcmRequest;
import org.onap.policy.appclcm.LcmRequestWrapper;
@@ -56,6 +53,16 @@ import org.slf4j.LoggerFactory;
public class AppcLcmActorServiceProviderTest {
+ private static final String VNF01 = "vnf01";
+
+ private static final String VNF_ID_KEY = "vnf-id";
+
+ private static final String REJECT = "REJECT";
+
+ private static final String PARTIAL_FAILURE = "PARTIAL FAILURE";
+
+ private static final String FAILURE = "FAILURE";
+
private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProviderTest.class);
private static final VirtualControlLoopEvent onsetEvent;
@@ -87,7 +94,7 @@ public class AppcLcmActorServiceProviderTest {
/* Construct an operation with an APPC actor and restart operation. */
operation = new ControlLoopOperation();
operation.setActor("APPC");
- operation.setOperation("Restart");
+ operation.setOperation(RECIPE_RESTART);
operation.setTarget("VM");
operation.setEnd(Instant.now());
operation.setSubRequestId("1");
@@ -98,7 +105,7 @@ public class AppcLcmActorServiceProviderTest {
policy.setDescription("Upon getting the trigger event, restart the VM");
policy.setActor("APPC");
policy.setTarget(new Target(TargetType.VNF));
- policy.setRecipe("Restart");
+ policy.setRecipe(RECIPE_RESTART);
policy.setPayload(null);
policy.setRetry(2);
policy.setTimeout(300);
@@ -122,7 +129,7 @@ public class AppcLcmActorServiceProviderTest {
appcRequest.setAction("restart");
HashMap<String, String> actionIdentifiers = new HashMap<>();
- actionIdentifiers.put("vnf-id", "trial-vnf-003");
+ actionIdentifiers.put(VNF_ID_KEY, "trial-vnf-003");
appcRequest.setActionIdentifiers(actionIdentifiers);
@@ -147,14 +154,11 @@ public class AppcLcmActorServiceProviderTest {
/**
* Set up before test class.
+ * @throws Exception if an error occurs
*/
@BeforeClass
- public static void setUpSimulator() {
- try {
- Util.buildAaiSim();
- } catch (Exception e) {
- fail(e.getMessage());
- }
+ public static void setUpSimulator() throws Exception {
+ Util.buildAaiSim();
}
/**
@@ -172,7 +176,7 @@ public class AppcLcmActorServiceProviderTest {
public void constructRestartRequestTest() {
LcmRequestWrapper dmaapRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, policy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, policy, VNF01);
/* The service provider must return a non null DMAAP request wrapper */
assertNotNull(dmaapRequest);
@@ -191,12 +195,12 @@ public class AppcLcmActorServiceProviderTest {
/* An action is required and cannot be null */
assertNotNull(appcRequest.getAction());
- assertEquals("Restart", appcRequest.getAction());
+ assertEquals(RECIPE_RESTART, appcRequest.getAction());
/* Action Identifiers are required and cannot be null */
assertNotNull(appcRequest.getActionIdentifiers());
- assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
- assertEquals("vnf01", appcRequest.getActionIdentifiers().get("vnf-id"));
+ assertNotNull(appcRequest.getActionIdentifiers().get(VNF_ID_KEY));
+ assertEquals(VNF01, appcRequest.getActionIdentifiers().get(VNF_ID_KEY));
logger.debug("APPC Request: \n" + appcRequest.toString());
}
@@ -240,35 +244,35 @@ public class AppcLcmActorServiceProviderTest {
/* If APPC rejects, PolicyResult is failure exception */
dmaapResponse.getBody().getStatus().setCode(300);
- dmaapResponse.getBody().getStatus().setMessage("REJECT");
+ dmaapResponse.getBody().getStatus().setMessage(REJECT);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
/* Test multiple reject codes */
dmaapResponse.getBody().getStatus().setCode(306);
- dmaapResponse.getBody().getStatus().setMessage("REJECT");
+ dmaapResponse.getBody().getStatus().setMessage(REJECT);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
dmaapResponse.getBody().getStatus().setCode(313);
- dmaapResponse.getBody().getStatus().setMessage("REJECT");
+ dmaapResponse.getBody().getStatus().setMessage(REJECT);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
/* If APPC returns failure, PolicyResult is failure */
dmaapResponse.getBody().getStatus().setCode(401);
- dmaapResponse.getBody().getStatus().setMessage("FAILURE");
+ dmaapResponse.getBody().getStatus().setMessage(FAILURE);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE, result.getKey());
/* Test multiple failure codes */
dmaapResponse.getBody().getStatus().setCode(406);
- dmaapResponse.getBody().getStatus().setMessage("FAILURE");
+ dmaapResponse.getBody().getStatus().setMessage(FAILURE);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE, result.getKey());
dmaapResponse.getBody().getStatus().setCode(450);
- dmaapResponse.getBody().getStatus().setMessage("FAILURE");
+ dmaapResponse.getBody().getStatus().setMessage(FAILURE);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE, result.getKey());
@@ -280,18 +284,18 @@ public class AppcLcmActorServiceProviderTest {
/* If APPC returns partial failure, PolicyResult is failure exception */
dmaapResponse.getBody().getStatus().setCode(501);
- dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE");
+ dmaapResponse.getBody().getStatus().setMessage(PARTIAL_FAILURE);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
/* Test multiple partial failure codes */
dmaapResponse.getBody().getStatus().setCode(599);
- dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE");
+ dmaapResponse.getBody().getStatus().setMessage(PARTIAL_FAILURE);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
dmaapResponse.getBody().getStatus().setCode(550);
- dmaapResponse.getBody().getStatus().setMessage("PARTIAL FAILURE");
+ dmaapResponse.getBody().getStatus().setMessage(PARTIAL_FAILURE);
result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
@@ -302,27 +306,21 @@ public class AppcLcmActorServiceProviderTest {
assertEquals(PolicyResult.FAILURE_EXCEPTION, result.getKey());
}
- /**
+ /*
* This test ensures that that if the the source entity is also the target entity, the source
* will be used for the APPC request.
*/
@Test
- public void sourceIsTargetTest() {
+ public void sourceIsTargetTest() throws Exception {
String resourceId = "82194af1-3c2c-485a-8f44-420e22a9eaa4";
- String targetVnfId = null;
- try {
- targetVnfId = AppcLcmActorServiceProvider.vnfNamedQuery(resourceId, "vnf01",
- "http://localhost:6666", "AAI", "AAI");
- } catch (AaiException e) {
- logger.warn(e.toString());
- fail("no vnf-id found");
- }
+ String targetVnfId = AppcLcmActorServiceProvider.vnfNamedQuery(resourceId, VNF01, "http://localhost:6666",
+ "AAI", "AAI");
assertNotNull(targetVnfId);
- assertEquals("vnf01", targetVnfId);
+ assertEquals(VNF01, targetVnfId);
}
- /**
- * THis test exercises getters not exercised in other tests.
+ /*
+ * This test exercises getters not exercised in other tests.
*/
@Test
public void testMethods() {
@@ -330,8 +328,8 @@ public class AppcLcmActorServiceProviderTest {
assertEquals("APPC", sp.actor());
assertEquals(4, sp.recipes().size());
- assertEquals("VM", sp.recipeTargets("Restart").get(0));
- assertEquals("vm-id", sp.recipePayloads("Restart").get(0));
+ assertEquals("VM", sp.recipeTargets(RECIPE_RESTART).get(0));
+ assertEquals("vm-id", sp.recipePayloads(RECIPE_RESTART).get(0));
}
@Test
@@ -343,11 +341,11 @@ public class AppcLcmActorServiceProviderTest {
// when
LcmRequestWrapper migrateRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, migratePolicy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, migratePolicy, VNF01);
LcmRequestWrapper rebuildRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, rebuildPolicy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, rebuildPolicy, VNF01);
LcmRequestWrapper restartRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, restartPolicy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, restartPolicy, VNF01);
// then
assertNull(migrateRequest.getBody().getPayload());
@@ -363,9 +361,9 @@ public class AppcLcmActorServiceProviderTest {
// when
LcmRequestWrapper noPayloadRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, noPayloadPolicy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, noPayloadPolicy, VNF01);
LcmRequestWrapper emptyPayloadRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, emptyPayloadPolicy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, emptyPayloadPolicy, VNF01);
// then
@@ -382,7 +380,7 @@ public class AppcLcmActorServiceProviderTest {
// when
LcmRequestWrapper dmaapRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, otherPolicy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, otherPolicy, VNF01);
// then
assertEquals(dmaapRequest.getBody().getPayload(),
@@ -402,7 +400,7 @@ public class AppcLcmActorServiceProviderTest {
// when
LcmRequestWrapper dmaapRequest =
- AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, otherPolicy, "vnf01");
+ AppcLcmActorServiceProvider.constructRequest(onsetEvent, operation, otherPolicy, VNF01);
// then
assertEquals(dmaapRequest.getBody().getPayload(),
diff --git a/models-interactions/model-actors/actor.sdnc/src/test/java/org/onap/policy/controlloop/actor/sdnc/SdncActorServiceProviderTest.java b/models-interactions/model-actors/actor.sdnc/src/test/java/org/onap/policy/controlloop/actor/sdnc/SdncActorServiceProviderTest.java
index c80a38d77..26f7336d6 100644
--- a/models-interactions/model-actors/actor.sdnc/src/test/java/org/onap/policy/controlloop/actor/sdnc/SdncActorServiceProviderTest.java
+++ b/models-interactions/model-actors/actor.sdnc/src/test/java/org/onap/policy/controlloop/actor/sdnc/SdncActorServiceProviderTest.java
@@ -25,11 +25,9 @@ package org.onap.policy.controlloop.actor.sdnc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import java.util.Objects;
import java.util.UUID;
-
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -42,16 +40,15 @@ import org.onap.policy.simulators.Util;
public class SdncActorServiceProviderTest {
+ private static final String REROUTE = "Reroute";
+
/**
- * Set up for test class.
+ * Set up before test class.
+ * @throws Exception if the A&AI simulator cannot be started
*/
@BeforeClass
- public static void setUpSimulator() {
- try {
- Util.buildAaiSim();
- } catch (Exception e) {
- fail(e.getMessage());
- }
+ public static void setUpSimulator() throws Exception {
+ Util.buildAaiSim();
}
@AfterClass
@@ -65,7 +62,7 @@ public class SdncActorServiceProviderTest {
ControlLoopOperation operation = new ControlLoopOperation();
Policy policy = new Policy();
- policy.setRecipe("Reroute");
+ policy.setRecipe(REROUTE);
SdncActorServiceProvider provider = new SdncActorServiceProvider();
assertNull(provider.constructRequest(onset, operation, policy));
@@ -84,7 +81,7 @@ public class SdncActorServiceProviderTest {
onset.getAai().put("service-instance.service-instance-id", "service-instance-01");
assertNotNull(provider.constructRequest(onset, operation, policy));
- policy.setRecipe("Reroute");
+ policy.setRecipe(REROUTE);
assertNotNull(provider.constructRequest(onset, operation, policy));
SdncRequest request =
@@ -103,8 +100,8 @@ public class SdncActorServiceProviderTest {
assertEquals("SDNC", sp.actor());
assertEquals(1, sp.recipes().size());
- assertEquals("Reroute", sp.recipes().get(0));
- assertEquals("VM", sp.recipeTargets("Reroute").get(0));
- assertEquals(0, sp.recipePayloads("Reroute").size());
+ assertEquals(REROUTE, sp.recipes().get(0));
+ assertEquals("VM", sp.recipeTargets(REROUTE).get(0));
+ assertEquals(0, sp.recipePayloads(REROUTE).size());
}
}
diff --git a/models-interactions/model-actors/actor.sdnr/src/main/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProvider.java b/models-interactions/model-actors/actor.sdnr/src/main/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProvider.java
index 32346bfa2..4367f54c5 100644
--- a/models-interactions/model-actors/actor.sdnr/src/main/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProvider.java
+++ b/models-interactions/model-actors/actor.sdnr/src/main/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProvider.java
@@ -70,7 +70,6 @@ public class SdnrActorServiceProvider implements Actor {
// Strings for recipes
private static final String RECIPE_MODIFY = "ModifyConfig";
- private static final String RECIPE_MODIFY_ANR = "ModifyConfigANR";
/* To be used in future releases when pci ModifyConfig is used */
private static final String SDNR_REQUEST_PARAMS = "request-parameters";
diff --git a/models-interactions/model-actors/actor.sdnr/src/test/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProviderTest.java b/models-interactions/model-actors/actor.sdnr/src/test/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProviderTest.java
index 265aea341..a9178961a 100644
--- a/models-interactions/model-actors/actor.sdnr/src/test/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProviderTest.java
+++ b/models-interactions/model-actors/actor.sdnr/src/test/java/org/onap/policy/controlloop/actor/sdnr/SdnrActorServiceProviderTest.java
@@ -46,6 +46,8 @@ import org.slf4j.LoggerFactory;
public class SdnrActorServiceProviderTest {
+ private static final String MODIFY_CONFIG = "ModifyConfig";
+
private static final Logger logger = LoggerFactory.getLogger(SdnrActorServiceProviderTest.class);
private static final VirtualControlLoopEvent onsetEvent;
@@ -73,7 +75,7 @@ public class SdnrActorServiceProviderTest {
/* Construct an operation with an SDNR actor and ModifyConfig operation. */
operation = new ControlLoopOperation();
operation.setActor("SDNR");
- operation.setOperation("ModifyConfig");
+ operation.setOperation(MODIFY_CONFIG);
operation.setTarget("VNF");
operation.setEnd(Instant.now());
operation.setSubRequestId("1");
@@ -85,7 +87,7 @@ public class SdnrActorServiceProviderTest {
policy.setActor("SDNR");
policy.setTarget(new Target(TargetType.VNF));
policy.getTarget().setResourceID("Eace933104d443b496b8.nodes.heat.vpg");
- policy.setRecipe("ModifyConfig");
+ policy.setRecipe(MODIFY_CONFIG);
policy.setPayload(null);
policy.setRetry(2);
policy.setTimeout(300);
@@ -132,7 +134,7 @@ public class SdnrActorServiceProviderTest {
/* An action is required and cannot be null */
assertNotNull(sdnrRequest.getAction());
- assertEquals("ModifyConfig", sdnrRequest.getAction());
+ assertEquals(MODIFY_CONFIG, sdnrRequest.getAction());
/* A payload is required and cannot be null */
assertNotNull(sdnrRequest.getPayload());
@@ -147,7 +149,7 @@ public class SdnrActorServiceProviderTest {
/* The JSON string must contain the following fields */
assertTrue(jsonRequest.contains("CommonHeader"));
assertTrue(jsonRequest.contains("Action"));
- assertTrue(jsonRequest.contains("ModifyConfig"));
+ assertTrue(jsonRequest.contains(MODIFY_CONFIG));
assertTrue(jsonRequest.contains("payload"));
PciResponse sdnrResponse = new PciResponse(sdnrRequest);
@@ -164,7 +166,7 @@ public class SdnrActorServiceProviderTest {
assertEquals("SDNR", sp.actor());
assertEquals(1, sp.recipes().size());
- assertEquals("VNF", sp.recipeTargets("ModifyConfig").get(0));
- assertEquals(2, sp.recipePayloads("ModifyConfig").size());
+ assertEquals("VNF", sp.recipeTargets(MODIFY_CONFIG).get(0));
+ assertEquals(2, sp.recipePayloads(MODIFY_CONFIG).size());
}
}
diff --git a/models-interactions/model-actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SoActorServiceProvider.java b/models-interactions/model-actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SoActorServiceProvider.java
index 2da0a95af..8aad5feb3 100644
--- a/models-interactions/model-actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SoActorServiceProvider.java
+++ b/models-interactions/model-actors/actor.so/src/main/java/org/onap/policy/controlloop/actor/so/SoActorServiceProvider.java
@@ -57,6 +57,9 @@ import org.slf4j.LoggerFactory;
public class SoActorServiceProvider implements Actor {
private static final Logger logger = LoggerFactory.getLogger(SoActorServiceProvider.class);
+ private static final String TENANT_NOT_FOUND = "Tenant Item not found in AAI response {}";
+ private static final String CONSTRUCTED_SO_MSG = "Constructed SO request: {}";
+
// Strings for SO Actor
private static final String SO_ACTOR = "SO";
@@ -160,7 +163,7 @@ public class SoActorServiceProvider implements Actor {
tenantItem = aaiResponseWrapper.getAaiNqResponse().getInventoryResponseItems().get(0).getItems()
.getInventoryResponseItems().get(1);
} catch (Exception e) {
- logger.error("Tenant Item not found in AAI response {}",
+ logger.error(TENANT_NOT_FOUND,
Serialization.gsonPretty.toJson(aaiResponseWrapper), e);
return null;
}
@@ -180,7 +183,7 @@ public class SoActorServiceProvider implements Actor {
if (RECIPE_VF_MODULE_CREATE.equals(policy.getRecipe())) {
return constructCreateRequest(aaiResponseWrapper, policy, tenantItem, vnfItem, vnfServiceItem, soModelInfo);
} else if (RECIPE_VF_MODULE_DELETE.equals(policy.getRecipe())) {
- return constructDeleteRequest(tenantItem, vnfItem, vnfServiceItem, soModelInfo, policy);
+ return constructDeleteRequest(tenantItem, vnfItem, vnfServiceItem, policy);
} else {
return null;
}
@@ -188,21 +191,23 @@ public class SoActorServiceProvider implements Actor {
private SoModelInfo prepareSoModelInfo(Policy policy) {
- SoModelInfo soModelInfo = new SoModelInfo();
- if ((policy.getTarget() != null && (policy.getTarget().getModelCustomizationId() != null))
- && (policy.getTarget().getModelInvariantId() != null) && (policy.getTarget().getModelName() != null)
- && (policy.getTarget().getModelVersion() != null) && (policy.getTarget().getModelVersionId() != null)) {
-
- soModelInfo.setModelCustomizationId(policy.getTarget().getModelCustomizationId());
- soModelInfo.setModelInvariantId(policy.getTarget().getModelInvariantId());
- soModelInfo.setModelName(policy.getTarget().getModelName());
- soModelInfo.setModelVersion(policy.getTarget().getModelVersion());
- soModelInfo.setModelVersionId(policy.getTarget().getModelVersionId());
- soModelInfo.setModelType("vfModule");
- return soModelInfo;
- } else {
+ if (policy.getTarget() == null || policy.getTarget().getModelCustomizationId() == null
+ || policy.getTarget().getModelInvariantId() == null) {
return null;
}
+
+ if (policy.getTarget().getModelName() == null || policy.getTarget().getModelVersion() == null
+ || policy.getTarget().getModelVersionId() == null) {
+ return null;
+ }
+
+ SoModelInfo soModelInfo = new SoModelInfo();
+ soModelInfo.setModelCustomizationId(policy.getTarget().getModelCustomizationId());
+ soModelInfo.setModelInvariantId(policy.getTarget().getModelInvariantId());
+ soModelInfo.setModelName(policy.getTarget().getModelName());
+ soModelInfo.setModelVersion(policy.getTarget().getModelVersion());
+ soModelInfo.setModelVersionId(policy.getTarget().getModelVersionId());
+ return soModelInfo;
}
/**
@@ -301,7 +306,7 @@ public class SoActorServiceProvider implements Actor {
preserveInstanceIds(vnfItem.getGenericVnf().getVnfId(),
vnfServiceItem.getServiceInstance().getServiceInstanceId(), null);
if (logger.isDebugEnabled()) {
- logger.debug("Constructed SO request: {}", Serialization.gsonPretty.toJson(request));
+ logger.debug(CONSTRUCTED_SO_MSG, Serialization.gsonPretty.toJson(request));
}
return request;
}
@@ -312,11 +317,10 @@ public class SoActorServiceProvider implements Actor {
* @param tenantItem tenant item from A&AI named-query response
* @param vnfItem vnf item from A&AI named-query response
* @param vnfServiceItem vnf service item from A&AI named-query response
- * @param vfModuleItem vf module item from A&AI named-query response
* @return SO delete vf-module request
*/
private SoRequest constructDeleteRequest(AaiNqInventoryResponseItem tenantItem, AaiNqInventoryResponseItem vnfItem,
- AaiNqInventoryResponseItem vnfServiceItem, SoModelInfo vfModuleItem, Policy policy) {
+ AaiNqInventoryResponseItem vnfServiceItem, Policy policy) {
SoRequest request = new SoRequest();
request.setOperationType(SoOperationType.DELETE_VF_MODULE);
request.setRequestDetails(new SoRequestDetails());
@@ -334,7 +338,7 @@ public class SoActorServiceProvider implements Actor {
vnfServiceItem.getServiceInstance().getServiceInstanceId(), null);
if (logger.isDebugEnabled()) {
- logger.debug("Constructed SO request: {}", Serialization.gsonPretty.toJson(request));
+ logger.debug(CONSTRUCTED_SO_MSG, Serialization.gsonPretty.toJson(request));
}
return request;
}
@@ -513,14 +517,14 @@ public class SoActorServiceProvider implements Actor {
try {
tenantItem = aaiCqResponse.getDefaultTenant();
} catch (Exception e) {
- logger.error("Tenant Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiCqResponse), e);
+ logger.error(TENANT_NOT_FOUND, Serialization.gsonPretty.toJson(aaiCqResponse), e);
return null;
}
try {
cloudRegionItem = aaiCqResponse.getDefaultCloudRegion();
} catch (Exception e) {
- logger.error("Tenant Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiCqResponse), e);
+ logger.error(TENANT_NOT_FOUND, Serialization.gsonPretty.toJson(aaiCqResponse), e);
return null;
}
@@ -531,7 +535,7 @@ public class SoActorServiceProvider implements Actor {
return constructCreateRequestCq(aaiCqResponse, policy, tenantItem, vnfItem, vnfServiceItem, soModelInfo,
cloudRegionItem);
} else if (RECIPE_VF_MODULE_DELETE.equals(policy.getRecipe())) {
- return constructDeleteRequestCq(tenantItem, vnfItem, vnfServiceItem, soModelInfo, policy, cloudRegionItem);
+ return constructDeleteRequestCq(tenantItem, vnfItem, vnfServiceItem, policy, cloudRegionItem);
} else {
return null;
}
@@ -622,7 +626,7 @@ public class SoActorServiceProvider implements Actor {
// vfModuleId is not required for the create vf-module
preserveInstanceIds(vnfItem.getVnfId(), vnfServiceItem.getServiceInstanceId(), null);
if (logger.isDebugEnabled()) {
- logger.debug("Constructed SO request: {}", Serialization.gsonPretty.toJson(request));
+ logger.debug(CONSTRUCTED_SO_MSG, Serialization.gsonPretty.toJson(request));
}
return request;
}
@@ -633,13 +637,12 @@ public class SoActorServiceProvider implements Actor {
* @param tenantItem Tenant from A&AI CQ request
* @param vnfItem Generic VNF from A&AI CQ request
* @param vnfServiceItem ServiceInstance from A&AI CQ request
- * @param vfModuleItem VFModule from A&AI CQ request
* @param policy policy information
* @param cloudRegionItem CloudRegion from A&AI CQ request
* @return SoRequest deleted
*/
private SoRequest constructDeleteRequestCq(Tenant tenantItem, GenericVnf vnfItem, ServiceInstance vnfServiceItem,
- SoModelInfo vfModuleItem, Policy policy, CloudRegion cloudRegionItem) {
+ Policy policy, CloudRegion cloudRegionItem) {
SoRequest request = new SoRequest();
request.setOperationType(SoOperationType.DELETE_VF_MODULE);
request.setRequestDetails(new SoRequestDetails());
@@ -656,7 +659,7 @@ public class SoActorServiceProvider implements Actor {
preserveInstanceIds(vnfItem.getVnfId(), vnfServiceItem.getServiceInstanceId(), null);
if (logger.isDebugEnabled()) {
- logger.debug("Constructed SO request: {}", Serialization.gsonPretty.toJson(request));
+ logger.debug(CONSTRUCTED_SO_MSG, Serialization.gsonPretty.toJson(request));
}
return request;
}
diff --git a/models-interactions/model-actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java b/models-interactions/model-actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java
index 9c26a4cd1..175d2fe0c 100644
--- a/models-interactions/model-actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java
+++ b/models-interactions/model-actors/actor.so/src/test/java/org/onap/policy/controlloop/actor/so/SoActorServiceProviderTest.java
@@ -26,7 +26,6 @@ package org.onap.policy.controlloop.actor.so;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -36,7 +35,6 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
-import org.eclipse.persistence.exceptions.JAXBException;
import org.junit.Test;
import org.onap.policy.aai.AaiCqResponse;
import org.onap.policy.aai.AaiNqResponse;
@@ -52,6 +50,8 @@ import org.onap.policy.so.util.Serialization;
public class SoActorServiceProviderTest {
+ private static final String C_VALUE = "cvalue";
+ private static final String A_VALUE = "avalue";
private static final String VF_MODULE_CREATE = "VF Module Create";
private static final String VF_MODULE_DELETE = "VF Module Delete";
@@ -90,9 +90,9 @@ public class SoActorServiceProviderTest {
request = new SoActorServiceProvider().constructRequest(onset, operation, policy, aaiNqResp);
assertNotNull(request);
assertEquals(true, request.getRequestDetails().getRequestParameters().isUsePreload());
- assertEquals("avalue", request.getRequestDetails().getRequestParameters().getUserParams().get(0).get("akey"));
+ assertEquals(A_VALUE, request.getRequestDetails().getRequestParameters().getUserParams().get(0).get("akey"));
assertEquals(1, request.getRequestDetails().getConfigurationParameters().size());
- assertEquals("cvalue", request.getRequestDetails().getConfigurationParameters().get(0).get("ckey"));
+ assertEquals(C_VALUE, request.getRequestDetails().getConfigurationParameters().get(0).get("ckey"));
// payload with config, but no request params
policy.setPayload(makePayload());
@@ -176,11 +176,7 @@ public class SoActorServiceProviderTest {
@Test
public void testSendRequest() {
- try {
- SoActorServiceProvider.sendRequest(UUID.randomUUID().toString(), null, null, null, null, null);
- } catch (Exception e) {
- fail("Test should not throw an exception");
- }
+ SoActorServiceProvider.sendRequest(UUID.randomUUID().toString(), null, null, null, null, null);
}
@Test
@@ -232,9 +228,9 @@ public class SoActorServiceProviderTest {
request = new SoActorServiceProvider().constructRequestCq(onset, operation, policy, aaiCqResp);
assertNotNull(request);
assertEquals(true, request.getRequestDetails().getRequestParameters().isUsePreload());
- assertEquals("avalue", request.getRequestDetails().getRequestParameters().getUserParams().get(0).get("akey"));
+ assertEquals(A_VALUE, request.getRequestDetails().getRequestParameters().getUserParams().get(0).get("akey"));
assertEquals(1, request.getRequestDetails().getConfigurationParameters().size());
- assertEquals("cvalue", request.getRequestDetails().getConfigurationParameters().get(0).get("ckey"));
+ assertEquals(C_VALUE, request.getRequestDetails().getConfigurationParameters().get(0).get("ckey"));
// payload with config, but no request params
policy.setPayload(makePayload());
@@ -282,9 +278,8 @@ public class SoActorServiceProviderTest {
* @param fileName name of the file containing the JSON response
* @return output from the AAI vserver named-query
* @throws IOException if the file cannot be read
- * @throws JAXBException throws JAXBException
*/
- private AaiCqResponse loadAaiResponseCq(String fileName) throws IOException, JAXBException {
+ private AaiCqResponse loadAaiResponseCq(String fileName) throws IOException {
String resp = IOUtils.toString(getClass().getResource(fileName), StandardCharsets.UTF_8);
return new AaiCqResponse(resp);
}
@@ -316,7 +311,7 @@ public class SoActorServiceProviderTest {
params.setUsePreload(true);
Map<String, String> map = new TreeMap<>();
- map.put("akey", "avalue");
+ map.put("akey", A_VALUE);
List<Map<String, String>> lst = new LinkedList<>();
lst.add(map);
@@ -333,7 +328,7 @@ public class SoActorServiceProviderTest {
*/
private String makeConfigParams() {
Map<String, String> map = new TreeMap<>();
- map.put("ckey", "cvalue");
+ map.put("ckey", C_VALUE);
List<Map<String, String>> lst = new LinkedList<>();
lst.add(map);
diff --git a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java
index 61cf81da9..a41d9e82d 100644
--- a/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java
+++ b/models-interactions/model-actors/actor.vfc/src/main/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProvider.java
@@ -41,6 +41,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VfcActorServiceProvider implements Actor {
+ private static final String GENERIC_VNF_ID = "generic-vnf.vnf-id";
+
private static final Logger logger = LoggerFactory.getLogger(VfcActorServiceProvider.class);
// Strings for VFC Actor
@@ -105,7 +107,7 @@ public class VfcActorServiceProvider implements Actor {
request.setNsInstanceId(serviceInstance);
request.setRequestId(onset.getRequestId());
request.setHealRequest(new VfcHealRequest());
- request.getHealRequest().setVnfInstanceId(onset.getAai().get("generic-vnf.vnf-id"));
+ request.getHealRequest().setVnfInstanceId(onset.getAai().get(GENERIC_VNF_ID));
request.getHealRequest().setCause(operation.getMessage());
request.getHealRequest().setAdditionalParams(new VfcHealAdditionalParams());
@@ -127,7 +129,7 @@ public class VfcActorServiceProvider implements Actor {
AaiGetVnfResponse response = null;
UUID requestId = event.getRequestId();
String vnfName = event.getAai().get("generic-vnf.vnf-name");
- String vnfId = event.getAai().get("generic-vnf.vnf-id");
+ String vnfId = event.getAai().get(GENERIC_VNF_ID);
try {
if (vnfName != null) {
String url = aaiUrl + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=";
@@ -176,7 +178,7 @@ public class VfcActorServiceProvider implements Actor {
request.setNsInstanceId(serviceInstance);
request.setRequestId(onset.getRequestId());
request.setHealRequest(new VfcHealRequest());
- request.getHealRequest().setVnfInstanceId(onset.getAai().get("generic-vnf.vnf-id"));
+ request.getHealRequest().setVnfInstanceId(onset.getAai().get(GENERIC_VNF_ID));
request.getHealRequest().setCause(operation.getMessage());
request.getHealRequest().setAdditionalParams(new VfcHealAdditionalParams());
diff --git a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java
index 8d5d5fae0..54bb995d2 100644
--- a/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java
+++ b/models-interactions/model-actors/actor.vfc/src/test/java/org/onap/policy/controlloop/actor/vfc/VfcActorServiceProviderTest.java
@@ -25,14 +25,12 @@ package org.onap.policy.controlloop.actor.vfc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
-import org.eclipse.persistence.exceptions.JAXBException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -47,16 +45,18 @@ import org.onap.policy.vfc.VfcRequest;
public class VfcActorServiceProviderTest {
+ private static final String LOCAL_URL = "http://localhost:6666";
+ private static final String DOROTHY_GALE_1939 = "dorothy.gale.1939";
+ private static final String CQ_RESPONSE_JSON = "aai/AaiCqResponse.json";
+ private static final String RESTART = "Restart";
+
/**
- * Set up for test class.
+ * Set up before test class.
+ * @throws Exception if the A&AI simulator cannot be started
*/
@BeforeClass
- public static void setUpSimulator() {
- try {
- Util.buildAaiSim();
- } catch (Exception e) {
- fail(e.getMessage());
- }
+ public static void setUpSimulator() throws Exception {
+ Util.buildAaiSim();
}
@AfterClass
@@ -74,40 +74,40 @@ public class VfcActorServiceProviderTest {
assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, null, null, null));
- onset.getAai().put("generic-vnf.vnf-id", "dorothy.gale.1939");
+ onset.getAai().put("generic-vnf.vnf-id", DOROTHY_GALE_1939);
assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, null, null, null));
- assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, "http://localhost:6666",
+ assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, LOCAL_URL,
"AAI", "AAI"));
UUID requestId = UUID.randomUUID();
onset.setRequestId(requestId);
- assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, "http://localhost:6666",
+ assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, LOCAL_URL,
"AAI", "AAI"));
onset.getAai().put("generic-vnf.vnf-name", "Dorothy");
- assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, "http://localhost:6666",
+ assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, LOCAL_URL,
"AAI", null));
- assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, "http://localhost:6666",
+ assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, LOCAL_URL,
"AAI", "AAI"));
onset.getAai().put("service-instance.service-instance-id", "");
- assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, "http://localhost:6666",
+ assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, null, LOCAL_URL,
"AAI", "AAI"));
assertNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse(),
- "http://localhost:6666", "AAI", "AAI"));
+ LOCAL_URL, "AAI", "AAI"));
- policy.setRecipe("Restart");
+ policy.setRecipe(RESTART);
assertNotNull(VfcActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse(),
- "http://localhost:6666", "AAI", "AAI"));
+ LOCAL_URL, "AAI", "AAI"));
VfcRequest request = VfcActorServiceProvider.constructRequest(onset, operation, policy, new AaiGetVnfResponse(),
- "http://localhost:6666", "AAI", "AAI");
+ LOCAL_URL, "AAI", "AAI");
assertEquals(requestId, Objects.requireNonNull(request).getRequestId());
- assertEquals("dorothy.gale.1939", request.getHealRequest().getVnfInstanceId());
+ assertEquals(DOROTHY_GALE_1939, request.getHealRequest().getVnfInstanceId());
assertEquals("restartvm", request.getHealRequest().getAdditionalParams().getAction());
}
@@ -117,13 +117,13 @@ public class VfcActorServiceProviderTest {
assertEquals("VFC", sp.actor());
assertEquals(1, sp.recipes().size());
- assertEquals("Restart", sp.recipes().get(0));
- assertEquals("VM", sp.recipeTargets("Restart").get(0));
- assertEquals(0, sp.recipePayloads("Restart").size());
+ assertEquals(RESTART, sp.recipes().get(0));
+ assertEquals("VM", sp.recipeTargets(RESTART).get(0));
+ assertEquals(0, sp.recipePayloads(RESTART).size());
}
@Test
- public void testConstructRequestCq() throws IOException, JAXBException {
+ public void testConstructRequestCq() throws IOException {
VirtualControlLoopEvent onset = new VirtualControlLoopEvent();
ControlLoopOperation operation = new ControlLoopOperation();
@@ -132,7 +132,7 @@ public class VfcActorServiceProviderTest {
assertNull(VfcActorServiceProvider.constructRequestCq(onset, operation, policy, null));
- onset.getAai().put("generic-vnf.vnf-id", "dorothy.gale.1939");
+ onset.getAai().put("generic-vnf.vnf-id", DOROTHY_GALE_1939);
assertNull(VfcActorServiceProvider.constructRequestCq(onset, operation, policy, null));
@@ -148,17 +148,17 @@ public class VfcActorServiceProviderTest {
assertNull(VfcActorServiceProvider.constructRequestCq(onset, operation, policy, null));
assertNull(VfcActorServiceProvider.constructRequestCq(onset, operation, policy,
- loadAaiResponse("aai/AaiCqResponse.json")));
+ loadAaiResponse(CQ_RESPONSE_JSON)));
- policy.setRecipe("Restart");
+ policy.setRecipe(RESTART);
assertNotNull(VfcActorServiceProvider.constructRequestCq(onset, operation, policy,
- loadAaiResponse("aai/AaiCqResponse.json")));
+ loadAaiResponse(CQ_RESPONSE_JSON)));
VfcRequest request = VfcActorServiceProvider.constructRequestCq(onset, operation, policy,
- loadAaiResponse("aai/AaiCqResponse.json"));
+ loadAaiResponse(CQ_RESPONSE_JSON));
assertEquals(requestId, Objects.requireNonNull(request).getRequestId());
- assertEquals("dorothy.gale.1939", request.getHealRequest().getVnfInstanceId());
+ assertEquals(DOROTHY_GALE_1939, request.getHealRequest().getVnfInstanceId());
assertEquals("restartvm", request.getHealRequest().getAdditionalParams().getAction());
}
@@ -168,9 +168,8 @@ public class VfcActorServiceProviderTest {
* @param fileName name of the file containing the JSON response
* @return output from the AAI vserver named-query
* @throws IOException if the file cannot be read
- * @throws JAXBException throws JAXBException
*/
- private AaiCqResponse loadAaiResponse(String fileName) throws IOException, JAXBException {
+ private AaiCqResponse loadAaiResponse(String fileName) throws IOException {
String resp = IOUtils.toString(getClass().getResource(fileName), StandardCharsets.UTF_8);
return new AaiCqResponse(resp);
}
diff --git a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/ActorServiceProviderTest.java b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/ActorServiceProviderTest.java
index 3354a2268..7ab21dece 100644
--- a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/ActorServiceProviderTest.java
+++ b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/ActorServiceProviderTest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -29,6 +30,8 @@ import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
public class ActorServiceProviderTest {
+ private static final String DOROTHY = "Dorothy";
+
@Test
public void testActorServiceProvider() {
ActorService actorService = ActorService.getInstance();
@@ -45,10 +48,10 @@ public class ActorServiceProviderTest {
assertEquals("DummyActor", dummyActor.actor());
assertEquals(2, dummyActor.recipes().size());
- assertEquals("Dorothy", dummyActor.recipes().get(0));
+ assertEquals(DOROTHY, dummyActor.recipes().get(0));
assertEquals("Wizard", dummyActor.recipes().get(1));
- assertEquals(2, dummyActor.recipeTargets("Dorothy").size());
- assertEquals(2, dummyActor.recipePayloads("Dorothy").size());
+ assertEquals(2, dummyActor.recipeTargets(DOROTHY).size());
+ assertEquals(2, dummyActor.recipePayloads(DOROTHY).size());
}
}
diff --git a/models-interactions/model-impl/aai/src/main/java/org/onap/policy/aai/AaiManager.java b/models-interactions/model-impl/aai/src/main/java/org/onap/policy/aai/AaiManager.java
index 2b51a7bde..20998ae0c 100644
--- a/models-interactions/model-impl/aai/src/main/java/org/onap/policy/aai/AaiManager.java
+++ b/models-interactions/model-impl/aai/src/main/java/org/onap/policy/aai/AaiManager.java
@@ -45,6 +45,8 @@ public final class AaiManager {
/** The Constant logger. */
private static final Logger logger = LoggerFactory.getLogger(AaiManager.class);
+ private static final String APPLICATION_JSON = "application/json";
+
/** The rest manager. */
// The REST manager used for processing REST calls for this AAI manager
private final RestManager restManager;
@@ -77,7 +79,7 @@ public final class AaiManager {
return null;
} else {
JSONObject responseObj = new JSONObject(getResponse);
- JSONArray resultsArray = new JSONArray();
+ JSONArray resultsArray;
if (responseObj.has("result-data")) {
resultsArray = (JSONArray) responseObj.get("result-data");
} else {
@@ -138,7 +140,7 @@ public final class AaiManager {
url = url + CQ_URL;
Pair<Integer, String> httpDetails =
- this.restManager.put(url, username, password, headers, "application/json", requestJson);
+ this.restManager.put(url, username, password, headers, APPLICATION_JSON, requestJson);
logger.debug("RestManager.put after");
if (httpDetails == null) {
@@ -232,7 +234,7 @@ public final class AaiManager {
String requestJson = Serialization.gsonPretty.toJson(request);
NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
Pair<Integer, String> httpDetails =
- restManager.post(url, username, password, headers, "application/json", requestJson);
+ restManager.post(url, username, password, headers, APPLICATION_JSON, requestJson);
logger.debug("RestManager.post after");
if (httpDetails == null) {
@@ -360,7 +362,7 @@ public final class AaiManager {
headers.put("X-FromAppId", "POLICY");
headers.put("X-TransactionId", requestId.toString());
- headers.put("Accept", "application/json");
+ headers.put("Accept", APPLICATION_JSON);
return headers;
}
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiCqResponseTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiCqResponseTest.java
index efdba10a3..8335ce80b 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiCqResponseTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiCqResponseTest.java
@@ -40,6 +40,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AaiCqResponseTest {
+ private static final String ETE_VFMODULE = "Vfmodule_Ete_vFWCLvFWSNK_7ba1fbde_0";
+ private static final String ETE_VNF = "Ete_vFWCLvFWSNK_7ba1fbde_0";
private static final Logger LOGGER = LoggerFactory.getLogger(AaiCqResponseTest.class);
private static final String CQ_RESPONSE_SAMPLE = "src/test/resources/org/onap/policy/aai/AaiCqResponseFull.json";
@@ -168,7 +170,7 @@ public class AaiCqResponseTest {
aaiCqResponse = new AaiCqResponse(responseString);
GenericVnf genVnf = aaiCqResponse.getDefaultGenericVnf();
assertNotNull(genVnf);
- assertEquals("Ete_vFWCLvFWSNK_7ba1fbde_0", genVnf.getVnfName());
+ assertEquals(ETE_VNF, genVnf.getVnfName());
LOGGER.info(genVnf.getVnfName());
}
@@ -181,7 +183,7 @@ public class AaiCqResponseTest {
AaiCqResponse aaiCqResponse;
aaiCqResponse = new AaiCqResponse(responseString);
- GenericVnf genVnf = aaiCqResponse.getGenericVnfByVnfName("Ete_vFWCLvFWSNK_7ba1fbde_0");
+ GenericVnf genVnf = aaiCqResponse.getGenericVnfByVnfName(ETE_VNF);
assertNotNull(genVnf);
assertEquals("f17face5-69cb-4c88-9e0b-7426db7edddd", genVnf.getVnfId());
LOGGER.info(genVnf.getVnfId());
@@ -214,7 +216,7 @@ public class AaiCqResponseTest {
GenericVnf genVnf =
aaiCqResponse.getGenericVnfByVfModuleModelInvariantId("e6130d03-56f1-4b0a-9a1d-e1b2ebc30e0e");
assertNotNull(genVnf);
- assertEquals("Ete_vFWCLvFWSNK_7ba1fbde_0", genVnf.getVnfName());
+ assertEquals(ETE_VNF, genVnf.getVnfName());
LOGGER.info(genVnf.getVnfName());
}
@@ -245,9 +247,9 @@ public class AaiCqResponseTest {
AaiCqResponse aaiCqResponse;
aaiCqResponse = new AaiCqResponse(responseString);
- VfModule vfModule = aaiCqResponse.getVfModuleByVfModuleName("Vfmodule_Ete_vFWCLvFWSNK_7ba1fbde_0");
+ VfModule vfModule = aaiCqResponse.getVfModuleByVfModuleName(ETE_VFMODULE);
assertNotNull(vfModule);
- assertEquals("Vfmodule_Ete_vFWCLvFWSNK_7ba1fbde_0", vfModule.getVfModuleName());
+ assertEquals(ETE_VFMODULE, vfModule.getVfModuleName());
LOGGER.info(vfModule.getVfModuleName());
@@ -263,7 +265,7 @@ public class AaiCqResponseTest {
aaiCqResponse = new AaiCqResponse(responseString);
VfModule vfModule = aaiCqResponse.getVfModuleByVfModelInvariantId("e6130d03-56f1-4b0a-9a1d-e1b2ebc30e0e");
assertNotNull(vfModule);
- assertEquals("Vfmodule_Ete_vFWCLvFWSNK_7ba1fbde_0", vfModule.getVfModuleName());
+ assertEquals(ETE_VFMODULE, vfModule.getVfModuleName());
LOGGER.info(vfModule.getVfModuleName());
@@ -279,7 +281,7 @@ public class AaiCqResponseTest {
aaiCqResponse = new AaiCqResponse(responseString);
VfModule vfModule = aaiCqResponse.getDefaultVfModule();
assertNotNull(vfModule);
- assertEquals("Vfmodule_Ete_vFWCLvFWSNK_7ba1fbde_0", vfModule.getVfModuleName());
+ assertEquals(ETE_VFMODULE, vfModule.getVfModuleName());
LOGGER.info(vfModule.getVfModuleName());
}
@@ -293,7 +295,7 @@ public class AaiCqResponseTest {
aaiCqResponse = new AaiCqResponse(responseString);
Vserver vserver = aaiCqResponse.getVserver();
assertNotNull(vserver);
- assertEquals("Ete_vFWCLvFWSNK_7ba1fbde_0", vserver.getVserverName());
+ assertEquals(ETE_VNF, vserver.getVserverName());
LOGGER.info(vserver.getVserverName());
}
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiManagerTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiManagerTest.java
index 7842b076c..9a8d7d260 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiManagerTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiManagerTest.java
@@ -44,6 +44,12 @@ import org.onap.policy.rest.RestManager;
import org.onap.policy.rest.RestManager.Pair;
public class AaiManagerTest {
+ private static final String VSERVER_NAME = "vserverName";
+ private static final String CQ_QUERY_URL = "http://testing.cq.query";
+ private static final String WITCH = "Witch";
+ private static final String DOROTHY = "Dorothy";
+ private static final String SOME_URL = "http://somewhere.over.the.rainbow";
+ private static final String ANOTHER_URL = "http://somewhere.under.the.rainbow";
RestManager restManagerMock;
UUID aaiNqRequestUuid = UUID.randomUUID();
Pair<Integer, String> httpResponseOk;
@@ -92,14 +98,14 @@ public class AaiManagerTest {
UUID vserverNameRequestId = UUID.randomUUID();
- when(restManagerMock.put(startsWith("http://testing.cq.query"), eq("Foo"), eq("Bar"), anyMap(), anyString(),
+ when(restManagerMock.put(startsWith(CQ_QUERY_URL), eq("Foo"), eq("Bar"), anyMap(), anyString(),
anyString())).thenReturn(httpCqResponseOk);
- when(restManagerMock.get(startsWith("http://testing.cq.query"), eq("Foo"), eq("Bar"), anyMap()))
+ when(restManagerMock.get(startsWith(CQ_QUERY_URL), eq("Foo"), eq("Bar"), anyMap()))
.thenReturn(httpTenantResponseOk);
AaiCqResponse aaiCqResponse =
- aaiManager.getCustomQueryResponse("http://testing.cq.query", "Foo", "Bar", vserverNameRequestId, "Foo");
+ aaiManager.getCustomQueryResponse(CQ_QUERY_URL, "Foo", "Bar", vserverNameRequestId, "Foo");
assertNotNull(aaiCqResponse);
when(restManagerMock.put(eq(""), eq("Foo"), eq("Bar"), anyMap(), anyString(), anyString()))
@@ -146,30 +152,30 @@ public class AaiManagerTest {
AaiNqRequest aaiNqRequest = new AaiNqRequest();
aaiNqRequest.setQueryParameters(aaiNqQueryParameters);
- when(restManagerMock.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Gale"), anyMap(),
+ when(restManagerMock.post(startsWith(SOME_URL), eq(DOROTHY), eq("Gale"), anyMap(),
anyString(), anyString())).thenReturn(httpResponseOk);
- AaiNqResponse aaiNqOkResponse = aaiManager.postQuery("http://somewhere.over.the.rainbow", "Dorothy", "Gale",
+ AaiNqResponse aaiNqOkResponse = aaiManager.postQuery(SOME_URL, DOROTHY, "Gale",
aaiNqRequest, aaiNqRequestUuid);
assertNotNull(aaiNqOkResponse);
- when(restManagerMock.post(isNull(), eq("Dorothy"), anyString(), anyMap(), anyString(), anyString()))
+ when(restManagerMock.post(isNull(), eq(DOROTHY), anyString(), anyMap(), anyString(), anyString()))
.thenReturn(null);
- AaiNqResponse aaiNqNullResponse = aaiManager.postQuery(null, "Dorothy", "Gale", null, aaiNqRequestUuid);
+ AaiNqResponse aaiNqNullResponse = aaiManager.postQuery(null, DOROTHY, "Gale", null, aaiNqRequestUuid);
assertNull(aaiNqNullResponse);
- when(restManagerMock.post(startsWith("http://somewhere.over.the.rainbow"), eq("Witch"), eq("West"), anyMap(),
+ when(restManagerMock.post(startsWith(SOME_URL), eq(WITCH), eq("West"), anyMap(),
anyString(), anyString())).thenReturn(httpResponseErr0);
- AaiNqResponse aaiNqNotOkResponse0 = aaiManager.postQuery("http://somewhere.over.the.rainbow", "Witch", "West",
+ AaiNqResponse aaiNqNotOkResponse0 = aaiManager.postQuery(SOME_URL, WITCH, "West",
aaiNqRequest, aaiNqRequestUuid);
assertNull(aaiNqNotOkResponse0);
- when(restManagerMock.post(startsWith("http://somewhere.under.the.rainbow"), eq("Witch"), eq("West"), anyMap(),
+ when(restManagerMock.post(startsWith(ANOTHER_URL), eq(WITCH), eq("West"), anyMap(),
anyString(), anyString())).thenReturn(httpResponseErr1);
- AaiNqResponse aaiNqNotOkResponse1 = aaiManager.postQuery("http://somewhere.under.the.rainbow", "Witch", "West",
+ AaiNqResponse aaiNqNotOkResponse1 = aaiManager.postQuery(ANOTHER_URL, WITCH, "West",
aaiNqRequest, aaiNqRequestUuid);
assertNull(aaiNqNotOkResponse1);
}
@@ -181,22 +187,22 @@ public class AaiManagerTest {
UUID vserverNameRequestId = UUID.randomUUID();
- when(restManagerMock.get(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Gale"), anyMap()))
+ when(restManagerMock.get(startsWith(SOME_URL), eq(DOROTHY), eq("Gale"), anyMap()))
.thenReturn(httpResponseOk);
- AaiGetVserverResponse vserverResponse = aaiManager.getQueryByVserverName("http://somewhere.over.the.rainbow",
- "Dorothy", "Gale", vserverNameRequestId, "vserverName");
+ AaiGetVserverResponse vserverResponse = aaiManager.getQueryByVserverName(SOME_URL,
+ DOROTHY, "Gale", vserverNameRequestId, VSERVER_NAME);
assertNotNull(vserverResponse);
AaiGetVserverResponse vserverNullResponse =
- aaiManager.getQueryByVserverName(null, "Dorothy", "Gale", vserverNameRequestId, "vserverName");
+ aaiManager.getQueryByVserverName(null, DOROTHY, "Gale", vserverNameRequestId, VSERVER_NAME);
assertNull(vserverNullResponse);
- when(restManagerMock.get(startsWith("http://somewhere.under.the.rainbow"), eq("Witch"), eq("West"), anyMap()))
+ when(restManagerMock.get(startsWith(ANOTHER_URL), eq(WITCH), eq("West"), anyMap()))
.thenReturn(httpResponseErr0);
AaiGetVserverResponse vserverNotOkResponse0 = aaiManager.getQueryByVserverName(
- "http://somewhere.under.the.rainbow", "Witch", "West", vserverNameRequestId, "vserverName");
+ ANOTHER_URL, WITCH, "West", vserverNameRequestId, VSERVER_NAME);
assertNull(vserverNotOkResponse0);
}
@@ -207,10 +213,10 @@ public class AaiManagerTest {
UUID vserverNameRequestId = UUID.randomUUID();
- when(restManagerMock.get(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Gale"), anyMap()))
+ when(restManagerMock.get(startsWith(SOME_URL), eq(DOROTHY), eq("Gale"), anyMap()))
.thenReturn(httpResponseOk);
- AaiGetVnfResponse vnfResponse = aaiManager.getQueryByVnfId("http://somewhere.over.the.rainbow", "Dorothy",
+ AaiGetVnfResponse vnfResponse = aaiManager.getQueryByVnfId(SOME_URL, DOROTHY,
"Gale", vserverNameRequestId, "vnfID");
assertNotNull(vnfResponse);
}
@@ -222,10 +228,10 @@ public class AaiManagerTest {
UUID vserverNameRequestId = UUID.randomUUID();
- when(restManagerMock.get(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Gale"), anyMap()))
+ when(restManagerMock.get(startsWith(SOME_URL), eq(DOROTHY), eq("Gale"), anyMap()))
.thenReturn(httpResponseOk);
- AaiGetVnfResponse vnfResponse = aaiManager.getQueryByVnfId("http://somewhere.over.the.rainbow", "Dorothy",
+ AaiGetVnfResponse vnfResponse = aaiManager.getQueryByVnfId(SOME_URL, DOROTHY,
"Gale", vserverNameRequestId, "vnfName");
assertNotNull(vnfResponse);
}
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqCloudRegionTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqCloudRegionTest.java
index 6932031db..9bdc758ed 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqCloudRegionTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqCloudRegionTest.java
@@ -24,18 +24,10 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
public class AaiNqCloudRegionTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqCloudRegion aaiNqCloudRegion = new AaiNqCloudRegion();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertiesTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertiesTest.java
index e1ac2379c..ed76f8a12 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertiesTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertiesTest.java
@@ -23,18 +23,10 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
public class AaiNqExtraPropertiesTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqExtraProperties aaiNqExtraProperties = new AaiNqExtraProperties();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertyTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertyTest.java
index ebc64efc9..483753679 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertyTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqExtraPropertyTest.java
@@ -24,18 +24,10 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
public class AaiNqExtraPropertyTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqExtraProperty aaiNqExtraProperty = new AaiNqExtraProperty();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java
index e30bcaf86..93119c73e 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqGenericVnfTest.java
@@ -24,17 +24,12 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
public class AaiNqGenericVnfTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
+ private static final String VERSION_ID = "98f410f6-4c63-447b-97d2-42508437cec0";
+ private static final String INVARIANT_ID = "653d2caa-7e47-4614-95b3-26c8d82755b8";
@Test
public void test() {
@@ -44,12 +39,12 @@ public class AaiNqGenericVnfTest {
aaiNqGenericVnf.setIpv4Loopback0Address("aa");
aaiNqGenericVnf.setIpv4OamAddress("oamAddress");
aaiNqGenericVnf.setIsClosedLoopDisabled(false);
- aaiNqGenericVnf.setModelInvariantId("653d2caa-7e47-4614-95b3-26c8d82755b8");
- aaiNqGenericVnf.setModelVersionId("98f410f6-4c63-447b-97d2-42508437cec0");
+ aaiNqGenericVnf.setModelInvariantId(INVARIANT_ID);
+ aaiNqGenericVnf.setModelVersionId(VERSION_ID);
aaiNqGenericVnf.setModelCustomizationId("SomeCustomizationId");
aaiNqGenericVnf.setOperationalState("active");
- aaiNqGenericVnf.setPersonaModelId("653d2caa-7e47-4614-95b3-26c8d82755b8");
- aaiNqGenericVnf.setPersonaModelVersion("98f410f6-4c63-447b-97d2-42508437cec0");
+ aaiNqGenericVnf.setPersonaModelId(INVARIANT_ID);
+ aaiNqGenericVnf.setPersonaModelVersion(VERSION_ID);
aaiNqGenericVnf.setProvStatus("complete");
aaiNqGenericVnf.setResourceVersion("1505056714553");
aaiNqGenericVnf.setServiceId("e8cb8968-5411-478b-906a-f28747de72cd");
@@ -64,12 +59,12 @@ public class AaiNqGenericVnfTest {
assertEquals("aa", aaiNqGenericVnf.getIpv4Loopback0Address());
assertEquals("oamAddress", aaiNqGenericVnf.getIpv4OamAddress());
assertEquals(false, aaiNqGenericVnf.getIsClosedLoopDisabled());
- assertEquals("653d2caa-7e47-4614-95b3-26c8d82755b8", aaiNqGenericVnf.getModelInvariantId());
- assertEquals("98f410f6-4c63-447b-97d2-42508437cec0", aaiNqGenericVnf.getModelVersionId());
+ assertEquals(INVARIANT_ID, aaiNqGenericVnf.getModelInvariantId());
+ assertEquals(VERSION_ID, aaiNqGenericVnf.getModelVersionId());
assertEquals("SomeCustomizationId", aaiNqGenericVnf.getModelCustomizationId());
assertEquals("active", aaiNqGenericVnf.getOperationalState());
- assertEquals("653d2caa-7e47-4614-95b3-26c8d82755b8", aaiNqGenericVnf.getPersonaModelId());
- assertEquals("98f410f6-4c63-447b-97d2-42508437cec0", aaiNqGenericVnf.getPersonaModelVersion());
+ assertEquals(INVARIANT_ID, aaiNqGenericVnf.getPersonaModelId());
+ assertEquals(VERSION_ID, aaiNqGenericVnf.getPersonaModelVersion());
assertEquals("complete", aaiNqGenericVnf.getProvStatus());
assertEquals("1505056714553", aaiNqGenericVnf.getResourceVersion());
assertEquals("e8cb8968-5411-478b-906a-f28747de72cd", aaiNqGenericVnf.getServiceId());
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInstanceFiltersTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInstanceFiltersTest.java
index 0c487d437..4b4cc6a6a 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInstanceFiltersTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInstanceFiltersTest.java
@@ -23,18 +23,10 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
public class AaiNqInstanceFiltersTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqInstanceFilters aaiNqInstanceFilters = new AaiNqInstanceFilters();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemTest.java
index 97384db76..79f23b629 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemTest.java
@@ -24,27 +24,27 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertNotNull;
import java.util.LinkedList;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AaiNqInventoryResponseItemTest {
+ private static final String WIDGET = "widget";
+ private static final String SERVICE_INSTANCE = "service-instance";
+ private static final String MODEL_VERSION_KEY = "model.model-version";
+ private static final String MODEL_TYPE_KEY = "model.model-type";
+ private static final String MODEL_NAME_KEY = "model.model-name";
+ private static final String MODEL_ID_KEY = "model.model-id";
+ private static final String PERSONA_MODEL_ID2 = "ef86f9c5-2165-44f3-8fc3-96018b609ea5";
+ private static final String PERSONA_MODEL_ID = "82194af1-3c2c-485a-8f44-420e22a9eaa4";
+ private static final String RESOURCE_VERSION = "1485366450";
private static final Logger logger = LoggerFactory.getLogger(AaiNqInventoryResponseItemTest.class);
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqInventoryResponseItem aaiNqInventoryResponseItem = new AaiNqInventoryResponseItem();
- aaiNqInventoryResponseItem.setModelName("service-instance");
+ aaiNqInventoryResponseItem.setModelName(SERVICE_INSTANCE);
AaiNqCloudRegion aaiNqCloudRegion = new AaiNqCloudRegion();
aaiNqCloudRegion.setCloudOwner("OWNER");
aaiNqCloudRegion.setCloudRegionId("REGIONID");
@@ -54,11 +54,11 @@ public class AaiNqInventoryResponseItemTest {
aaiNqInventoryResponseItem.setCloudRegion(aaiNqCloudRegion);
AaiNqExtraProperties aaiNqExtraProperties = new AaiNqExtraProperties();
aaiNqExtraProperties.setExtraProperty(new LinkedList<>());
- aaiNqExtraProperties.getExtraProperty().add(new AaiNqExtraProperty("model.model-name", "generic-vnf"));
- aaiNqExtraProperties.getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- aaiNqExtraProperties.getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ aaiNqExtraProperties.getExtraProperty().add(new AaiNqExtraProperty(MODEL_NAME_KEY, "generic-vnf"));
+ aaiNqExtraProperties.getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ aaiNqExtraProperties.getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
aaiNqExtraProperties.getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
aaiNqExtraProperties.getExtraProperty()
.add(new AaiNqExtraProperty("model.model-name-version-id", "93a6166f-b3d5-4f06-b4ba-aed48d009ad9"));
aaiNqInventoryResponseItem.setExtraProperties(aaiNqExtraProperties);
@@ -74,29 +74,29 @@ public class AaiNqInventoryResponseItemTest {
aaiNqGenericVnf.setIpv4Loopback0Address("dhv-test-gvnfipv4-loopback0-address");
aaiNqGenericVnf.setInMaint(false);
aaiNqGenericVnf.setIsClosedLoopDisabled(false);
- aaiNqGenericVnf.setResourceVersion("1485366450");
+ aaiNqGenericVnf.setResourceVersion(RESOURCE_VERSION);
aaiNqGenericVnf.setEncrypedAccessFlag(true);
aaiNqGenericVnf.setPersonaModelId("acc6edd8-a8d4-4b93-afaa-0994068be14c");
aaiNqGenericVnf.setPersonaModelVersion("1.0");
aaiNqInventoryResponseItem.setGenericVnf(aaiNqGenericVnf);
AaiNqInventoryResponseItem serviceItem = new AaiNqInventoryResponseItem();
- serviceItem.setModelName("service-instance");
+ serviceItem.setModelName(SERVICE_INSTANCE);
serviceItem.setServiceInstance(new AaiNqServiceInstance());
serviceItem.getServiceInstance().setServiceInstanceId("dhv-test-vhnfportal-service-instance-id");
serviceItem.getServiceInstance().setServiceInstanceName("dhv-test-service-instance-name1");
- serviceItem.getServiceInstance().setPersonaModelId("82194af1-3c2c-485a-8f44-420e22a9eaa4");
+ serviceItem.getServiceInstance().setPersonaModelId(PERSONA_MODEL_ID);
serviceItem.getServiceInstance().setPersonaModelVersion("1.0");
serviceItem.getServiceInstance().setServiceInstanceLocationId("dhv-test-service-instance-location-id1");
serviceItem.getServiceInstance().setResourceVersion("1485366092");
serviceItem.setExtraProperties(new AaiNqExtraProperties());
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "service-instance"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, SERVICE_INSTANCE));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "82194af1-3c2c-485a-8f44-420e22a9eaa4"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, PERSONA_MODEL_ID));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "46b92144-923a-4d20-b85a-3cbd847668a9"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "46b92144-923a-4d20-b85a-3cbd847668a9"));
AaiNqInventoryResponseItem vfModuleItem = new AaiNqInventoryResponseItem();
vfModuleItem.setModelName("vf-module");
@@ -106,21 +106,21 @@ public class AaiNqInventoryResponseItemTest {
vfModuleItem.getVfModule().setHeatStackId("example-heat-stack-id-val-86300");
vfModuleItem.getVfModule().setOrchestrationStatus("example-orchestration-status-val-56523");
vfModuleItem.getVfModule().setIsBaseVfModule(true);
- vfModuleItem.getVfModule().setResourceVersion("1485366450");
- vfModuleItem.getVfModule().setPersonaModelId("ef86f9c5-2165-44f3-8fc3-96018b609ea5");
+ vfModuleItem.getVfModule().setResourceVersion(RESOURCE_VERSION);
+ vfModuleItem.getVfModule().setPersonaModelId(PERSONA_MODEL_ID2);
vfModuleItem.getVfModule().setPersonaModelVersion("1.0");
vfModuleItem.getVfModule().setWidgetModelId("example-widget-model-id-val-92571");
vfModuleItem.getVfModule().setWidgetModelVersion("example-widget-model-version-val-83317");
vfModuleItem.getVfModule().setContrailServiceInstanceFqdn("example-contrail-service-instance-fqdn-val-86796");
vfModuleItem.setExtraProperties(new AaiNqExtraProperties());
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "vf-module"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "vf-module"));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "ef86f9c5-2165-44f3-8fc3-96018b609ea5"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, PERSONA_MODEL_ID2));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "c00563ae-812b-4e62-8330-7c4d0f47088a"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "c00563ae-812b-4e62-8330-7c4d0f47088a"));
AaiNqInventoryResponseItems aaiNqInventoryResponseItems = new AaiNqInventoryResponseItems();
aaiNqInventoryResponseItems.getInventoryResponseItems().add(serviceItem);
@@ -130,7 +130,7 @@ public class AaiNqInventoryResponseItemTest {
AaiNqServiceInstance serviceInstance = new AaiNqServiceInstance();
serviceInstance.setServiceInstanceId("dhv-test-vhnfportal-service-instance-id");
serviceInstance.setServiceInstanceName("dhv-test-service-instance-name1");
- serviceInstance.setPersonaModelId("82194af1-3c2c-485a-8f44-420e22a9eaa4");
+ serviceInstance.setPersonaModelId(PERSONA_MODEL_ID);
serviceInstance.setPersonaModelVersion("1.0");
serviceInstance.setServiceInstanceLocationId("dhv-test-service-instance-location-id1");
serviceInstance.setResourceVersion("1485366092");
@@ -146,8 +146,8 @@ public class AaiNqInventoryResponseItemTest {
aaiNqVfModule.setHeatStackId("example-heat-stack-id-val-86300");
aaiNqVfModule.setOrchestrationStatus("example-orchestration-status-val-56523");
aaiNqVfModule.setIsBaseVfModule(true);
- aaiNqVfModule.setResourceVersion("1485366450");
- aaiNqVfModule.setPersonaModelId("ef86f9c5-2165-44f3-8fc3-96018b609ea5");
+ aaiNqVfModule.setResourceVersion(RESOURCE_VERSION);
+ aaiNqVfModule.setPersonaModelId(PERSONA_MODEL_ID2);
aaiNqVfModule.setPersonaModelVersion("1.0");
aaiNqVfModule.setWidgetModelId("example-widget-model-id-val-92571");
aaiNqVfModule.setWidgetModelVersion("example-widget-model-version-val-83317");
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemsTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemsTest.java
index f43d7c777..ef1dd4e09 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemsTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqInventoryResponseItemsTest.java
@@ -25,28 +25,25 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.LinkedList;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AaiNqInventoryResponseItemsTest {
+ private static final String WIDGET = "widget";
+ private static final String SERVICE_INSTANCE = "service-instance";
+ private static final String MODEL_VERSION_KEY = "model.model-version";
+ private static final String MODEL_TYPE_KEY = "model.model-type";
+ private static final String MODEL_NAME_KEY = "model.model-name";
+ private static final String MODEL_ID_KEY = "model.model-id";
private static final Logger logger = LoggerFactory.getLogger(AaiNqInventoryResponseItemsTest.class);
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqInventoryResponseItem serviceItem = new AaiNqInventoryResponseItem();
- serviceItem.setModelName("service-instance");
- assertEquals("service-instance", serviceItem.getModelName());
+ serviceItem.setModelName(SERVICE_INSTANCE);
+ assertEquals(SERVICE_INSTANCE, serviceItem.getModelName());
serviceItem.setServiceInstance(new AaiNqServiceInstance());
serviceItem.getServiceInstance().setServiceInstanceId("dhv-test-vhnfportal-service-instance-id");
@@ -57,13 +54,13 @@ public class AaiNqInventoryResponseItemsTest {
serviceItem.getServiceInstance().setResourceVersion("1485366092");
serviceItem.setExtraProperties(new AaiNqExtraProperties());
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "service-instance"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, SERVICE_INSTANCE));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "82194af1-3c2c-485a-8f44-420e22a9eaa4"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "82194af1-3c2c-485a-8f44-420e22a9eaa4"));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "46b92144-923a-4d20-b85a-3cbd847668a9"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "46b92144-923a-4d20-b85a-3cbd847668a9"));
AaiNqInventoryResponseItem vfModuleItem = new AaiNqInventoryResponseItem();
vfModuleItem.setModelName("vf-module");
@@ -81,13 +78,13 @@ public class AaiNqInventoryResponseItemsTest {
vfModuleItem.getVfModule().setContrailServiceInstanceFqdn("example-contrail-service-instance-fqdn-val-86796");
vfModuleItem.setExtraProperties(new AaiNqExtraProperties());
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "vf-module"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "vf-module"));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "ef86f9c5-2165-44f3-8fc3-96018b609ea5"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "ef86f9c5-2165-44f3-8fc3-96018b609ea5"));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "c00563ae-812b-4e62-8330-7c4d0f47088a"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "c00563ae-812b-4e62-8330-7c4d0f47088a"));
AaiNqInventoryResponseItem genericVnfItem = new AaiNqInventoryResponseItem();
genericVnfItem.setModelName("generic-vnf");
@@ -110,13 +107,13 @@ public class AaiNqInventoryResponseItemsTest {
genericVnfItem.setExtraProperties(new AaiNqExtraProperties());
genericVnfItem.getExtraProperties().setExtraProperty(new LinkedList<>());
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "generic-vnf"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "generic-vnf"));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-type", "widget"));
+ .add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
genericVnfItem.getExtraProperties().getExtraProperty()
.add(new AaiNqExtraProperty("model.model-name-version-id", "93a6166f-b3d5-4f06-b4ba-aed48d009ad9"));
genericVnfItem.setItems(new AaiNqInventoryResponseItems());
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqNamedQueryTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqNamedQueryTest.java
index 2986f6db6..a4344d8e6 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqNamedQueryTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqNamedQueryTest.java
@@ -25,19 +25,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.UUID;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
public class AaiNqNamedQueryTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqNamedQuery aaiNqNamedQuery = new AaiNqNamedQuery();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqQueryParametersTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqQueryParametersTest.java
index 22c1b4bbf..f304713f9 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqQueryParametersTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqQueryParametersTest.java
@@ -25,19 +25,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.UUID;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
public class AaiNqQueryParametersTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqQueryParameters aaiNqQueryParameters = new AaiNqQueryParameters();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqRequestTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqRequestTest.java
index a8863197e..35108a03a 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqRequestTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqRequestTest.java
@@ -25,9 +25,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.UUID;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
@@ -36,12 +33,6 @@ import org.slf4j.LoggerFactory;
public class AaiNqRequestTest {
private static final Logger logger = LoggerFactory.getLogger(AaiNqRequestTest.class);
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqRequest aaiNqRequest = new AaiNqRequest();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseTest.java
index 9b3a4afee..ba160e2c7 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseTest.java
@@ -29,6 +29,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AaiNqResponseTest {
+ private static final String WIDGET = "widget";
+ private static final String MODEL_VERSION_KEY = "model.model-version";
+ private static final String MODEL_TYPE_KEY = "model.model-type";
+ private static final String MODEL_NAME_KEY = "model.model-name";
+ private static final String MODEL_ID_KEY = "model.model-id";
private static final Logger logger = LoggerFactory.getLogger(AaiNqResponseTest.class);
@Test
@@ -53,13 +58,13 @@ public class AaiNqResponseTest {
serviceItem.getServiceInstance().setResourceVersion("1485366092");
serviceItem.setExtraProperties(new AaiNqExtraProperties());
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "service-instance"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "service-instance"));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "82194af1-3c2c-485a-8f44-420e22a9eaa4"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "82194af1-3c2c-485a-8f44-420e22a9eaa4"));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "46b92144-923a-4d20-b85a-3cbd847668a9"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "46b92144-923a-4d20-b85a-3cbd847668a9"));
AaiNqInventoryResponseItem vfModuleItem = new AaiNqInventoryResponseItem();
vfModuleItem.setModelName("vf-module");
@@ -77,13 +82,13 @@ public class AaiNqResponseTest {
vfModuleItem.getVfModule().setContrailServiceInstanceFqdn("example-contrail-service-instance-fqdn-val-86796");
vfModuleItem.setExtraProperties(new AaiNqExtraProperties());
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "vf-module"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "vf-module"));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "ef86f9c5-2165-44f3-8fc3-96018b609ea5"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "ef86f9c5-2165-44f3-8fc3-96018b609ea5"));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "c00563ae-812b-4e62-8330-7c4d0f47088a"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "c00563ae-812b-4e62-8330-7c4d0f47088a"));
AaiNqInventoryResponseItem genericVnfItem = new AaiNqInventoryResponseItem();
genericVnfItem.setModelName("generic-vnf");
@@ -106,13 +111,13 @@ public class AaiNqResponseTest {
genericVnfItem.setExtraProperties(new AaiNqExtraProperties());
genericVnfItem.getExtraProperties().setExtraProperty(new LinkedList<>());
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "generic-vnf"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "generic-vnf"));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-type", "widget"));
+ .add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
genericVnfItem.getExtraProperties().getExtraProperty()
.add(new AaiNqExtraProperty("model.model-name-version-id", "93a6166f-b3d5-4f06-b4ba-aed48d009ad9"));
genericVnfItem.setItems(new AaiNqInventoryResponseItems());
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseWrapperTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseWrapperTest.java
index 459454e3a..f80fd82bd 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseWrapperTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqResponseWrapperTest.java
@@ -37,6 +37,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AaiNqResponseWrapperTest {
+ private static final String WIDGET = "widget";
+ private static final String MODEL_VERSION_KEY = "model.model-version";
+ private static final String MODEL_TYPE_KEY = "model.model-type";
+ private static final String MODEL_NAME_KEY = "model.model-name";
+ private static final String MODEL_ID_KEY = "model.model-id";
+ private static final String VERSION_JSON = "AaiNqResponseWrapper-Vserver.json";
+ private static final String NO_NAMES_JSON = "AaiNqResponseWrapper-NoNames.json";
private static final Logger logger = LoggerFactory.getLogger(AaiNqResponseWrapperTest.class);
@Test
@@ -52,13 +59,13 @@ public class AaiNqResponseWrapperTest {
serviceItem.getServiceInstance().setResourceVersion("1485366092");
serviceItem.setExtraProperties(new AaiNqExtraProperties());
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "service-instance"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "service-instance"));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ serviceItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "82194af1-3c2c-485a-8f44-420e22a9eaa4"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "82194af1-3c2c-485a-8f44-420e22a9eaa4"));
serviceItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "46b92144-923a-4d20-b85a-3cbd847668a9"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "46b92144-923a-4d20-b85a-3cbd847668a9"));
AaiNqInventoryResponseItem vfModuleItem = new AaiNqInventoryResponseItem();
vfModuleItem.setModelName("vf-module");
@@ -76,13 +83,13 @@ public class AaiNqResponseWrapperTest {
vfModuleItem.getVfModule().setContrailServiceInstanceFqdn("example-contrail-service-instance-fqdn-val-86796");
vfModuleItem.setExtraProperties(new AaiNqExtraProperties());
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "vf-module"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-type", "widget"));
- vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "vf-module"));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
+ vfModuleItem.getExtraProperties().getExtraProperty().add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "ef86f9c5-2165-44f3-8fc3-96018b609ea5"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "ef86f9c5-2165-44f3-8fc3-96018b609ea5"));
vfModuleItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "c00563ae-812b-4e62-8330-7c4d0f47088a"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "c00563ae-812b-4e62-8330-7c4d0f47088a"));
AaiNqInventoryResponseItem genericVnfItem = new AaiNqInventoryResponseItem();
genericVnfItem.setModelName("generic-vnf");
@@ -105,13 +112,13 @@ public class AaiNqResponseWrapperTest {
genericVnfItem.setExtraProperties(new AaiNqExtraProperties());
genericVnfItem.getExtraProperties().setExtraProperty(new LinkedList<>());
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-name", "generic-vnf"));
+ .add(new AaiNqExtraProperty(MODEL_NAME_KEY, "generic-vnf"));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-type", "widget"));
+ .add(new AaiNqExtraProperty(MODEL_TYPE_KEY, WIDGET));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-version", "1.0"));
+ .add(new AaiNqExtraProperty(MODEL_VERSION_KEY, "1.0"));
genericVnfItem.getExtraProperties().getExtraProperty()
- .add(new AaiNqExtraProperty("model.model-id", "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
+ .add(new AaiNqExtraProperty(MODEL_ID_KEY, "acc6edd8-a8d4-4b93-afaa-0994068be14c"));
genericVnfItem.getExtraProperties().getExtraProperty()
.add(new AaiNqExtraProperty("model.model-name-version-id", "93a6166f-b3d5-4f06-b4ba-aed48d009ad9"));
genericVnfItem.setItems(new AaiNqInventoryResponseItems());
@@ -175,13 +182,13 @@ public class AaiNqResponseWrapperTest {
// null item
resp = new AaiNqResponseWrapper();
assertEquals(0, resp.countVfModules());
-
+
// no names
- resp.setAaiNqResponse(load("AaiNqResponseWrapper-NoNames.json"));
+ resp.setAaiNqResponse(load(NO_NAMES_JSON));
assertEquals(0, resp.countVfModules());
// has VF modules
- resp.setAaiNqResponse(load("AaiNqResponseWrapper-Vserver.json"));
+ resp.setAaiNqResponse(load(VERSION_JSON));
assertEquals(3, resp.countVfModules());
}
@@ -192,13 +199,13 @@ public class AaiNqResponseWrapperTest {
// null item
resp = new AaiNqResponseWrapper();
assertEquals(null, resp.genVfModuleName());
-
+
// no names
- resp.setAaiNqResponse(load("AaiNqResponseWrapper-NoNames.json"));
+ resp.setAaiNqResponse(load(NO_NAMES_JSON));
assertEquals(null, resp.genVfModuleName());
// has VF modules
- resp.setAaiNqResponse(load("AaiNqResponseWrapper-Vserver.json"));
+ resp.setAaiNqResponse(load(VERSION_JSON));
assertEquals("my-module-abc_124", resp.genVfModuleName());
}
@@ -220,25 +227,25 @@ public class AaiNqResponseWrapperTest {
resp.getAaiNqResponse().getInventoryResponseItems().get(0).getItems().getInventoryResponseItems().get(0)
.getItems().setInventoryResponseItems(null);
assertTrue(resp.getVfModuleItems(false).isEmpty());
-
+
// no modules
resp.setAaiNqResponse(load("AaiNqResponseWrapper-NoModules.json"));
assertTrue(resp.getVfModuleItems(false).isEmpty());
-
+
// no names
- resp.setAaiNqResponse(load("AaiNqResponseWrapper-NoNames.json"));
+ resp.setAaiNqResponse(load(NO_NAMES_JSON));
List<AaiNqInventoryResponseItem> lst;
lst = resp.getVfModuleItems(false);
assertEquals(0, lst.size());
// base VF modules
- resp.setAaiNqResponse(load("AaiNqResponseWrapper-Vserver.json"));
+ resp.setAaiNqResponse(load(VERSION_JSON));
lst = resp.getVfModuleItems(true);
assertEquals(1, lst.size());
assertEquals("Vfmodule_vLBMS-0809-1", lst.get(0).getVfModule().getVfModuleName());
-
+
// non base VF modules
- resp.setAaiNqResponse(load("AaiNqResponseWrapper-Vserver.json"));
+ resp.setAaiNqResponse(load(VERSION_JSON));
lst = resp.getVfModuleItems(false);
assertEquals(3, lst.size());
int index;
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqServiceInstanceTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqServiceInstanceTest.java
index 4dc9b15e4..45a55c99b 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqServiceInstanceTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqServiceInstanceTest.java
@@ -24,8 +24,6 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
@@ -34,12 +32,6 @@ import org.slf4j.LoggerFactory;
public class AaiNqServiceInstanceTest {
private static final Logger logger = LoggerFactory.getLogger(AaiNqServiceInstanceTest.class);
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqServiceInstance aaiNqServiceInstance = new AaiNqServiceInstance();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqTenantTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqTenantTest.java
index 4e03f57fc..ed4cdb705 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqTenantTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqTenantTest.java
@@ -24,8 +24,6 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
@@ -34,12 +32,6 @@ import org.slf4j.LoggerFactory;
public class AaiNqTenantTest {
private static final Logger logger = LoggerFactory.getLogger(AaiNqTenantTest.class);
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqTenant aaiNqTenant = new AaiNqTenant();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVServerTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVServerTest.java
index c6a04a5eb..c613a0223 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVServerTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVServerTest.java
@@ -27,8 +27,6 @@ import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.nio.file.Files;
import java.util.List;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
@@ -37,13 +35,6 @@ import org.slf4j.LoggerFactory;
public class AaiNqVServerTest {
private static final Logger logger = LoggerFactory.getLogger(AaiNqVServerTest.class);
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() throws Exception {
// deserialize json and verify fields are populated properly
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java
index da169d589..65bde98c2 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/AaiNqVfModuleTest.java
@@ -24,8 +24,6 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
@@ -34,13 +32,6 @@ import org.slf4j.LoggerFactory;
public class AaiNqVfModuleTest {
private static final Logger logger = LoggerFactory.getLogger(AaiNqVfModuleTest.class);
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
AaiNqVfModule aaiNqVfModule = new AaiNqVfModule();
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfInstanceTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfInstanceTest.java
index ab397cd95..8cf839110 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfInstanceTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfInstanceTest.java
@@ -27,27 +27,20 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PnfInstanceTest {
+ private static final String PNF_NAME_TEST = "pnf-name-test";
private static final Logger logger = LoggerFactory.getLogger(PnfInstanceTest.class);
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
PnfInstance pnfInstance = new PnfInstance();
pnfInstance.setPnfInstanceName("pnf-instance-name-test");
- pnfInstance.setPnfName("pnf-name-test");
+ pnfInstance.setPnfName(PNF_NAME_TEST);
pnfInstance.setPnfType(PnfType.ENODEB);
pnfInstance.setPnfSerial("pnf-serial-test");
assertNotNull(pnfInstance);
@@ -59,7 +52,7 @@ public class PnfInstanceTest {
PnfInstance pnfInstanceClone = new PnfInstance(pnfInstance);
assertNotNull(pnfInstanceClone);
- assertEquals("pnf-name-test", pnfInstanceClone.getPnfName());
+ assertEquals(PNF_NAME_TEST, pnfInstanceClone.getPnfName());
assertEquals(PnfType.ENODEB, pnfInstanceClone.getPnfType());
assertEquals("pnf-serial-test", pnfInstanceClone.getPnfSerial());
@@ -69,7 +62,7 @@ public class PnfInstanceTest {
assertNotEquals(0, new Pnf().hashCode());
PnfInstance pnfInstanceOther0 = new PnfInstance();
- pnfInstanceOther0.setPnfName("pnf-name-test");
+ pnfInstanceOther0.setPnfName(PNF_NAME_TEST);
PnfInstance pnfInstanceOther1 = new PnfInstance(pnfInstance);
pnfInstanceOther1.setPnfName("pnf-name-test-diff");
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTest.java
index b5b152089..54cf4735b 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTest.java
@@ -27,33 +27,26 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PnfTest {
+ private static final String PNF_NAME_TEST = "pnf-name-test";
private static final Logger logger = LoggerFactory.getLogger(PnfTest.class);
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
Pnf pnf = new Pnf();
- pnf.setPnfName("pnf-name-test");
+ pnf.setPnfName(PNF_NAME_TEST);
pnf.setPnfType(PnfType.ENODEB);
assertNotNull(pnf);
Pnf pnfClone = new Pnf(pnf);
assertNotNull(pnfClone);
- assertEquals("pnf-name-test", pnfClone.getPnfName());
+ assertEquals(PNF_NAME_TEST, pnfClone.getPnfName());
assertEquals(PnfType.ENODEB, pnfClone.getPnfType());
assertEquals("PNF [PNFName=pnf-name-test, PNFType=eNodeB]", pnfClone.toString());
@@ -61,7 +54,7 @@ public class PnfTest {
assertNotEquals(0, new Pnf().hashCode());
Pnf pnfOther = new Pnf();
- pnfOther.setPnfName("pnf-name-test");
+ pnfOther.setPnfName(PNF_NAME_TEST);
assertTrue(pnf.equals(pnf));
assertFalse(pnf.equals(null));
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTypeTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTypeTest.java
index 3a24d8c46..d3236904d 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTypeTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/PnfTypeTest.java
@@ -23,8 +23,6 @@ package org.onap.policy.aai;
import static org.junit.Assert.assertNotNull;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.aai.util.Serialization;
import org.slf4j.Logger;
@@ -33,13 +31,6 @@ import org.slf4j.LoggerFactory;
public class PnfTypeTest {
private static final Logger logger = LoggerFactory.getLogger(PnfTypeTest.class);
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {}
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {}
-
@Test
public void test() {
PnfType pnfType = PnfType.ENODEB;
diff --git a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/util/AaiExceptionTest.java b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/util/AaiExceptionTest.java
index 4be8a53f6..c15407dd0 100644
--- a/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/util/AaiExceptionTest.java
+++ b/models-interactions/model-impl/aai/src/test/java/org/onap/policy/aai/util/AaiExceptionTest.java
@@ -29,12 +29,14 @@ import org.junit.Test;
public class AaiExceptionTest {
+ private static final String MESSAGE = "message";
+
@Test
public void test() {
assertNotNull(new AaiException());
- assertNotNull(new AaiException("message"));
- assertNotNull(new AaiException("message", new IOException()));
- assertNotNull(new AaiException("message", new IOException(), true, false));
+ assertNotNull(new AaiException(MESSAGE));
+ assertNotNull(new AaiException(MESSAGE, new IOException()));
+ assertNotNull(new AaiException(MESSAGE, new IOException(), true, false));
assertNotNull(new AaiException(new IOException()));
}
diff --git a/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/CommonHeaderTest.java b/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/CommonHeaderTest.java
index 5ff71e03a..ad8fc1f34 100644
--- a/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/CommonHeaderTest.java
+++ b/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/CommonHeaderTest.java
@@ -19,27 +19,6 @@
* ============LICENSE_END=========================================================
*/
-/*-
- * ============LICENSE_START=======================================================
- * appc
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * 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.policy.appc;
import static org.junit.Assert.assertEquals;
@@ -58,6 +37,10 @@ import org.junit.Test;
public class CommonHeaderTest {
+ private static final String KANSAS = "Kansas";
+ private static final String DOROTHY = "Dorothy";
+ private static final String CAN_I_GO_HOME = "Can I go home?";
+
@Test
public void testCommonHeader() {
CommonHeader commonHeader = new CommonHeader();
@@ -65,15 +48,15 @@ public class CommonHeaderTest {
assertNotNull(new CommonHeader(commonHeader));
assertNotEquals(0, commonHeader.hashCode());
- commonHeader.setApiVer("Kansas");
- assertEquals("Kansas", commonHeader.getApiVer());
+ commonHeader.setApiVer(KANSAS);
+ assertEquals(KANSAS, commonHeader.getApiVer());
List<Map<String, String>> flagSet = new ArrayList<>();
commonHeader.setFlags(flagSet);
assertEquals(flagSet, commonHeader.getFlags());
- commonHeader.setOriginatorId("Dorothy");
- assertEquals("Dorothy", commonHeader.getOriginatorId());
+ commonHeader.setOriginatorId(DOROTHY);
+ assertEquals(DOROTHY, commonHeader.getOriginatorId());
UUID requestId = UUID.randomUUID();
commonHeader.setRequestId(requestId);
@@ -83,8 +66,8 @@ public class CommonHeaderTest {
commonHeader.setRequestTrack(requestTrackSet);
assertEquals(requestTrackSet, commonHeader.getRequestTrack());
- commonHeader.setSubRequestId("Can I go home?");
- assertEquals("Can I go home?", commonHeader.getSubRequestId());
+ commonHeader.setSubRequestId(CAN_I_GO_HOME);
+ assertEquals(CAN_I_GO_HOME, commonHeader.getSubRequestId());
Instant timestamp = Instant.now();
commonHeader.setTimeStamp(timestamp);
@@ -118,9 +101,9 @@ public class CommonHeaderTest {
assertFalse(commonHeader.equals(copiedCommonHeader));
copiedCommonHeader.setApiVer(null);
assertTrue(commonHeader.equals(copiedCommonHeader));
- commonHeader.setApiVer("Kansas");
+ commonHeader.setApiVer(KANSAS);
assertFalse(commonHeader.equals(copiedCommonHeader));
- copiedCommonHeader.setApiVer("Kansas");
+ copiedCommonHeader.setApiVer(KANSAS);
assertTrue(commonHeader.equals(copiedCommonHeader));
commonHeader.setFlags(null);
@@ -136,9 +119,9 @@ public class CommonHeaderTest {
assertFalse(commonHeader.equals(copiedCommonHeader));
copiedCommonHeader.setOriginatorId(null);
assertTrue(commonHeader.equals(copiedCommonHeader));
- commonHeader.setOriginatorId("Dorothy");
+ commonHeader.setOriginatorId(DOROTHY);
assertFalse(commonHeader.equals(copiedCommonHeader));
- copiedCommonHeader.setOriginatorId("Dorothy");
+ copiedCommonHeader.setOriginatorId(DOROTHY);
assertTrue(commonHeader.equals(copiedCommonHeader));
commonHeader.setRequestId(null);
@@ -163,9 +146,9 @@ public class CommonHeaderTest {
assertFalse(commonHeader.equals(copiedCommonHeader));
copiedCommonHeader.setSubRequestId(null);
assertTrue(commonHeader.equals(copiedCommonHeader));
- commonHeader.setSubRequestId("Can I go home?");
+ commonHeader.setSubRequestId(CAN_I_GO_HOME);
assertFalse(commonHeader.equals(copiedCommonHeader));
- copiedCommonHeader.setSubRequestId("Can I go home?");
+ copiedCommonHeader.setSubRequestId(CAN_I_GO_HOME);
assertTrue(commonHeader.equals(copiedCommonHeader));
commonHeader.setTimeStamp(null);
diff --git a/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/RequestTest.java b/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/RequestTest.java
index 0f461d221..560a7d8d5 100644
--- a/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/RequestTest.java
+++ b/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/RequestTest.java
@@ -34,6 +34,9 @@ import org.junit.Test;
public class RequestTest {
+ private static final String WIZARD = "Wizard";
+ private static final String GO_TO_OZ = "Go to Oz";
+
@Test
public void testRequest() {
Request request = new Request();
@@ -45,11 +48,11 @@ public class RequestTest {
request.setCommonHeader(commonHeader);
assertEquals(commonHeader, request.getCommonHeader());
- request.setAction("Go to Oz");
- assertEquals("Go to Oz", request.getAction());
+ request.setAction(GO_TO_OZ);
+ assertEquals(GO_TO_OZ, request.getAction());
- request.setObjectId("Wizard");
- assertEquals("Wizard", request.getObjectId());
+ request.setObjectId(WIZARD);
+ assertEquals(WIZARD, request.getObjectId());
request.setTargetId("Oz");
assertEquals("Oz", request.getTargetId());
@@ -90,18 +93,18 @@ public class RequestTest {
assertFalse(request.equals(copiedRequest));
copiedRequest.setAction(null);
assertTrue(request.equals(copiedRequest));
- request.setAction("Go to Oz");
+ request.setAction(GO_TO_OZ);
assertFalse(request.equals(copiedRequest));
- copiedRequest.setAction("Go to Oz");
+ copiedRequest.setAction(GO_TO_OZ);
assertTrue(request.equals(copiedRequest));
request.setObjectId(null);
assertFalse(request.equals(copiedRequest));
copiedRequest.setObjectId(null);
assertTrue(request.equals(copiedRequest));
- request.setObjectId("Wizard");
+ request.setObjectId(WIZARD);
assertFalse(request.equals(copiedRequest));
- copiedRequest.setObjectId("Wizard");
+ copiedRequest.setObjectId(WIZARD);
assertTrue(request.equals(copiedRequest));
request.setTargetId(null);
diff --git a/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/ResponseStatusTest.java b/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/ResponseStatusTest.java
index 561c9494b..2541f9b0a 100644
--- a/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/ResponseStatusTest.java
+++ b/models-interactions/model-impl/appc/src/test/java/org/onap/policy/appc/ResponseStatusTest.java
@@ -31,6 +31,9 @@ import org.junit.Test;
public class ResponseStatusTest {
+ private static final String THERE_S_NO_PLACE_LIKE_HOME = "There's no place like home";
+ private static final String THE_WONDERFUL_LAND_OF_OZ = "The wonderful land of Oz";
+
@Test
public void testResonseStatus() {
ResponseStatus status = new ResponseStatus();
@@ -40,11 +43,11 @@ public class ResponseStatusTest {
status.setCode(1234);
assertEquals(1234, status.getCode());
- status.setDescription("The wonderful land of Oz");
- assertEquals("The wonderful land of Oz", status.getDescription());
+ status.setDescription(THE_WONDERFUL_LAND_OF_OZ);
+ assertEquals(THE_WONDERFUL_LAND_OF_OZ, status.getDescription());
- status.setValue("There's no place like home");
- assertEquals("There's no place like home", status.getValue());
+ status.setValue(THERE_S_NO_PLACE_LIKE_HOME);
+ assertEquals(THERE_S_NO_PLACE_LIKE_HOME, status.getValue());
assertNotEquals(0, status.hashCode());
assertEquals("ResponseStatus [Code=1234, Value=There's no pla", status.toString().substring(0, 47));
@@ -72,18 +75,18 @@ public class ResponseStatusTest {
assertFalse(status.equals(copiedStatus));
copiedStatus.setDescription(null);
assertTrue(status.equals(copiedStatus));
- status.setDescription("The wonderful land of Oz");
+ status.setDescription(THE_WONDERFUL_LAND_OF_OZ);
assertFalse(status.equals(copiedStatus));
- copiedStatus.setDescription("The wonderful land of Oz");
+ copiedStatus.setDescription(THE_WONDERFUL_LAND_OF_OZ);
assertTrue(status.equals(copiedStatus));
status.setValue(null);
assertFalse(status.equals(copiedStatus));
copiedStatus.setValue(null);
assertTrue(status.equals(copiedStatus));
- status.setValue("There's no place like home");
+ status.setValue(THERE_S_NO_PLACE_LIKE_HOME);
assertFalse(status.equals(copiedStatus));
- copiedStatus.setValue("There's no place like home");
+ copiedStatus.setValue(THERE_S_NO_PLACE_LIKE_HOME);
assertTrue(status.equals(copiedStatus));
}
}
diff --git a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/AppcLcmTest.java b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/AppcLcmTest.java
index 0ca6239cd..0ee79cf17 100644
--- a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/AppcLcmTest.java
+++ b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/AppcLcmTest.java
@@ -35,6 +35,12 @@ import org.slf4j.LoggerFactory;
public class AppcLcmTest {
+ private static final String VNF_ID_KEY = "vnf-id";
+
+ private static final String RESTART = "restart";
+
+ private static final String CORRELATION_ID = "664be3d2-6c12-4f4b-a3e7-c349acced200";
+
private static final Logger logger = LoggerFactory.getLogger(AppcLcmTest.class);
private static LcmRequestWrapper dmaapRequest;
@@ -45,29 +51,29 @@ public class AppcLcmTest {
* Construct an APPCLCM Request to be Serialized
*/
dmaapRequest = new LcmRequestWrapper();
- dmaapRequest.setCorrelationId("664be3d2-6c12-4f4b-a3e7-c349acced200" + "-" + "1");
- dmaapRequest.setRpcName("restart");
+ dmaapRequest.setCorrelationId(CORRELATION_ID + "-" + "1");
+ dmaapRequest.setRpcName(RESTART);
dmaapRequest.setType("request");
dmaapResponse = new LcmResponseWrapper();
- dmaapResponse.setCorrelationId("664be3d2-6c12-4f4b-a3e7-c349acced200" + "-" + "1");
- dmaapResponse.setRpcName("restart");
+ dmaapResponse.setCorrelationId(CORRELATION_ID + "-" + "1");
+ dmaapResponse.setRpcName(RESTART);
dmaapResponse.setType("response");
LcmRequest appcRequest = new LcmRequest();
- appcRequest.setAction("restart");
+ appcRequest.setAction(RESTART);
HashMap<String, String> actionIdentifiers = new HashMap<>();
- actionIdentifiers.put("vnf-id", "trial-vnf-003");
+ actionIdentifiers.put(VNF_ID_KEY, "trial-vnf-003");
actionIdentifiers.put("vserver-id", "08f6c1f9-99e7-49f3-a662-c62b9f200d79");
appcRequest.setActionIdentifiers(actionIdentifiers);
LcmCommonHeader commonHeader = new LcmCommonHeader();
- commonHeader.setRequestId(UUID.fromString("664be3d2-6c12-4f4b-a3e7-c349acced200"));
+ commonHeader.setRequestId(UUID.fromString(CORRELATION_ID));
commonHeader.setSubRequestId("1");
- commonHeader.setOriginatorId("664be3d2-6c12-4f4b-a3e7-c349acced200");
+ commonHeader.setOriginatorId(CORRELATION_ID);
appcRequest.setCommonHeader(commonHeader);
@@ -111,7 +117,7 @@ public class AppcLcmTest {
* action-identifiers should exist and contain a vnf-id
*/
assertTrue(jsonRequest.contains("action-identifiers"));
- assertTrue(jsonRequest.contains("vnf-id"));
+ assertTrue(jsonRequest.contains(VNF_ID_KEY));
/*
* The action sub-tag should exist
@@ -132,19 +138,19 @@ public class AppcLcmTest {
/*
* Use the serializer to convert the json string into a java object
*/
- LcmRequestWrapper dmaapRequest = Serialization.gson.fromJson(jsonRequest, LcmRequestWrapper.class);
- assertNotNull(dmaapRequest);
+ LcmRequestWrapper req = Serialization.gson.fromJson(jsonRequest, LcmRequestWrapper.class);
+ assertNotNull(req);
/*
* The type of the DMAAP wrapper should be request
*/
- assertEquals("request", dmaapRequest.getType());
+ assertEquals("request", req.getType());
/*
* The DMAAP wrapper must have a body as that is the true APPC request
*/
- assertNotNull(dmaapRequest.getBody());
- LcmRequest appcRequest = dmaapRequest.getBody();
+ assertNotNull(req.getBody());
+ LcmRequest appcRequest = req.getBody();
assertNotNull(appcRequest);
/*
@@ -156,13 +162,13 @@ public class AppcLcmTest {
* The action should not be null and should be set to restart
*/
assertNotNull(appcRequest.getAction());
- assertEquals("restart", appcRequest.getAction());
+ assertEquals(RESTART, appcRequest.getAction());
/*
* The action-identifiers should not be null and should contain a vnf-id
*/
assertNotNull(appcRequest.getActionIdentifiers());
- assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
+ assertNotNull(appcRequest.getActionIdentifiers().get(VNF_ID_KEY));
logger.debug("Request as a Java Object: \n" + appcRequest.toString() + "\n\n");
}
@@ -202,19 +208,19 @@ public class AppcLcmTest {
/*
* Use the serializer to convert the json string into a java object
*/
- LcmResponseWrapper dmaapResponse = Serialization.gson.fromJson(jsonResponse, LcmResponseWrapper.class);
- assertNotNull(dmaapResponse);
+ LcmResponseWrapper resp = Serialization.gson.fromJson(jsonResponse, LcmResponseWrapper.class);
+ assertNotNull(resp);
/*
* The type of the DMAAP wrapper should be response
*/
- assertEquals("response", dmaapResponse.getType());
+ assertEquals("response", resp.getType());
/*
* The DMAAP wrapper must have a body as that is the true APPC response
*/
- assertNotNull(dmaapResponse.getBody());
- LcmResponse appcResponse = dmaapResponse.getBody();
+ assertNotNull(resp.getBody());
+ LcmResponse appcResponse = resp.getBody();
assertNotNull(appcResponse);
/*
diff --git a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmCommonHeaderTest.java b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmCommonHeaderTest.java
index 7825e7fc1..32a4954c1 100644
--- a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmCommonHeaderTest.java
+++ b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmCommonHeaderTest.java
@@ -36,6 +36,10 @@ import org.junit.Test;
public class LcmCommonHeaderTest {
+ private static final String KANSAS = "Kansas";
+ private static final String DOROTHY = "Dorothy";
+ private static final String CAN_I_GO_HOME = "Can I go home?";
+
@Test
public void testLcmCommonHeader() {
LcmCommonHeader commonHeader = new LcmCommonHeader();
@@ -43,22 +47,22 @@ public class LcmCommonHeaderTest {
assertNotNull(new LcmCommonHeader(commonHeader));
assertNotEquals(0, commonHeader.hashCode());
- commonHeader.setApiVer("Kansas");
- assertEquals("Kansas", commonHeader.getApiVer());
+ commonHeader.setApiVer(KANSAS);
+ assertEquals(KANSAS, commonHeader.getApiVer());
Map<String, String> flagMap = new HashMap<>();
commonHeader.setFlags(flagMap);
assertEquals(flagMap, commonHeader.getFlags());
- commonHeader.setOriginatorId("Dorothy");
- assertEquals("Dorothy", commonHeader.getOriginatorId());
+ commonHeader.setOriginatorId(DOROTHY);
+ assertEquals(DOROTHY, commonHeader.getOriginatorId());
UUID requestId = UUID.randomUUID();
commonHeader.setRequestId(requestId);
assertEquals(requestId, commonHeader.getRequestId());
- commonHeader.setSubRequestId("Can I go home?");
- assertEquals("Can I go home?", commonHeader.getSubRequestId());
+ commonHeader.setSubRequestId(CAN_I_GO_HOME);
+ assertEquals(CAN_I_GO_HOME, commonHeader.getSubRequestId());
Instant timestamp = Instant.now();
commonHeader.setTimeStamp(timestamp);
@@ -91,9 +95,9 @@ public class LcmCommonHeaderTest {
assertFalse(commonHeader.equals(copiedLcmCommonHeader));
copiedLcmCommonHeader.setApiVer(null);
assertTrue(commonHeader.equals(copiedLcmCommonHeader));
- commonHeader.setApiVer("Kansas");
+ commonHeader.setApiVer(KANSAS);
assertFalse(commonHeader.equals(copiedLcmCommonHeader));
- copiedLcmCommonHeader.setApiVer("Kansas");
+ copiedLcmCommonHeader.setApiVer(KANSAS);
assertTrue(commonHeader.equals(copiedLcmCommonHeader));
commonHeader.setFlags(null);
@@ -109,9 +113,9 @@ public class LcmCommonHeaderTest {
assertFalse(commonHeader.equals(copiedLcmCommonHeader));
copiedLcmCommonHeader.setOriginatorId(null);
assertTrue(commonHeader.equals(copiedLcmCommonHeader));
- commonHeader.setOriginatorId("Dorothy");
+ commonHeader.setOriginatorId(DOROTHY);
assertFalse(commonHeader.equals(copiedLcmCommonHeader));
- copiedLcmCommonHeader.setOriginatorId("Dorothy");
+ copiedLcmCommonHeader.setOriginatorId(DOROTHY);
assertTrue(commonHeader.equals(copiedLcmCommonHeader));
commonHeader.setRequestId(null);
@@ -127,9 +131,9 @@ public class LcmCommonHeaderTest {
assertFalse(commonHeader.equals(copiedLcmCommonHeader));
copiedLcmCommonHeader.setSubRequestId(null);
assertTrue(commonHeader.equals(copiedLcmCommonHeader));
- commonHeader.setSubRequestId("Can I go home?");
+ commonHeader.setSubRequestId(CAN_I_GO_HOME);
assertFalse(commonHeader.equals(copiedLcmCommonHeader));
- copiedLcmCommonHeader.setSubRequestId("Can I go home?");
+ copiedLcmCommonHeader.setSubRequestId(CAN_I_GO_HOME);
assertTrue(commonHeader.equals(copiedLcmCommonHeader));
commonHeader.setTimeStamp(null);
diff --git a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmRequestTest.java b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmRequestTest.java
index 4b392f816..40662935d 100644
--- a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmRequestTest.java
+++ b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmRequestTest.java
@@ -34,6 +34,9 @@ import org.junit.Test;
public class LcmRequestTest {
+ private static final String THE_EMERALD_CITY = "The Emerald City";
+ private static final String GO_TO_OZ = "Go to Oz";
+
@Test
public void testLcmRequest() {
LcmRequest request = new LcmRequest();
@@ -45,8 +48,8 @@ public class LcmRequestTest {
request.setCommonHeader(commonHeader);
assertEquals(commonHeader, request.getCommonHeader());
- request.setAction("Go to Oz");
- assertEquals("Go to Oz", request.getAction());
+ request.setAction(GO_TO_OZ);
+ assertEquals(GO_TO_OZ, request.getAction());
Map<String, String> actionIdentifiers = new HashMap<>();
actionIdentifiers.put("North", "Good Witch");
@@ -55,8 +58,8 @@ public class LcmRequestTest {
request.setActionIdentifiers(actionIdentifiers);
assertEquals(actionIdentifiers, request.getActionIdentifiers());
- request.setPayload("The Emerald City");
- assertEquals("The Emerald City", request.getPayload());
+ request.setPayload(THE_EMERALD_CITY);
+ assertEquals(THE_EMERALD_CITY, request.getPayload());
assertNotEquals(0, request.hashCode());
@@ -86,9 +89,9 @@ public class LcmRequestTest {
assertFalse(request.equals(copiedLcmRequest));
copiedLcmRequest.setAction(null);
assertTrue(request.equals(copiedLcmRequest));
- request.setAction("Go to Oz");
+ request.setAction(GO_TO_OZ);
assertFalse(request.equals(copiedLcmRequest));
- copiedLcmRequest.setAction("Go to Oz");
+ copiedLcmRequest.setAction(GO_TO_OZ);
assertTrue(request.equals(copiedLcmRequest));
request.setActionIdentifiers(null);
@@ -104,9 +107,9 @@ public class LcmRequestTest {
assertFalse(request.equals(copiedLcmRequest));
copiedLcmRequest.setPayload(null);
assertTrue(request.equals(copiedLcmRequest));
- request.setPayload("The Emerald City");
+ request.setPayload(THE_EMERALD_CITY);
assertFalse(request.equals(copiedLcmRequest));
- copiedLcmRequest.setPayload("The Emerald City");
+ copiedLcmRequest.setPayload(THE_EMERALD_CITY);
assertTrue(request.equals(copiedLcmRequest));
}
}
diff --git a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmResponseStatusTest.java b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmResponseStatusTest.java
index b022aa1cb..a4d1bc6d1 100644
--- a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmResponseStatusTest.java
+++ b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmResponseStatusTest.java
@@ -31,6 +31,8 @@ import org.junit.Test;
public class LcmResponseStatusTest {
+ private static final String THE_WONDERFUL_LAND_OF_OZ = "The wonderful land of Oz";
+
@Test
public void testResonseStatus() {
LcmResponseStatus status = new LcmResponseStatus();
@@ -40,8 +42,8 @@ public class LcmResponseStatusTest {
status.setCode(1234);
assertEquals(1234, status.getCode());
- status.setMessage("The wonderful land of Oz");
- assertEquals("The wonderful land of Oz", status.getMessage());
+ status.setMessage(THE_WONDERFUL_LAND_OF_OZ);
+ assertEquals(THE_WONDERFUL_LAND_OF_OZ, status.getMessage());
assertEquals("ResponseStatus [code=1234, message=The wonderfu", status.toString().substring(0, 47));
@@ -67,9 +69,9 @@ public class LcmResponseStatusTest {
assertFalse(status.equals(copiedStatus));
copiedStatus.setMessage(null);
assertTrue(status.equals(copiedStatus));
- status.setMessage("The wonderful land of Oz");
+ status.setMessage(THE_WONDERFUL_LAND_OF_OZ);
assertFalse(status.equals(copiedStatus));
- copiedStatus.setMessage("The wonderful land of Oz");
+ copiedStatus.setMessage(THE_WONDERFUL_LAND_OF_OZ);
assertTrue(status.equals(copiedStatus));
}
}
diff --git a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmWrapperTest.java b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmWrapperTest.java
index 18fdc8ca2..7d005cdd4 100644
--- a/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmWrapperTest.java
+++ b/models-interactions/model-impl/appclcm/src/test/java/org/onap/policy/appclcm/LcmWrapperTest.java
@@ -31,26 +31,32 @@ import org.junit.Test;
public class LcmWrapperTest {
+ private static final String YELLOW_BRICK_ROAD = "YellowBrickRoad";
+ private static final String TORNADO = "Tornado";
+ private static final String THE_EMERALD_CITY = "The Emerald City";
+ private static final String MUNCHKIN = "Munchkin";
+ private static final String VERSION19 = "19.3.9";
+
@Test
public void testLcmWrapper() {
LcmWrapper wrapper = new LcmWrapper();
assertNotNull(wrapper);
assertNotEquals(0, wrapper.hashCode());
- wrapper.setVersion("19.3.9");
- assertEquals("19.3.9", wrapper.getVersion());
+ wrapper.setVersion(VERSION19);
+ assertEquals(VERSION19, wrapper.getVersion());
- wrapper.setCambriaPartition("The Emerald City");
- assertEquals("The Emerald City", wrapper.getCambriaPartition());
+ wrapper.setCambriaPartition(THE_EMERALD_CITY);
+ assertEquals(THE_EMERALD_CITY, wrapper.getCambriaPartition());
- wrapper.setRpcName("Tornado");
- assertEquals("Tornado", wrapper.getRpcName());
+ wrapper.setRpcName(TORNADO);
+ assertEquals(TORNADO, wrapper.getRpcName());
- wrapper.setCorrelationId("YellowBrickRoad");
- assertEquals("YellowBrickRoad", wrapper.getCorrelationId());
+ wrapper.setCorrelationId(YELLOW_BRICK_ROAD);
+ assertEquals(YELLOW_BRICK_ROAD, wrapper.getCorrelationId());
- wrapper.setType("Munchkin");
- assertEquals("Munchkin", wrapper.getType());
+ wrapper.setType(MUNCHKIN);
+ assertEquals(MUNCHKIN, wrapper.getType());
assertNotEquals(0, wrapper.hashCode());
@@ -72,45 +78,45 @@ public class LcmWrapperTest {
assertFalse(wrapper.equals(copiedLcmWrapper));
copiedLcmWrapper.setVersion(null);
assertTrue(wrapper.equals(copiedLcmWrapper));
- wrapper.setVersion("19.3.9");
+ wrapper.setVersion(VERSION19);
assertFalse(wrapper.equals(copiedLcmWrapper));
- copiedLcmWrapper.setVersion("19.3.9");
+ copiedLcmWrapper.setVersion(VERSION19);
assertTrue(wrapper.equals(copiedLcmWrapper));
wrapper.setCambriaPartition(null);
assertFalse(wrapper.equals(copiedLcmWrapper));
copiedLcmWrapper.setCambriaPartition(null);
assertTrue(wrapper.equals(copiedLcmWrapper));
- wrapper.setCambriaPartition("The Emerald City");
+ wrapper.setCambriaPartition(THE_EMERALD_CITY);
assertFalse(wrapper.equals(copiedLcmWrapper));
- copiedLcmWrapper.setCambriaPartition("The Emerald City");
+ copiedLcmWrapper.setCambriaPartition(THE_EMERALD_CITY);
assertTrue(wrapper.equals(copiedLcmWrapper));
wrapper.setRpcName(null);
assertFalse(wrapper.equals(copiedLcmWrapper));
copiedLcmWrapper.setRpcName(null);
assertTrue(wrapper.equals(copiedLcmWrapper));
- wrapper.setRpcName("Tornado");
+ wrapper.setRpcName(TORNADO);
assertFalse(wrapper.equals(copiedLcmWrapper));
- copiedLcmWrapper.setRpcName("Tornado");
+ copiedLcmWrapper.setRpcName(TORNADO);
assertTrue(wrapper.equals(copiedLcmWrapper));
wrapper.setCorrelationId(null);
assertFalse(wrapper.equals(copiedLcmWrapper));
copiedLcmWrapper.setCorrelationId(null);
assertTrue(wrapper.equals(copiedLcmWrapper));
- wrapper.setCorrelationId("YellowBrickRoad");
+ wrapper.setCorrelationId(YELLOW_BRICK_ROAD);
assertFalse(wrapper.equals(copiedLcmWrapper));
- copiedLcmWrapper.setCorrelationId("YellowBrickRoad");
+ copiedLcmWrapper.setCorrelationId(YELLOW_BRICK_ROAD);
assertTrue(wrapper.equals(copiedLcmWrapper));
wrapper.setType(null);
assertFalse(wrapper.equals(copiedLcmWrapper));
copiedLcmWrapper.setType(null);
assertTrue(wrapper.equals(copiedLcmWrapper));
- wrapper.setType("Munchkin");
+ wrapper.setType(MUNCHKIN);
assertFalse(wrapper.equals(copiedLcmWrapper));
- copiedLcmWrapper.setType("Munchkin");
+ copiedLcmWrapper.setType(MUNCHKIN);
assertTrue(wrapper.equals(copiedLcmWrapper));
}
}
diff --git a/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptor.java b/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptor.java
index 3957fe5e4..17eefd227 100644
--- a/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptor.java
+++ b/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptor.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Bell Canada.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -49,12 +50,12 @@ public class BasicAuthClientHeaderInterceptor implements ClientInterceptor {
}
@Override
- public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method,
+ public <Q, P> ClientCall<Q, P> interceptCall(MethodDescriptor<Q, P> method,
CallOptions callOptions, Channel channel) {
Key<String> authHeader = Key.of(BASIC_AUTH_HEADER_KEY, Metadata.ASCII_STRING_MARSHALLER);
- return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(channel.newCall(method, callOptions)) {
+ return new ForwardingClientCall.SimpleForwardingClientCall<Q, P>(channel.newCall(method, callOptions)) {
@Override
- public void start(Listener<RespT> responseListener, Metadata headers) {
+ public void start(Listener<P> responseListener, Metadata headers) {
headers.put(authHeader, props.getBasicAuth());
super.start(responseListener, headers);
}
diff --git a/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/properties/CdsServerProperties.java b/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/properties/CdsServerProperties.java
index 94a336b6d..2e919814b 100644
--- a/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/properties/CdsServerProperties.java
+++ b/models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/properties/CdsServerProperties.java
@@ -39,7 +39,6 @@ public class CdsServerProperties implements ParameterGroup {
private static final int MIN_USER_PORT = 1024;
private static final int MAX_USER_PORT = 65535;
- private static final String INVALID_PROP = "Invalid CDS property: ";
private static final String SERVER_PROPERTIES_TYPE = "CDS gRPC Server Properties";
// CDS carrier properties
diff --git a/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptorTest.java b/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptorTest.java
index 3b6ad7da1..fedf4703c 100644
--- a/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptorTest.java
+++ b/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/BasicAuthClientHeaderInterceptorTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Bell Canada.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -127,9 +128,8 @@ public class BasicAuthClientHeaderInterceptorTest {
private static class TestServerInterceptor implements ServerInterceptor {
@Override
- public <ReqT, RespT> Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
- final Metadata metadata,
- final ServerCallHandler<ReqT, RespT> serverCallHandler) {
+ public <Q, P> Listener<Q> interceptCall(final ServerCall<Q, P> serverCall,
+ final Metadata metadata, final ServerCallHandler<Q, P> serverCallHandler) {
return serverCallHandler.startCall(serverCall, metadata);
}
}
diff --git a/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/CdsProcessorGrpcClientTest.java b/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/CdsProcessorGrpcClientTest.java
index b9a9a84cd..17b4dc534 100644
--- a/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/CdsProcessorGrpcClientTest.java
+++ b/models-interactions/model-impl/cds/src/test/java/org/onap/policy/cds/client/CdsProcessorGrpcClientTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Bell Canada.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -19,9 +20,8 @@
package org.onap.policy.cds.client;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@@ -128,13 +128,13 @@ public class CdsProcessorGrpcClientTest {
@Test
public void testCdsProcessorGrpcClientConstructor() {
- new CdsProcessorGrpcClient(listener, props);
+ new CdsProcessorGrpcClient(listener, props).close();
}
@Test(expected = IllegalStateException.class)
public void testCdsProcessorGrpcClientConstructorFailure() {
props.setHost(null);
- new CdsProcessorGrpcClient(listener, props);
+ new CdsProcessorGrpcClient(listener, props).close();
}
@Test
diff --git a/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/ControlLoopNotificationTest.java b/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/ControlLoopNotificationTest.java
index 0c1070e44..2ad097254 100644
--- a/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/ControlLoopNotificationTest.java
+++ b/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/ControlLoopNotificationTest.java
@@ -61,7 +61,7 @@ public class ControlLoopNotificationTest {
assertEquals("from", notification.getFrom());
notification.setHistory(Collections.emptyList());
- assertTrue(notification.getHistory().size() == 0);
+ assertTrue(notification.getHistory().isEmpty());
notification.setMessage("message");
assertEquals("message", notification.getMessage());
diff --git a/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/params/ControlLoopParamsTest.java b/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/params/ControlLoopParamsTest.java
index bf23e5706..fd17f782e 100644
--- a/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/params/ControlLoopParamsTest.java
+++ b/models-interactions/model-impl/events/src/test/java/org/onap/policy/controlloop/params/ControlLoopParamsTest.java
@@ -21,8 +21,8 @@
package org.onap.policy.controlloop.params;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import org.junit.Test;
@@ -41,11 +41,11 @@ public class ControlLoopParamsTest {
ControlLoopParams params2 = new ControlLoopParams(params);
- assertTrue(params2.getClosedLoopControlName().equals("name"));
- assertTrue(params2.getControlLoopYaml().equals("yaml"));
- assertTrue(params2.getPolicyName().equals("name"));
- assertTrue(params2.getPolicyScope().equals("scope"));
- assertTrue(params2.getPolicyVersion().equals("1"));
+ assertEquals("name", params2.getClosedLoopControlName());
+ assertEquals("yaml", params2.getControlLoopYaml());
+ assertEquals("name", params2.getPolicyName());
+ assertEquals("scope", params2.getPolicyScope());
+ assertEquals("1", params2.getPolicyVersion());
}
}
diff --git a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceInstanceTest.java b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceInstanceTest.java
index 940963565..8ae0084f6 100644
--- a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceInstanceTest.java
+++ b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceInstanceTest.java
@@ -30,6 +30,10 @@ import org.junit.Test;
public class ResourceInstanceTest {
+ private static final String RESOURCE = "resource";
+ private static final String INSTANCE = "instance";
+ private static final String VERSION_000 = "0.0.0";
+
@Test
public void testConstructors() {
ResourceInstance ri = new ResourceInstance();
@@ -111,11 +115,11 @@ public class ResourceInstanceTest {
assertTrue(ri1.equals(ri2));
assertTrue(ri2.equals(ri1));
- ri1.setResourceInstanceName("instance");
- ri1.setResourceName("resource");
+ ri1.setResourceInstanceName(INSTANCE);
+ ri1.setResourceName(RESOURCE);
ri1.setResourceInvariantUUID(UUID.randomUUID());
ri1.setResourceInvariantUUID(UUID.randomUUID());
- ri1.setResourceVersion("0.0.0");
+ ri1.setResourceVersion(VERSION_000);
ri1.setResourceType(ResourceType.VL);
ri2 = new ResourceInstance(ri1);
assertTrue(ri1.equals(ri2));
@@ -128,11 +132,11 @@ public class ResourceInstanceTest {
ResourceInstance ri2 = new ResourceInstance(ri1);
assertEquals(ri1.toString(), ri2.toString());
- ri1.setResourceInstanceName("instance");
- ri1.setResourceName("resource");
+ ri1.setResourceInstanceName(INSTANCE);
+ ri1.setResourceName(RESOURCE);
ri1.setResourceInvariantUUID(UUID.randomUUID());
ri1.setResourceInvariantUUID(UUID.randomUUID());
- ri1.setResourceVersion("0.0.0");
+ ri1.setResourceVersion(VERSION_000);
ri1.setResourceType(ResourceType.VL);
ri2 = new ResourceInstance(ri1);
assertEquals(ri1.toString(), ri2.toString());
@@ -144,11 +148,11 @@ public class ResourceInstanceTest {
ResourceInstance ri2 = new ResourceInstance(ri1);
assertEquals(ri1.hashCode(), ri2.hashCode());
- ri1.setResourceInstanceName("instance");
- ri1.setResourceName("resource");
+ ri1.setResourceInstanceName(INSTANCE);
+ ri1.setResourceName(RESOURCE);
ri1.setResourceInvariantUUID(UUID.randomUUID());
ri1.setResourceInvariantUUID(UUID.randomUUID());
- ri1.setResourceVersion("0.0.0");
+ ri1.setResourceVersion(VERSION_000);
ri1.setResourceType(ResourceType.VL);
ri2 = new ResourceInstance(ri1);
assertEquals(ri1.hashCode(), ri2.hashCode());
diff --git a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceTest.java b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceTest.java
index 60510a1d1..6949a36f8 100644
--- a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceTest.java
+++ b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ResourceTest.java
@@ -30,6 +30,9 @@ import org.junit.Test;
public class ResourceTest {
+ private static final String EQUALS_TEST = "equalsTest";
+ private static final String VERSION_111 = "1.1.1";
+
@Test
public void testConstructors() {
Resource res = new Resource();
@@ -120,7 +123,7 @@ public class ResourceTest {
assertTrue(r1.equals(r2));
assertTrue(r2.equals(r1));
- r1 = new Resource(UUID.randomUUID(), UUID.randomUUID(), "equalsTest", "1.1.1",
+ r1 = new Resource(UUID.randomUUID(), UUID.randomUUID(), EQUALS_TEST, VERSION_111,
ResourceType.VFC);
r2 = new Resource(r1);
assertTrue(r1.equals(r2));
@@ -133,7 +136,7 @@ public class ResourceTest {
Resource r2 = new Resource(r1);
assertEquals(r1.toString(), r2.toString());
- r1 = new Resource(UUID.randomUUID(), UUID.randomUUID(), "equalsTest", "1.1.1",
+ r1 = new Resource(UUID.randomUUID(), UUID.randomUUID(), EQUALS_TEST, VERSION_111,
ResourceType.VFC);
r2 = new Resource(r1);
assertEquals(r1.toString(), r2.toString());
@@ -145,7 +148,7 @@ public class ResourceTest {
Resource r2 = new Resource(r1);
assertEquals(r1.hashCode(), r2.hashCode());
- r1 = new Resource(UUID.randomUUID(), UUID.randomUUID(), "equalsTest", "1.1.1",
+ r1 = new Resource(UUID.randomUUID(), UUID.randomUUID(), EQUALS_TEST, VERSION_111,
ResourceType.VFC);
r2 = new Resource(r1);
assertEquals(r1.hashCode(), r2.hashCode());
diff --git a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceInstanceTest.java b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceInstanceTest.java
index ca2cb3d0e..c06974cd5 100644
--- a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceInstanceTest.java
+++ b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceInstanceTest.java
@@ -30,6 +30,10 @@ import org.junit.Test;
public class ServiceInstanceTest {
+ private static final String SERVICE = "service";
+ private static final String INSTANCE = "instance";
+ private static final String VERSION_333 = "3.3.3";
+
@Test
public void testConstructors() {
ServiceInstance si = new ServiceInstance();
@@ -123,13 +127,13 @@ public class ServiceInstanceTest {
assertTrue(si1.equals(si2));
assertTrue(si2.equals(si1));
- si1.setServiceInstanceName("instance");
- si1.setServiceName("service");
+ si1.setServiceInstanceName(INSTANCE);
+ si1.setServiceName(SERVICE);
si1.setServiceInstanceUUID(UUID.randomUUID());
si1.setServiceUUID(UUID.randomUUID());
si1.setPersonaModelUUID(UUID.randomUUID());
si1.setWidgetModelUUID(UUID.randomUUID());
- si1.setWidgetModelVersion("3.3.3");
+ si1.setWidgetModelVersion(VERSION_333);
si2 = new ServiceInstance(si1);
assertTrue(si1.equals(si2));
assertTrue(si2.equals(si1));
@@ -141,13 +145,13 @@ public class ServiceInstanceTest {
ServiceInstance si2 = new ServiceInstance(si1);
assertEquals(si1.toString(), si2.toString());
- si1.setServiceInstanceName("instance");
- si1.setServiceName("service");
+ si1.setServiceInstanceName(INSTANCE);
+ si1.setServiceName(SERVICE);
si1.setServiceInstanceUUID(UUID.randomUUID());
si1.setServiceUUID(UUID.randomUUID());
si1.setPersonaModelUUID(UUID.randomUUID());
si1.setWidgetModelUUID(UUID.randomUUID());
- si1.setWidgetModelVersion("3.3.3");
+ si1.setWidgetModelVersion(VERSION_333);
si2 = new ServiceInstance(si1);
assertEquals(si1.toString(), si2.toString());
}
@@ -158,13 +162,13 @@ public class ServiceInstanceTest {
ServiceInstance si2 = new ServiceInstance(si1);
assertEquals(si1.hashCode(), si2.hashCode());
- si1.setServiceInstanceName("instance");
- si1.setServiceName("service");
+ si1.setServiceInstanceName(INSTANCE);
+ si1.setServiceName(SERVICE);
si1.setServiceInstanceUUID(UUID.randomUUID());
si1.setServiceUUID(UUID.randomUUID());
si1.setPersonaModelUUID(UUID.randomUUID());
si1.setWidgetModelUUID(UUID.randomUUID());
- si1.setWidgetModelVersion("3.3.3");
+ si1.setWidgetModelVersion(VERSION_333);
si2 = new ServiceInstance(si1);
assertEquals(si1.hashCode(), si2.hashCode());
}
diff --git a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceTest.java b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceTest.java
index 3bf6a537e..19238622d 100644
--- a/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceTest.java
+++ b/models-interactions/model-impl/sdc/src/test/java/org/onap/policy/sdc/ServiceTest.java
@@ -30,6 +30,9 @@ import org.junit.Test;
public class ServiceTest {
+ private static final String EQUALS_TEST = "equalsTest";
+ private static final String VERSION_111 = "1.1.1";
+
@Test
public void testConstructors() {
Service svc = new Service();
@@ -108,7 +111,7 @@ public class ServiceTest {
assertTrue(s1.equals(s2));
assertTrue(s2.equals(s1));
- s1 = new Service(UUID.randomUUID(), UUID.randomUUID(), "equalsTest", "1.1.1");
+ s1 = new Service(UUID.randomUUID(), UUID.randomUUID(), EQUALS_TEST, VERSION_111);
s2 = new Service(s1);
assertTrue(s1.equals(s2));
assertTrue(s2.equals(s1));
@@ -120,7 +123,7 @@ public class ServiceTest {
Service s2 = new Service(s1);
assertEquals(s1.toString(), s2.toString());
- s1 = new Service(UUID.randomUUID(), UUID.randomUUID(), "equalsTest", "1.1.1");
+ s1 = new Service(UUID.randomUUID(), UUID.randomUUID(), EQUALS_TEST, VERSION_111);
s2 = new Service(s1);
assertEquals(s1.toString(), s2.toString());
}
@@ -131,7 +134,7 @@ public class ServiceTest {
Service s2 = new Service(s1);
assertEquals(s1.hashCode(), s2.hashCode());
- s1 = new Service(UUID.randomUUID(), UUID.randomUUID(), "equalsTest", "1.1.1");
+ s1 = new Service(UUID.randomUUID(), UUID.randomUUID(), EQUALS_TEST, VERSION_111);
s2 = new Service(s1);
assertEquals(s1.hashCode(), s2.hashCode());
}
diff --git a/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java b/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java
index 3679625ec..7612eeb3f 100644
--- a/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java
+++ b/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java
@@ -49,6 +49,7 @@ public final class SdncManager implements Runnable {
// The REST manager used for processing REST calls for this Sdnc manager
private RestManager restManager;
+ @FunctionalInterface
public interface SdncCallback {
public void onCallback(SdncResponse response);
}
@@ -133,7 +134,7 @@ public final class SdncManager implements Runnable {
logger.info(body);
response.setRequestId(sdncRequest.getRequestId().toString());
- if (!response.getResponseOutput().getResponseCode().equals("200")) {
+ if (!"200".equals(response.getResponseOutput().getResponseCode())) {
logger.info(
"Sdnc Heal Restcall failed with http error code {} {}", httpDetails.first, httpDetails.second
);
diff --git a/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/util/Serialization.java b/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/util/Serialization.java
index cfaa46fd0..090b4f9b6 100644
--- a/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/util/Serialization.java
+++ b/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/util/Serialization.java
@@ -2,6 +2,7 @@
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Huawei. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -23,11 +24,12 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public final class Serialization {
- private Serialization() {
- }
-
+
public static final Gson gsonPretty = new GsonBuilder().disableHtmlEscaping()
.setPrettyPrinting()
.create();
+ private Serialization() {
+
+ }
}
diff --git a/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/DemoTest.java b/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/DemoTest.java
index 1c18d9c8f..41f07c3c7 100644
--- a/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/DemoTest.java
+++ b/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/DemoTest.java
@@ -2,6 +2,7 @@
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Huawei. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -21,8 +22,11 @@ package org.onap.policy.sdnc;
import org.junit.Test;
import org.onap.policy.sdnc.util.Serialization;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DemoTest {
+ private static final Logger logger = LoggerFactory.getLogger(DemoTest.class);
@Test
public void test() {
@@ -37,34 +41,34 @@ public class DemoTest {
request.getHealRequest().setRequestInfo(new SdncHealRequestInfo());
request.getHealRequest().getRequestInfo().setRequestAction("request-action");
-
+
request.getHealRequest().setServiceInfo(new SdncHealServiceInfo());
request.getHealRequest().getServiceInfo().setServiceInstanceId("service-instance-01");
-
+
request.getHealRequest().setNetworkInfo(new SdncHealNetworkInfo());
request.getHealRequest().getNetworkInfo().setNetworkId("network-5555");
-
+
String body = Serialization.gsonPretty.toJson(request);
- System.out.println(body);
+ logger.info("{}", body);
SdncResponse response = new SdncResponse();
body = Serialization.gsonPretty.toJson(response);
- System.out.println(body);
+ logger.info("{}", body);
response.setRequestId("request-01");
response.setResponseOutput(new SdncResponseOutput());
response.getResponseOutput().setSvcRequestId("service-req-01");
response.getResponseOutput().setResponseCode("200");
response.getResponseOutput().setAckFinalIndicator("final-indicator-00");
-
+
body = Serialization.gsonPretty.toJson(response);
- System.out.println(body);
+ logger.info("{}", body);
response = Serialization.gsonPretty.fromJson(body, SdncResponse.class);
body = Serialization.gsonPretty.toJson(response);
- System.out.println(body);
+ logger.info("{}", body);
}
}
diff --git a/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java b/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java
index 2a1cc6984..c069f1c3b 100644
--- a/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java
+++ b/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java
@@ -23,8 +23,7 @@
package org.onap.policy.sdnc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.endsWith;
@@ -35,7 +34,6 @@ import static org.mockito.Mockito.when;
import java.util.UUID;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.rest.RestManager;
import org.onap.policy.rest.RestManager.Pair;
@@ -43,6 +41,10 @@ import org.onap.policy.sdnc.SdncManager.SdncCallback;
import org.onap.policy.sdnc.util.Serialization;
public class SdncManagerTest implements SdncCallback {
+ private static final String SOMEWHERE_OVER_THE_RAINBOW = "http://somewhere.over.the.rainbow";
+
+ private static final String DOROTHY = "Dorothy";
+
private RestManager mockedRestManager;
private Pair<Integer, String> httpResponsePutOk;
@@ -53,10 +55,6 @@ public class SdncManagerTest implements SdncCallback {
private SdncRequest request;
private SdncResponse response;
- @BeforeClass
- public static void beforeTestSdncManager() {
- }
-
/**
* Set up the mocked REST manager.
*/
@@ -90,7 +88,7 @@ public class SdncManagerTest implements SdncCallback {
request = new SdncRequest();
request.setRequestId(requestId);
request.setHealRequest(healRequest);
- request.setNsInstanceId("Dorothy");
+ request.setNsInstanceId(DOROTHY);
SdncResponseOutput responseDescriptor = new SdncResponseOutput();
responseDescriptor.setSvcRequestId("1234");
@@ -103,53 +101,30 @@ public class SdncManagerTest implements SdncCallback {
}
@Test
- public void testSdncInitiation() throws InterruptedException {
- try {
- new SdncManager(null, null, null, null, null);
- fail("test should throw an exception here");
- }
- catch (IllegalArgumentException e) {
- assertEquals(
- "the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null",
- e.getMessage()
- );
- }
-
- try {
- new SdncManager(this, null, null, null, null);
- fail("test should throw an exception here");
- }
- catch (IllegalArgumentException e) {
- assertEquals(
- "the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null",
- e.getMessage()
- );
- }
-
- try {
- new SdncManager(this, request, null, null, null);
- fail("test should throw an exception here");
- }
- catch (IllegalArgumentException e) {
- assertEquals(
- "the \"url\" parameter on the SdncManager constructor may not be null",
- e.getMessage()
- );
- }
-
- new SdncManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Toto");
+ public void testSdncInitiation() {
+
+ assertThatIllegalArgumentException().isThrownBy(() -> new SdncManager(null, null, null, null, null))
+ .withMessage("the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null");
+
+ assertThatIllegalArgumentException().isThrownBy(() -> new SdncManager(this, null, null, null, null))
+ .withMessage("the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null");
+
+ assertThatIllegalArgumentException().isThrownBy(() -> new SdncManager(this, request, null, null, null))
+ .withMessage("the \"url\" parameter on the SdncManager constructor may not be null");
+
+ new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Toto");
}
@Test
public void testSdncExecutionException() throws InterruptedException {
- SdncManager manager = new SdncManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Exception");
+ SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Exception");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Exception"), anyMap(), anyString(), anyString()))
- .thenThrow(new RuntimeException("OzException"));
+ when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("Exception"), anyMap(),
+ anyString(), anyString())).thenThrow(new RuntimeException("OzException"));
managerThread.join(100);
@@ -157,14 +132,14 @@ public class SdncManagerTest implements SdncCallback {
@Test
public void testSdncExecutionNull() throws InterruptedException {
- SdncManager manager = new SdncManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Null");
+ SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Null");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Null"), anyMap(), anyString(), anyString()))
- .thenReturn(null);
+ when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("Null"), anyMap(),
+ anyString(), anyString())).thenReturn(null);
managerThread.join(100);
}
@@ -172,44 +147,44 @@ public class SdncManagerTest implements SdncCallback {
@Test
public void testSdncExecutionError0() throws InterruptedException {
- SdncManager manager = new SdncManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Error0");
+ SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Error0");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("Error0"), anyMap(), anyString(), anyString()))
- .thenReturn(httpResponseErr);
+ when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("Error0"), anyMap(),
+ anyString(), anyString())).thenReturn(httpResponseErr);
managerThread.join(100);
}
@Test
public void testSdncExecutionBadResponse() throws InterruptedException {
- SdncManager manager = new SdncManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "BadResponse");
+ SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "BadResponse");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString()))
- .thenReturn(httpResponseBadResponse);
+ when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("OK"), anyMap(),
+ anyString(), anyString())).thenReturn(httpResponseBadResponse);
managerThread.join(100);
}
@Test
public void testSdncExecutionOk() throws InterruptedException {
- SdncManager manager = new SdncManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "OOK");
+ SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "OOK");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"), eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString()))
- .thenReturn(httpResponsePutOk);
+ when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("OK"), anyMap(),
+ anyString(), anyString())).thenReturn(httpResponsePutOk);
- when(mockedRestManager.get(endsWith("1234"), eq("Dorothy"), eq("OK"), anyMap()))
+ when(mockedRestManager.get(endsWith("1234"), eq(DOROTHY), eq("OK"), anyMap()))
.thenReturn(httpResponseGetOk);
diff --git a/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciCommonHeader.java b/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciCommonHeader.java
index f575a73c3..8552bb23c 100644
--- a/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciCommonHeader.java
+++ b/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciCommonHeader.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -148,6 +149,7 @@ public class PciCommonHeader implements Serializable {
public void setSubRequestId(String subRequestId) {
this.subRequestId = subRequestId;
}
+
/**
* Set the request track.
*
@@ -157,6 +159,7 @@ public class PciCommonHeader implements Serializable {
public void setRequestTrack(Map<String, String> requestTrack) {
this.requestTrack = requestTrack;
}
+
/**
* Get the request track.
*
diff --git a/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciRequest.java b/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciRequest.java
index 73ee4c65d..d76dd88b5 100644
--- a/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciRequest.java
+++ b/models-interactions/model-impl/sdnr/src/main/java/org/onap/policy/sdnr/PciRequest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -82,8 +83,8 @@ public class PciRequest implements Serializable {
/**
* Set the payload.
*
- * @param action
- * the action to set
+ * @param payload
+ * the payload to set
*/
public void setPayload(String payload) {
diff --git a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciCommonHeaderTest.java b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciCommonHeaderTest.java
index f0cc246b9..84178e062 100644
--- a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciCommonHeaderTest.java
+++ b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciCommonHeaderTest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -36,6 +37,9 @@ import org.junit.Test;
public class PciCommonHeaderTest {
+ private static final String KANSAS = "Kansas";
+ private static final String CAN_I_GO_HOME = "Can I go home?";
+
@Test
public void testPciCommonHeader() {
PciCommonHeader commonHeader = new PciCommonHeader();
@@ -43,8 +47,8 @@ public class PciCommonHeaderTest {
assertNotNull(new PciCommonHeader(commonHeader));
assertNotEquals(0, commonHeader.hashCode());
- commonHeader.setApiVer("Kansas");
- assertEquals("Kansas", commonHeader.getApiVer());
+ commonHeader.setApiVer(KANSAS);
+ assertEquals(KANSAS, commonHeader.getApiVer());
Map<String, String> flagMap = new HashMap<>();
commonHeader.setFlags(flagMap);
@@ -58,8 +62,8 @@ public class PciCommonHeaderTest {
commonHeader.setRequestId(requestId);
assertEquals(requestId, commonHeader.getRequestId());
- commonHeader.setSubRequestId("Can I go home?");
- assertEquals("Can I go home?", commonHeader.getSubRequestId());
+ commonHeader.setSubRequestId(CAN_I_GO_HOME);
+ assertEquals(CAN_I_GO_HOME, commonHeader.getSubRequestId());
Instant timestamp = Instant.now();
commonHeader.setTimeStamp(timestamp);
@@ -91,9 +95,9 @@ public class PciCommonHeaderTest {
assertFalse(commonHeader.equals(copiedPciCommonHeader));
copiedPciCommonHeader.setApiVer(null);
assertTrue(commonHeader.equals(copiedPciCommonHeader));
- commonHeader.setApiVer("Kansas");
+ commonHeader.setApiVer(KANSAS);
assertFalse(commonHeader.equals(copiedPciCommonHeader));
- copiedPciCommonHeader.setApiVer("Kansas");
+ copiedPciCommonHeader.setApiVer(KANSAS);
assertTrue(commonHeader.equals(copiedPciCommonHeader));
commonHeader.setFlags(null);
@@ -128,9 +132,9 @@ public class PciCommonHeaderTest {
assertFalse(commonHeader.equals(copiedPciCommonHeader));
copiedPciCommonHeader.setSubRequestId(null);
assertTrue(commonHeader.equals(copiedPciCommonHeader));
- commonHeader.setSubRequestId("Can I go home?");
+ commonHeader.setSubRequestId(CAN_I_GO_HOME);
assertFalse(commonHeader.equals(copiedPciCommonHeader));
- copiedPciCommonHeader.setSubRequestId("Can I go home?");
+ copiedPciCommonHeader.setSubRequestId(CAN_I_GO_HOME);
assertTrue(commonHeader.equals(copiedPciCommonHeader));
commonHeader.setTimeStamp(null);
diff --git a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciRequestTest.java b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciRequestTest.java
index 023dd18ca..0009c2a5c 100644
--- a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciRequestTest.java
+++ b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciRequestTest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -31,6 +32,8 @@ import org.junit.Test;
public class PciRequestTest {
+ private static final String MODIFY = "Modify";
+
@Test
public void testPciRequest() {
PciRequest request = new PciRequest();
@@ -46,8 +49,8 @@ public class PciRequestTest {
request.setPayload(requestPayload);
assertEquals(requestPayload, request.getPayload());
- request.setAction("Modify");
- assertEquals("Modify", request.getAction());
+ request.setAction(MODIFY);
+ assertEquals(MODIFY, request.getAction());
assertNotEquals(0, request.hashCode());
@@ -76,9 +79,9 @@ public class PciRequestTest {
assertFalse(request.equals(copiedPciRequest));
copiedPciRequest.setAction(null);
assertTrue(request.equals(copiedPciRequest));
- request.setAction("Modify");
+ request.setAction(MODIFY);
assertFalse(request.equals(copiedPciRequest));
- copiedPciRequest.setAction("Modify");
+ copiedPciRequest.setAction(MODIFY);
assertTrue(request.equals(copiedPciRequest));
request.setPayload(null);
diff --git a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciResponseTest.java b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciResponseTest.java
index 27f4c23cf..6e990ea12 100644
--- a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciResponseTest.java
+++ b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciResponseTest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -97,9 +98,9 @@ public class PciResponseTest {
response2.setStatus(response.getStatus());
assertTrue(response.equals(response2));
- Status status = new Status();
- status.setCode(5);
- response.setStatus(status);
+ Status stat = new Status();
+ stat.setCode(5);
+ response.setStatus(stat);
response2.setStatus(new Status());
assertFalse(response.equals(response2));
}
diff --git a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciStatusTest.java b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciStatusTest.java
index f8f5820dc..08ac56b85 100644
--- a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciStatusTest.java
+++ b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciStatusTest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -31,6 +32,8 @@ import org.junit.Test;
public class PciStatusTest {
+ private static final String THE_WONDERFUL_LAND_OF_OZ = "The wonderful land of Oz";
+
@Test
public void testResponseStatus() {
Status status = new Status();
@@ -40,8 +43,8 @@ public class PciStatusTest {
status.setCode(1234);
assertEquals(1234, status.getCode());
- status.setValue("The wonderful land of Oz");
- assertEquals("The wonderful land of Oz", status.getValue());
+ status.setValue(THE_WONDERFUL_LAND_OF_OZ);
+ assertEquals(THE_WONDERFUL_LAND_OF_OZ, status.getValue());
assertEquals("Status [code = 1234, value = The wonderfu", status.toString().substring(0, 41));
@@ -67,9 +70,9 @@ public class PciStatusTest {
assertFalse(status.equals(copiedStatus));
copiedStatus.setValue(null);
assertTrue(status.equals(copiedStatus));
- status.setValue("The wonderful land of Oz");
+ status.setValue(THE_WONDERFUL_LAND_OF_OZ);
assertFalse(status.equals(copiedStatus));
- copiedStatus.setValue("The wonderful land of Oz");
+ copiedStatus.setValue(THE_WONDERFUL_LAND_OF_OZ);
assertTrue(status.equals(copiedStatus));
}
}
diff --git a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciWrapperTest.java b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciWrapperTest.java
index 151d3343a..f05f50e67 100644
--- a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciWrapperTest.java
+++ b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/PciWrapperTest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -31,26 +32,32 @@ import org.junit.Test;
public class PciWrapperTest {
+ private static final String YELLOW_BRICK_ROAD = "YellowBrickRoad";
+ private static final String TORNADO = "Tornado";
+ private static final String THE_EMERALD_CITY = "The Emerald City";
+ private static final String MUNCHKIN = "Munchkin";
+ private static final String VERSION_19 = "19.3.9";
+
@Test
public void testPciWrapper() {
PciWrapper wrapper = new PciWrapper();
assertNotNull(wrapper);
assertNotEquals(0, wrapper.hashCode());
- wrapper.setVersion("19.3.9");
- assertEquals("19.3.9", wrapper.getVersion());
+ wrapper.setVersion(VERSION_19);
+ assertEquals(VERSION_19, wrapper.getVersion());
- wrapper.setCambriaPartition("The Emerald City");
- assertEquals("The Emerald City", wrapper.getCambriaPartition());
+ wrapper.setCambriaPartition(THE_EMERALD_CITY);
+ assertEquals(THE_EMERALD_CITY, wrapper.getCambriaPartition());
- wrapper.setRpcName("Tornado");
- assertEquals("Tornado", wrapper.getRpcName());
+ wrapper.setRpcName(TORNADO);
+ assertEquals(TORNADO, wrapper.getRpcName());
- wrapper.setCorrelationId("YellowBrickRoad");
- assertEquals("YellowBrickRoad", wrapper.getCorrelationId());
+ wrapper.setCorrelationId(YELLOW_BRICK_ROAD);
+ assertEquals(YELLOW_BRICK_ROAD, wrapper.getCorrelationId());
- wrapper.setType("Munchkin");
- assertEquals("Munchkin", wrapper.getType());
+ wrapper.setType(MUNCHKIN);
+ assertEquals(MUNCHKIN, wrapper.getType());
assertNotEquals(0, wrapper.hashCode());
@@ -72,45 +79,45 @@ public class PciWrapperTest {
assertFalse(wrapper.equals(copiedPciWrapper));
copiedPciWrapper.setVersion(null);
assertTrue(wrapper.equals(copiedPciWrapper));
- wrapper.setVersion("19.3.9");
+ wrapper.setVersion(VERSION_19);
assertFalse(wrapper.equals(copiedPciWrapper));
- copiedPciWrapper.setVersion("19.3.9");
+ copiedPciWrapper.setVersion(VERSION_19);
assertTrue(wrapper.equals(copiedPciWrapper));
wrapper.setCambriaPartition(null);
assertFalse(wrapper.equals(copiedPciWrapper));
copiedPciWrapper.setCambriaPartition(null);
assertTrue(wrapper.equals(copiedPciWrapper));
- wrapper.setCambriaPartition("The Emerald City");
+ wrapper.setCambriaPartition(THE_EMERALD_CITY);
assertFalse(wrapper.equals(copiedPciWrapper));
- copiedPciWrapper.setCambriaPartition("The Emerald City");
+ copiedPciWrapper.setCambriaPartition(THE_EMERALD_CITY);
assertTrue(wrapper.equals(copiedPciWrapper));
wrapper.setRpcName(null);
assertFalse(wrapper.equals(copiedPciWrapper));
copiedPciWrapper.setRpcName(null);
assertTrue(wrapper.equals(copiedPciWrapper));
- wrapper.setRpcName("Tornado");
+ wrapper.setRpcName(TORNADO);
assertFalse(wrapper.equals(copiedPciWrapper));
- copiedPciWrapper.setRpcName("Tornado");
+ copiedPciWrapper.setRpcName(TORNADO);
assertTrue(wrapper.equals(copiedPciWrapper));
wrapper.setCorrelationId(null);
assertFalse(wrapper.equals(copiedPciWrapper));
copiedPciWrapper.setCorrelationId(null);
assertTrue(wrapper.equals(copiedPciWrapper));
- wrapper.setCorrelationId("YellowBrickRoad");
+ wrapper.setCorrelationId(YELLOW_BRICK_ROAD);
assertFalse(wrapper.equals(copiedPciWrapper));
- copiedPciWrapper.setCorrelationId("YellowBrickRoad");
+ copiedPciWrapper.setCorrelationId(YELLOW_BRICK_ROAD);
assertTrue(wrapper.equals(copiedPciWrapper));
wrapper.setType(null);
assertFalse(wrapper.equals(copiedPciWrapper));
copiedPciWrapper.setType(null);
assertTrue(wrapper.equals(copiedPciWrapper));
- wrapper.setType("Munchkin");
+ wrapper.setType(MUNCHKIN);
assertFalse(wrapper.equals(copiedPciWrapper));
- copiedPciWrapper.setType("Munchkin");
+ copiedPciWrapper.setType(MUNCHKIN);
assertTrue(wrapper.equals(copiedPciWrapper));
}
}
diff --git a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/SdnrTest.java b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/SdnrTest.java
index 8317482cc..4cbda52ec 100644
--- a/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/SdnrTest.java
+++ b/models-interactions/model-impl/sdnr/src/test/java/org/onap/policy/sdnr/SdnrTest.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -35,6 +36,8 @@ import org.slf4j.LoggerFactory;
public class SdnrTest {
+ private static final String CORRELATION_ID = "664be3d2-6c12-4f4b-a3e7-c349acced200";
+
private static final Logger logger = LoggerFactory.getLogger(SdnrTest.class);
private static PciRequestWrapper dmaapRequest;
@@ -45,12 +48,12 @@ public class SdnrTest {
* Construct an SDNR Request to be Serialized
*/
dmaapRequest = new PciRequestWrapper();
- dmaapRequest.setCorrelationId("664be3d2-6c12-4f4b-a3e7-c349acced200" + "-" + "1");
+ dmaapRequest.setCorrelationId(CORRELATION_ID + "-" + "1");
dmaapRequest.setRpcName("restart");
dmaapRequest.setType("request");
dmaapResponse = new PciResponseWrapper();
- dmaapResponse.setCorrelationId("664be3d2-6c12-4f4b-a3e7-c349acced200" + "-" + "1");
+ dmaapResponse.setCorrelationId(CORRELATION_ID + "-" + "1");
dmaapResponse.setRpcName("restart");
dmaapResponse.setType("response");
@@ -59,7 +62,7 @@ public class SdnrTest {
sdnrRequest.setAction("ModifyConfig");
PciCommonHeader commonHeader = new PciCommonHeader();
- commonHeader.setRequestId(UUID.fromString("664be3d2-6c12-4f4b-a3e7-c349acced200"));
+ commonHeader.setRequestId(UUID.fromString(CORRELATION_ID));
commonHeader.setSubRequestId("1");
sdnrRequest.setCommonHeader(commonHeader);
diff --git a/models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java b/models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java
index 888afe2ae..6e2494b72 100644
--- a/models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java
+++ b/models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java
@@ -68,6 +68,7 @@ public final class SoManager {
private String user;
private String password;
+ @FunctionalInterface
public interface SoCallback {
public void onSoResponseWrapper(SoResponseWrapper wrapper);
}
diff --git a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoDummyServer.java b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoDummyServer.java
index e9c338356..d7e7a1166 100644
--- a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoDummyServer.java
+++ b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoDummyServer.java
@@ -36,6 +36,7 @@ import javax.ws.rs.core.Response;
@Path("/SO")
public class SoDummyServer {
+ private static final String ONGOING = "ONGOING";
private static int postMessagesReceived = 0;
private static int putMessagesReceived = 0;
private static int statMessagesReceived = 0;
@@ -113,9 +114,9 @@ public class SoDummyServer {
SoResponse response = ongoingRequestMap.get(nsInstanceId);
- int iterationsLeft = Integer.valueOf(response.getRequest().getRequestScope());
+ int iterationsLeft = Integer.parseInt(response.getRequest().getRequestScope());
if (--iterationsLeft > 0) {
- response.getRequest().setRequestScope(new Integer(iterationsLeft).toString());
+ response.getRequest().setRequestScope(Integer.toString(iterationsLeft));
String responseString = new Gson().toJson(response, SoResponse.class);
return Response.status(response.getHttpResponseCode()).entity(responseString).build();
}
@@ -158,12 +159,7 @@ public class SoDummyServer {
return Response.status(400).build();
}
- SoRequest request = null;
- try {
- request = new Gson().fromJson(jsonString, SoRequest.class);
- } catch (Exception e) {
- return Response.status(400).build();
- }
+ SoRequest request = new Gson().fromJson(jsonString, SoRequest.class);
if (request == null) {
return Response.status(400).build();
@@ -206,7 +202,7 @@ public class SoDummyServer {
if ("ReturnOnging202".equals(request.getRequestType())) {
ongoingRequestMap.put(request.getRequestId().toString(), response);
- response.getRequest().getRequestStatus().setRequestState("ONGOING");
+ response.getRequest().getRequestStatus().setRequestState(ONGOING);
response.setHttpResponseCode(202);
String responseString = new Gson().toJson(response, SoResponse.class);
return Response.status(response.getHttpResponseCode())
@@ -217,7 +213,7 @@ public class SoDummyServer {
if ("ReturnOnging200".equals(request.getRequestType())) {
ongoingRequestMap.put(request.getRequestId().toString(), response);
- response.getRequest().getRequestStatus().setRequestState("ONGOING");
+ response.getRequest().getRequestStatus().setRequestState(ONGOING);
response.setHttpResponseCode(200);
String responseString = new Gson().toJson(response, SoResponse.class);
return Response.status(response.getHttpResponseCode())
@@ -228,7 +224,7 @@ public class SoDummyServer {
if ("ReturnBadAfterWait".equals(request.getRequestType())) {
ongoingRequestMap.put(request.getRequestId().toString(), response);
- response.getRequest().getRequestStatus().setRequestState("ONGOING");
+ response.getRequest().getRequestStatus().setRequestState(ONGOING);
response.setHttpResponseCode(200);
String responseString = new Gson().toJson(response, SoResponse.class);
return Response.status(response.getHttpResponseCode())
diff --git a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java
index 03ac06dd5..aa3562ae5 100644
--- a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java
+++ b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java
@@ -28,13 +28,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URI;
import java.util.UUID;
import java.util.concurrent.Future;
-import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
@@ -49,6 +47,19 @@ import org.junit.Test;
import org.onap.policy.so.SoManager.SoCallback;
public class SoManagerTest implements SoCallback {
+ private static final String LOCALHOST_99999999 = "http:/localhost:99999999";
+ private static final String CITIZEN = "citizen";
+ private static final String RETURN_ONGING202 = "ReturnOnging202";
+ private static final String RETURN_ONGING200 = "ReturnOnging200";
+ private static final String RETURN_FAILED = "ReturnFailed";
+ private static final String RETURN_COMPLETED = "ReturnCompleted";
+ private static final String RETURN_BAD_JSON = "ReturnBadJson";
+ private static final String RETURN_BAD_AFTER_WAIT = "ReturnBadAfterWait";
+ private static final String ONGOING = "ONGOING";
+ private static final String FAILED = "FAILED";
+ private static final String COMPLETE = "COMPLETE";
+ private static final String DATE1 = "2018-03-23 16:31";
+ private static final String SERVICE_INSTANTIATION_V7 = "/serviceInstantiation/v7";
private static final String BASE_URI = "http://localhost:46553/TestSOManager";
private static final String BASE_SO_URI = BASE_URI + "/SO";
private static HttpServer server;
@@ -68,99 +79,100 @@ public class SoManagerTest implements SoCallback {
}
@AfterClass
- public static void tearDown() throws Exception {
+ public static void tearDown() {
server.shutdown();
}
@Test
- public void testGrizzlyServer() throws ClientProtocolException, IOException {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- HttpGet httpGet = new HttpGet("http://localhost:46553/TestSOManager/SO/Stats");
- CloseableHttpResponse response = httpclient.execute(httpGet);
-
- String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
- assertTrue(returnBody.matches("^\\{\"GET\": [0-9]*,\"STAT\": [0-9]*,\"POST\": [0-9]*,\"PUT\": [0-9]*,"
- + "\"DELETE\": [0-9]*\\}$"));
+ public void testGrizzlyServer() throws IOException {
+ try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
+ HttpGet httpGet = new HttpGet("http://localhost:46553/TestSOManager/SO/Stats");
+ CloseableHttpResponse response = httpclient.execute(httpGet);
+
+ String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
+ assertTrue(returnBody.matches("^\\{\"GET\": [0-9]*,\"STAT\": [0-9]*,\"POST\": [0-9]*,\"PUT\": [0-9]*,"
+ + "\"DELETE\": [0-9]*\\}$"));
+ }
}
@Test
- public void testServiceInstantiation() throws IOException {
+ public void testServiceInstantiation() {
SoManager manager = new SoManager(null, null, null);
assertNotNull(manager);
manager.setRestGetTimeout(100);
- SoResponse response = manager.createModuleInstance("http:/localhost:99999999", BASE_SO_URI, "sean",
- "citizen", null);
+ SoResponse response = manager.createModuleInstance(LOCALHOST_99999999, BASE_SO_URI, "sean",
+ CITIZEN, null);
assertNull(response);
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", null);
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, null);
assertNull(response);
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", new SoRequest());
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, new SoRequest());
assertNull(response);
SoRequest request = new SoRequest();
request.setRequestId(UUID.randomUUID());
request.setRequestScope("Test");
- request.setRequestType("ReturnBadJson");
- request.setStartTime("2018-03-23 16:31");
+ request.setRequestType(RETURN_BAD_JSON);
+ request.setStartTime(DATE1);
request.setRequestStatus(new SoRequestStatus());
- request.getRequestStatus().setRequestState("ONGOING");
+ request.getRequestStatus().setRequestState(ONGOING);
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", request);
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, request);
assertNull(response);
- request.setRequestType("ReturnCompleted");
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", request);
+ request.setRequestType(RETURN_COMPLETED);
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, request);
assertNotNull(response);
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
- request.setRequestType("ReturnFailed");
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", request);
+ request.setRequestType(RETURN_FAILED);
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, request);
assertNotNull(response);
- assertEquals("FAILED", response.getRequest().getRequestStatus().getRequestState());
+ assertEquals(FAILED, response.getRequest().getRequestStatus().getRequestState());
// Use scope to set the number of iterations we'll wait for
- request.setRequestType("ReturnOnging200");
- request.setRequestScope(new Integer(10).toString());
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", request);
+ request.setRequestType(RETURN_ONGING200);
+ request.setRequestScope("10");
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, request);
assertNotNull(response);
assertNotNull(response.getRequest());
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
- request.setRequestType("ReturnOnging202");
- request.setRequestScope(new Integer(20).toString());
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", request);
+ request.setRequestType(RETURN_ONGING202);
+ request.setRequestScope("20");
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, request);
assertNotNull(response);
assertNotNull(response.getRequest());
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
// Test timeout after 20 attempts for a response
- request.setRequestType("ReturnOnging202");
- request.setRequestScope(new Integer(21).toString());
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", request);
+ request.setRequestType(RETURN_ONGING202);
+ request.setRequestScope("21");
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, request);
assertNull(response);
// Test bad response after 3 attempts for a response
- request.setRequestType("ReturnBadAfterWait");
- request.setRequestScope(new Integer(3).toString());
- response = manager.createModuleInstance(BASE_SO_URI + "/serviceInstantiation/v7", BASE_SO_URI, "sean",
- "citizen", request);
+ request.setRequestType(RETURN_BAD_AFTER_WAIT);
+ request.setRequestScope("3");
+ response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean",
+ CITIZEN, request);
assertNull(response);
}
@Test
- public void testVfModuleCreation() throws IOException {
- SoManager manager = new SoManager("http:/localhost:99999999", "sean", "citizen");
+ public void testVfModuleCreation() throws Exception {
+ SoManager manager = new SoManager(LOCALHOST_99999999, "sean", CITIZEN);
assertNotNull(manager);
manager.setRestGetTimeout(100);
@@ -168,117 +180,81 @@ public class SoManagerTest implements SoCallback {
soRequest.setOperationType(SoOperationType.SCALE_OUT);
Future<SoResponse> asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this,
UUID.randomUUID().toString(), UUID.randomUUID().toString(), soRequest);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ SoResponse response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
- manager = new SoManager(BASE_SO_URI, "sean", "citizen");
+ manager = new SoManager(BASE_SO_URI, "sean", CITIZEN);
manager.setRestGetTimeout(100);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), soRequest);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
SoRequest request = new SoRequest();
request.setRequestId(UUID.randomUUID());
request.setRequestScope("Test");
- request.setRequestType("ReturnBadJson");
- request.setStartTime("2018-03-23 16:31");
+ request.setRequestType(RETURN_BAD_JSON);
+ request.setStartTime(DATE1);
request.setRequestStatus(new SoRequestStatus());
- request.getRequestStatus().setRequestState("ONGOING");
+ request.getRequestStatus().setRequestState(ONGOING);
request.setOperationType(SoOperationType.SCALE_OUT);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
- request.setRequestType("ReturnCompleted");
+ request.setRequestType(RETURN_COMPLETED);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
- request.setRequestType("ReturnFailed");
+ request.setRequestType(RETURN_FAILED);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals("FAILED", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(FAILED, response.getRequest().getRequestStatus().getRequestState());
// Use scope to set the number of iterations we'll wait for
- request.setRequestType("ReturnOnging200");
- request.setRequestScope(new Integer(10).toString());
+ request.setRequestType(RETURN_ONGING200);
+ request.setRequestScope("10");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertNotNull(response.getRequest());
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertNotNull(response.getRequest());
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
- request.setRequestType("ReturnOnging202");
- request.setRequestScope(new Integer(20).toString());
+ request.setRequestType(RETURN_ONGING202);
+ request.setRequestScope("20");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertNotNull(response.getRequest());
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertNotNull(response.getRequest());
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
// Test timeout after 20 attempts for a response
- request.setRequestType("ReturnOnging202");
- request.setRequestScope(new Integer(21).toString());
+ request.setRequestType(RETURN_ONGING202);
+ request.setRequestScope("21");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
// Test bad response after 3 attempts for a response
- request.setRequestType("ReturnBadAfterWait");
- request.setRequestScope(new Integer(3).toString());
+ request.setRequestType(RETURN_BAD_AFTER_WAIT);
+ request.setRequestScope("3");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
}
@Test
- public void testVfModuleDeletion() {
- SoManager manager = new SoManager("http:/localhost:99999999", "sean", "citizen");
+ public void testVfModuleDeletion() throws Exception {
+ SoManager manager = new SoManager(LOCALHOST_99999999, "sean", CITIZEN);
assertNotNull(manager);
manager.setRestGetTimeout(100);
@@ -286,113 +262,77 @@ public class SoManagerTest implements SoCallback {
soRequest.setOperationType(SoOperationType.DELETE_VF_MODULE);
Future<SoResponse> asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this,
UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), soRequest);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ SoResponse response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
- manager = new SoManager(BASE_SO_URI, "sean", "citizen");
+ manager = new SoManager(BASE_SO_URI, "sean", CITIZEN);
manager.setRestGetTimeout(100);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), soRequest);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
SoRequest request = new SoRequest();
request.setRequestId(UUID.randomUUID());
request.setRequestScope("Test");
- request.setRequestType("ReturnBadJson");
- request.setStartTime("2018-03-23 16:31");
+ request.setRequestType(RETURN_BAD_JSON);
+ request.setStartTime(DATE1);
request.setRequestStatus(new SoRequestStatus());
- request.getRequestStatus().setRequestState("ONGOING");
+ request.getRequestStatus().setRequestState(ONGOING);
request.setOperationType(SoOperationType.DELETE_VF_MODULE);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
- request.setRequestType("ReturnCompleted");
+ request.setRequestType(RETURN_COMPLETED);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
- request.setRequestType("ReturnFailed");
+ request.setRequestType(RETURN_FAILED);
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals("FAILED", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(FAILED, response.getRequest().getRequestStatus().getRequestState());
// Use scope to set the number of iterations we'll wait for
- request.setRequestType("ReturnOnging200");
- request.setRequestScope(new Integer(10).toString());
+ request.setRequestType(RETURN_ONGING200);
+ request.setRequestScope("10");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertNotNull(response.getRequest());
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertNotNull(response.getRequest());
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
- request.setRequestType("ReturnOnging202");
- request.setRequestScope(new Integer(20).toString());
+ request.setRequestType(RETURN_ONGING202);
+ request.setRequestScope("20");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertNotNull(response.getRequest());
- assertEquals("COMPLETE", response.getRequest().getRequestStatus().getRequestState());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertNotNull(response.getRequest());
+ assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState());
// Test timeout after 20 attempts for a response
- request.setRequestType("ReturnOnging202");
- request.setRequestScope(new Integer(21).toString());
+ request.setRequestType(RETURN_ONGING202);
+ request.setRequestScope("21");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
// Test bad response after 3 attempts for a response
- request.setRequestType("ReturnBadAfterWait");
- request.setRequestScope(new Integer(3).toString());
+ request.setRequestType(RETURN_BAD_AFTER_WAIT);
+ request.setRequestScope("3");
asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(),
UUID.randomUUID().toString(), UUID.randomUUID().toString(), request);
- try {
- SoResponse response = asyncRestCallFuture.get();
- assertEquals(999, response.getHttpResponseCode());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ response = asyncRestCallFuture.get();
+ assertEquals(999, response.getHttpResponseCode());
}
@Override
diff --git a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoRequestInfoTest.java b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoRequestInfoTest.java
index 2302696ee..dd7db84f3 100644
--- a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoRequestInfoTest.java
+++ b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoRequestInfoTest.java
@@ -3,7 +3,6 @@
* so
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -23,7 +22,8 @@
package org.onap.policy.so;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
import org.junit.Test;
@@ -33,16 +33,16 @@ public class SoRequestInfoTest {
public void testConstructor() {
SoRequestInfo obj = new SoRequestInfo();
- assertTrue(obj.getBillingAccountNumber() == null);
- assertTrue(obj.getCallbackUrl() == null);
- assertTrue(obj.getCorrelator() == null);
- assertTrue(obj.getInstanceName() == null);
- assertTrue(obj.getOrderNumber() == null);
- assertTrue(obj.getOrderVersion() == null);
- assertTrue(obj.getProductFamilyId() == null);
- assertTrue(obj.getRequestorId() == null);
- assertTrue(obj.getSource() == null);
- assertTrue(obj.isSuppressRollback() == false);
+ assertNull(obj.getBillingAccountNumber());
+ assertNull(obj.getCallbackUrl());
+ assertNull(obj.getCorrelator());
+ assertNull(obj.getInstanceName());
+ assertNull(obj.getOrderNumber());
+ assertNull(obj.getOrderVersion());
+ assertNull(obj.getProductFamilyId());
+ assertNull(obj.getRequestorId());
+ assertNull(obj.getSource());
+ assertFalse(obj.isSuppressRollback());
}
@Test
diff --git a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoResponseWrapperTest.java b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoResponseWrapperTest.java
index deedc79c5..fdc59965a 100644
--- a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoResponseWrapperTest.java
+++ b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoResponseWrapperTest.java
@@ -32,19 +32,21 @@ import org.junit.Test;
public class SoResponseWrapperTest {
+ private static final String REQ_ID = "reqID";
+
@Test
public void testConstructor() {
SoResponse response = new SoResponse();
- SoResponseWrapper obj = new SoResponseWrapper(response, "reqID");
+ SoResponseWrapper obj = new SoResponseWrapper(response, REQ_ID);
assertEquals(response, obj.getSoResponse());
- assertEquals("reqID", obj.getRequestId());
+ assertEquals(REQ_ID, obj.getRequestId());
}
@Test
public void testSetGet() {
SoResponse response = new SoResponse();
- SoResponseWrapper obj = new SoResponseWrapper(response, "reqID");
+ SoResponseWrapper obj = new SoResponseWrapper(response, REQ_ID);
SoResponse response2 = new SoResponse();
response2.setHttpResponseCode(2008);
diff --git a/models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java b/models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java
index 850f37552..406e35d33 100644
--- a/models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java
+++ b/models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java
@@ -47,6 +47,7 @@ public final class VfcManager implements Runnable {
// The REST manager used for processing REST calls for this VFC manager
private RestManager restManager;
+ @FunctionalInterface
public interface VfcCallback {
void onResponse(VfcResponse responseError);
}
@@ -155,9 +156,11 @@ public final class VfcManager implements Runnable {
}
Thread.sleep(20000);
}
- if ((attemptsLeft <= 0) && (responseGet != null) && (responseGet.getResponseDescriptor() != null)
- && (responseGet.getResponseDescriptor().getStatus() != null)
- && (!responseGet.getResponseDescriptor().getStatus().isEmpty())) {
+ boolean isTimeout = (attemptsLeft <= 0) && (responseGet != null)
+ && (responseGet.getResponseDescriptor() != null);
+ isTimeout = isTimeout && (responseGet.getResponseDescriptor().getStatus() != null)
+ && (!responseGet.getResponseDescriptor().getStatus().isEmpty());
+ if (isTimeout) {
logger.debug("VFC timeout. Status: ({})", responseGet.getResponseDescriptor().getStatus());
this.callback.onResponse(responseGet);
}
diff --git a/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/DemoTest.java b/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/DemoTest.java
index 4d060a713..1c530c797 100644
--- a/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/DemoTest.java
+++ b/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/DemoTest.java
@@ -21,11 +21,13 @@
package org.onap.policy.vfc;
import java.util.LinkedList;
-
import org.junit.Test;
import org.onap.policy.vfc.util.Serialization;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DemoTest {
+ private static final Logger logger = LoggerFactory.getLogger(DemoTest.class);
@Test
public void test() {
@@ -44,13 +46,13 @@ public class DemoTest {
request.getHealRequest().getAdditionalParams().getActionInfo().setVmname("xgw-smp11");
String body = Serialization.gsonPretty.toJson(request);
- System.out.println(body);
+ logger.info("{}", body);
VfcResponse response = new VfcResponse();
response.setJobId("1");
body = Serialization.gsonPretty.toJson(response);
- System.out.println(body);
+ logger.info("{}", body);
response.setResponseDescriptor(new VfcResponseDescriptor());
response.getResponseDescriptor().setProgress("40");
@@ -59,7 +61,7 @@ public class DemoTest {
response.getResponseDescriptor().setErrorCode(null);
response.getResponseDescriptor().setResponseId("42");
body = Serialization.gsonPretty.toJson(response);
- System.out.println(body);
+ logger.info("{}", body);
VfcResponseDescriptor responseDescriptor = new VfcResponseDescriptor();
responseDescriptor.setProgress("20");
@@ -72,11 +74,11 @@ public class DemoTest {
response.getResponseDescriptor().getResponseHistoryList().add(responseDescriptor);
body = Serialization.gsonPretty.toJson(response);
- System.out.println(body);
+ logger.info("{}", body);
response = Serialization.gsonPretty.fromJson(body, VfcResponse.class);
body = Serialization.gsonPretty.toJson(response);
- System.out.println(body);
+ logger.info("{}", body);
}
}
diff --git a/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java b/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java
index 15534dbbb..7874d2514 100644
--- a/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java
+++ b/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java
@@ -22,8 +22,7 @@
package org.onap.policy.vfc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.endsWith;
@@ -35,7 +34,6 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.rest.RestManager;
@@ -45,6 +43,10 @@ import org.onap.policy.vfc.util.Serialization;
public class VfcManagerTest implements VfcCallback {
+ private static final String SOME_URL = "http://somewhere.over.the.rainbow";
+
+ private static final String DOROTHY = "Dorothy";
+
private RestManager mockedRestManager;
private Pair<Integer, String> httpResponsePutOk;
@@ -89,7 +91,7 @@ public class VfcManagerTest implements VfcCallback {
final UUID requestId = UUID.randomUUID();
request = new VfcRequest();
request.setHealRequest(healRequest);
- request.setNsInstanceId("Dorothy");
+ request.setNsInstanceId(DOROTHY);
request.setRequestId(requestId);
List<VfcResponseDescriptor> responseHistoryList = new ArrayList<>();;
@@ -110,49 +112,31 @@ public class VfcManagerTest implements VfcCallback {
@Test
public void testVfcInitiation() {
- try {
- new VfcManager(null, null, null, null, null);
- fail("test should throw an exception here");
- }
- catch (IllegalArgumentException e) {
- assertEquals("the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null",
- e.getMessage());
- }
-
- try {
- new VfcManager(this, null, null, null, null);
- fail("test should throw an exception here");
- }
- catch (IllegalArgumentException e) {
- assertEquals("the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null",
- e.getMessage());
- }
-
- try {
- new VfcManager(this, request, null, null, null);
- fail("test should throw an exception here");
- }
- catch (IllegalArgumentException e) {
- assertEquals("the \"url\" parameter on the VfcManager constructor may not be null",
- e.getMessage());
- }
-
- new VfcManager(this, request, "http://somewhere.over.the.rainbow", null, null);
-
- new VfcManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Toto");
+ assertThatIllegalArgumentException().isThrownBy(() -> new VfcManager(null, null, null, null, null)).withMessage(
+ "the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null");
+
+ assertThatIllegalArgumentException().isThrownBy(() -> new VfcManager(this, null, null, null, null)).withMessage(
+ "the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null");
+
+ assertThatIllegalArgumentException().isThrownBy(() -> new VfcManager(this, request, null, null, null))
+ .withMessage("the \"url\" parameter on the VfcManager constructor may not be null");
+
+ new VfcManager(this, request, SOME_URL, null, null);
+
+ new VfcManager(this, request, SOME_URL, DOROTHY, "Toto");
}
@Test
public void testVfcExecutionException() throws InterruptedException {
- VfcManager manager = new VfcManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Exception");
+ VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Exception");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
when(mockedRestManager.post(
- startsWith("http://somewhere.over.the.rainbow"),
- eq("Dorothy"),
+ startsWith(SOME_URL),
+ eq(DOROTHY),
eq("Exception"),
anyMap(),
anyString(),
@@ -164,14 +148,14 @@ public class VfcManagerTest implements VfcCallback {
@Test
public void testVfcExecutionNull() throws InterruptedException {
- VfcManager manager = new VfcManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Null");
+ VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Null");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"),
- eq("Dorothy"), eq("Null"), anyMap(), anyString(), anyString()))
+ when(mockedRestManager.post(startsWith(SOME_URL),
+ eq(DOROTHY), eq("Null"), anyMap(), anyString(), anyString()))
.thenReturn(null);
managerThread.join();
@@ -179,14 +163,14 @@ public class VfcManagerTest implements VfcCallback {
@Test
public void testVfcExecutionError0() throws InterruptedException {
- VfcManager manager = new VfcManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Error0");
+ VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Error0");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"),
- eq("Dorothy"), eq("Error0"), anyMap(), anyString(), anyString()))
+ when(mockedRestManager.post(startsWith(SOME_URL),
+ eq(DOROTHY), eq("Error0"), anyMap(), anyString(), anyString()))
.thenReturn(httpResponseErr);
managerThread.join();
@@ -194,14 +178,14 @@ public class VfcManagerTest implements VfcCallback {
@Test
public void testVfcExecutionBadResponse() throws InterruptedException {
- VfcManager manager = new VfcManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "BadResponse");
+ VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "BadResponse");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"),
- eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString()))
+ when(mockedRestManager.post(startsWith(SOME_URL),
+ eq(DOROTHY), eq("OK"), anyMap(), anyString(), anyString()))
.thenReturn(httpResponseBadResponse);
managerThread.join();
@@ -209,17 +193,17 @@ public class VfcManagerTest implements VfcCallback {
@Test
public void testVfcExecutionOk() throws InterruptedException {
- VfcManager manager = new VfcManager(this, request, "http://somewhere.over.the.rainbow", "Dorothy", "Ok");
+ VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Ok");
manager.setRestManager(mockedRestManager);
Thread managerThread = new Thread(manager);
managerThread.start();
- when(mockedRestManager.post(startsWith("http://somewhere.over.the.rainbow"),
- eq("Dorothy"), eq("OK"), anyMap(), anyString(), anyString()))
+ when(mockedRestManager.post(startsWith(SOME_URL),
+ eq(DOROTHY), eq("OK"), anyMap(), anyString(), anyString()))
.thenReturn(httpResponsePutOk);
- when(mockedRestManager.get(endsWith("1234"), eq("Dorothy"), eq("OK"), anyMap()))
+ when(mockedRestManager.get(endsWith("1234"), eq(DOROTHY), eq("OK"), anyMap()))
.thenReturn(httpResponseGetOk);
managerThread.join();
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java
index 91b5266cc..c1543d05b 100644
--- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java
+++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -31,7 +31,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
+import org.apache.commons.lang3.StringUtils;
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.ClassBasedEdgeFactory;
import org.jgrapht.graph.DefaultEdge;
@@ -52,11 +52,11 @@ public class ControlLoopCompiler implements Serializable {
private static final String OPERATION_POLICY = "Operation Policy ";
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(ControlLoopCompiler.class.getName());
-
+
/**
* Compiles the policy from an object.
*/
- public static ControlLoopPolicy compile(ControlLoopPolicy policy,
+ public static ControlLoopPolicy compile(ControlLoopPolicy policy,
ControlLoopCompilerCallback callback) throws CompilerException {
//
// Ensure the control loop is sane
@@ -66,19 +66,19 @@ public class ControlLoopCompiler implements Serializable {
// Validate the policies
//
validatePolicies(policy, callback);
-
+
return policy;
}
-
+
/**
* Compiles the policy from an input stream.
- *
+ *
* @param yamlSpecification the yaml input stream
* @param callback method to callback during compilation
* @return Control Loop object
* @throws CompilerException throws any compile exception found
*/
- public static ControlLoopPolicy compile(InputStream yamlSpecification,
+ public static ControlLoopPolicy compile(InputStream yamlSpecification,
ControlLoopCompilerCallback callback) throws CompilerException {
Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
Object obj = yaml.load(yamlSpecification);
@@ -90,39 +90,38 @@ public class ControlLoopCompiler implements Serializable {
}
return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback);
}
-
- private static void validateControlLoop(ControlLoop controlLoop,
+
+ private static void validateControlLoop(ControlLoop controlLoop,
ControlLoopCompilerCallback callback) throws CompilerException {
if (controlLoop == null && callback != null) {
callback.onError("controlLoop cannot be null");
}
if (controlLoop != null) {
- if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1)
- && callback != null) {
+ if (StringUtils.isEmpty(controlLoop.getControlLoopName()) && callback != null) {
callback.onError("Missing controlLoopName");
}
if ((!controlLoop.getVersion().contentEquals(ControlLoop.getCompilerVersion())) && callback != null) {
callback.onError("Unsupported version for this compiler");
}
- if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) {
+ if (StringUtils.isEmpty(controlLoop.getTrigger_policy())) {
throw new CompilerException("trigger_policy is not valid");
}
}
}
- private static void validatePolicies(ControlLoopPolicy policy,
+ private static void validatePolicies(ControlLoopPolicy policy,
ControlLoopCompilerCallback callback) throws CompilerException {
if (policy == null) {
throw new CompilerException("policy cannot be null");
}
if (policy.getPolicies() == null) {
- callback.onWarning("controlLoop is an open loop.");
+ callback.onWarning("controlLoop is an open loop.");
} else {
//
// For this version we can use a directed multigraph, in the future we may not be able to
//
- DirectedGraph<NodeWrapper, LabeledEdge> graph =
- new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper,
+ DirectedGraph<NodeWrapper, LabeledEdge> graph =
+ new DirectedMultigraph<>(new ClassBasedEdgeFactory<NodeWrapper,
LabeledEdge>(LabeledEdge.class));
//
// Check to see if the trigger Event is for OpenLoop, we do so by
@@ -153,7 +152,7 @@ public class ControlLoopCompiler implements Serializable {
FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE);
FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT);
FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES);
- FinalResultNodeWrapper finalFailureException =
+ FinalResultNodeWrapper finalFailureException =
new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION);
FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD);
graph.addVertex(finalSuccess);
@@ -177,30 +176,30 @@ public class ControlLoopCompiler implements Serializable {
if (node == null) {
continue;
}
- addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess,
+ addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getSuccess(), finalSuccess,
PolicyResult.SUCCESS, node);
- addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure,
+ addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure(), finalFailure,
PolicyResult.FAILURE, node);
- addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout,
+ addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_timeout(), finalFailureTimeout,
PolicyResult.FAILURE_TIMEOUT, node);
- addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries,
+ addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_retries(), finalFailureRetries,
PolicyResult.FAILURE_RETRIES, node);
- addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException,
+ addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_exception(), finalFailureException,
PolicyResult.FAILURE_EXCEPTION, node);
- addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard,
+ addEdge(graph, mapNodes, operPolicy.getId(), operPolicy.getFailure_guard(), finalFailureGuard,
PolicyResult.FAILURE_GUARD, node);
}
validateNodesAndEdges(graph, callback);
- }
+ }
}
-
- private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult,
+
+ private static void validateOpenLoopPolicy(ControlLoopPolicy policy, FinalResult triggerResult,
ControlLoopCompilerCallback callback) throws CompilerException {
//
// Ensure they didn't use some other FinalResult code
//
if (triggerResult != FinalResult.FINAL_OPENLOOP) {
- throw new CompilerException("Unexpected Final Result for trigger_policy, should only be "
+ throw new CompilerException("Unexpected Final Result for trigger_policy, should only be "
+ FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
}
//
@@ -210,8 +209,8 @@ public class ControlLoopCompiler implements Serializable {
callback.onWarning("Open Loop policy contains policies. The policies will never be invoked.");
}
}
-
- private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy,
+
+ private static void validatePoliciesContainTriggerPolicyAndCombinedTimeoutIsOk(ControlLoopPolicy policy,
ControlLoopCompilerCallback callback) throws CompilerException {
int sum = 0;
boolean triggerPolicyFound = false;
@@ -224,15 +223,15 @@ public class ControlLoopCompiler implements Serializable {
if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) {
callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts.");
}
-
+
if (!triggerPolicyFound) {
- throw new CompilerException("Unexpected value for trigger_policy, should only be "
+ throw new CompilerException("Unexpected value for trigger_policy, should only be "
+ FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
}
}
-
- private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy,
- DirectedGraph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode,
+
+ private static Map<Policy, PolicyNodeWrapper> addPoliciesAsNodes(ControlLoopPolicy policy,
+ DirectedGraph<NodeWrapper, LabeledEdge> graph, TriggerNodeWrapper triggerNode,
ControlLoopCompilerCallback callback) {
Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<>();
for (Policy operPolicy : policy.getPolicies()) {
@@ -264,27 +263,27 @@ public class ControlLoopCompiler implements Serializable {
}
return mapNodes;
}
-
+
private static void addEdge(DirectedGraph<NodeWrapper, LabeledEdge> graph, Map<Policy, PolicyNodeWrapper> mapNodes,
- String policyId, String connectedPolicy,
- FinalResultNodeWrapper finalResultNodeWrapper,
+ String policyId, String connectedPolicy,
+ FinalResultNodeWrapper finalResultNodeWrapper,
PolicyResult policyResult, NodeWrapper node) throws CompilerException {
FinalResult finalResult = FinalResult.toResult(finalResultNodeWrapper.getId());
if (FinalResult.isResult(connectedPolicy, finalResult)) {
- graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper,
+ graph.addEdge(node, finalResultNodeWrapper, new LabeledEdge(node, finalResultNodeWrapper,
new FinalResultEdgeWrapper(finalResult)));
} else {
PolicyNodeWrapper toNode = findPolicyNode(mapNodes, connectedPolicy);
if (toNode == null) {
- throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy "
+ throw new CompilerException(OPERATION_POLICY + policyId + " is connected to unknown policy "
+ connectedPolicy);
} else {
graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(policyResult)));
}
}
}
-
- private static void validateNodesAndEdges(DirectedGraph<NodeWrapper, LabeledEdge> graph,
+
+ private static void validateNodesAndEdges(DirectedGraph<NodeWrapper, LabeledEdge> graph,
ControlLoopCompilerCallback callback) throws CompilerException {
for (NodeWrapper node : graph.vertexSet()) {
if (node instanceof TriggerNodeWrapper) {
@@ -299,8 +298,8 @@ public class ControlLoopCompiler implements Serializable {
}
}
}
-
- private static void validateTriggerNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
+
+ private static void validateTriggerNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
NodeWrapper node) throws CompilerException {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("Trigger Node {}", node);
@@ -318,8 +317,8 @@ public class ControlLoopCompiler implements Serializable {
throw new CompilerException("The event trigger should only go to ONE node");
}
}
-
- private static void validateFinalResultNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
+
+ private static void validateFinalResultNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
NodeWrapper node) throws CompilerException {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("FinalResult Node {}", node);
@@ -331,8 +330,8 @@ public class ControlLoopCompiler implements Serializable {
throw new CompilerException("FinalResult nodes should never have any out edges.");
}
}
-
- private static void validatePolicyNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
+
+ private static void validatePolicyNodeWrapper(DirectedGraph<NodeWrapper, LabeledEdge> graph,
NodeWrapper node, ControlLoopCompilerCallback callback) throws CompilerException {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("Policy Node {}", node);
@@ -344,13 +343,13 @@ public class ControlLoopCompiler implements Serializable {
throw new CompilerException("Policy node should ALWAYS have 6 out degrees.");
}
//
- // All Policy Nodes should have at least 1 in degrees
- //
+ // All Policy Nodes should have at least 1 in degrees
+ //
if (graph.inDegreeOf(node) == 0 && callback != null) {
callback.onWarning("Policy " + node.getId() + " is not reachable.");
}
}
-
+
private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = isPolicyIdOk(operPolicy, callback);
if (! isActorOk(operPolicy, callback)) {
@@ -367,7 +366,7 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isPolicyIdOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
if (operPolicy.getId() == null || operPolicy.getId().length() < 1) {
@@ -394,7 +393,7 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isActorOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
if (operPolicy.getActor() == null) {
@@ -416,7 +415,7 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isRecipeOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
if (operPolicy.getRecipe() == null) {
@@ -427,7 +426,7 @@ public class ControlLoopCompiler implements Serializable {
}
//
// NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these)
- //
+ //
ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>()
.put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"))
.put("SDNC", ImmutableList.of("Reroute"))
@@ -436,8 +435,8 @@ public class ControlLoopCompiler implements Serializable {
.put("VFC", ImmutableList.of("Restart"))
.build();
//
- if (operPolicy.getRecipe() != null
- && (!recipes.getOrDefault(operPolicy.getActor(),
+ if (operPolicy.getRecipe() != null
+ && (!recipes.getOrDefault(operPolicy.getActor(),
Collections.emptyList()).contains(operPolicy.getRecipe()))) {
if (callback != null) {
callback.onError("Policy recipe is invalid");
@@ -446,7 +445,7 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isTargetOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
if (operPolicy.getTarget() == null) {
@@ -455,9 +454,9 @@ public class ControlLoopCompiler implements Serializable {
}
isOk = false;
}
- if (operPolicy.getTarget() != null
- && operPolicy.getTarget().getType() != TargetType.VM
- && operPolicy.getTarget().getType() != TargetType.VFC
+ if (operPolicy.getTarget() != null
+ && operPolicy.getTarget().getType() != TargetType.VM
+ && operPolicy.getTarget().getType() != TargetType.VFC
&& operPolicy.getTarget().getType() != TargetType.PNF) {
if (callback != null) {
callback.onError("Policy target is invalid");
@@ -466,7 +465,7 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean arePolicyResultsOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
//
// Check that policy results are connected to either default final * or another policy
@@ -489,10 +488,10 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isSuccessPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
- if (FinalResult.toResult(operPolicy.getSuccess()) != null
+ if (FinalResult.toResult(operPolicy.getSuccess()) != null
&& !operPolicy.getSuccess().equals(FinalResult.FINAL_SUCCESS.toString())) {
if (callback != null) {
callback.onError("Policy success is neither another policy nor FINAL_SUCCESS");
@@ -501,10 +500,10 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isFailurePolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
- if (FinalResult.toResult(operPolicy.getFailure()) != null
+ if (FinalResult.toResult(operPolicy.getFailure()) != null
&& !operPolicy.getFailure().equals(FinalResult.FINAL_FAILURE.toString())) {
if (callback != null) {
callback.onError("Policy failure is neither another policy nor FINAL_FAILURE");
@@ -513,10 +512,10 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isFailureRetriesPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
- if (FinalResult.toResult(operPolicy.getFailure_retries()) != null
+ if (FinalResult.toResult(operPolicy.getFailure_retries()) != null
&& !operPolicy.getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())) {
if (callback != null) {
callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES");
@@ -525,10 +524,10 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isFailureTimeoutPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
- if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null
+ if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null
&& !operPolicy.getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())) {
if (callback != null) {
callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT");
@@ -537,10 +536,10 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isFailureExceptionPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
- if (FinalResult.toResult(operPolicy.getFailure_exception()) != null
+ if (FinalResult.toResult(operPolicy.getFailure_exception()) != null
&& !operPolicy.getFailure_exception().equals(FinalResult.FINAL_FAILURE_EXCEPTION.toString())) {
if (callback != null) {
callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION");
@@ -549,10 +548,10 @@ public class ControlLoopCompiler implements Serializable {
}
return isOk;
}
-
+
private static boolean isFailureGuardPolicyResultOk(Policy operPolicy, ControlLoopCompilerCallback callback) {
boolean isOk = true;
- if (FinalResult.toResult(operPolicy.getFailure_guard()) != null
+ if (FinalResult.toResult(operPolicy.getFailure_guard()) != null
&& !operPolicy.getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())) {
if (callback != null) {
callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD");
@@ -570,16 +569,16 @@ public class ControlLoopCompiler implements Serializable {
}
return null;
}
-
+
@FunctionalInterface
private interface NodeWrapper extends Serializable {
public String getId();
}
-
+
private static class TriggerNodeWrapper implements NodeWrapper {
private static final long serialVersionUID = -187644087811478349L;
private String closedLoopControlName;
-
+
public TriggerNodeWrapper(String closedLoopControlName) {
this.closedLoopControlName = closedLoopControlName;
}
@@ -593,9 +592,9 @@ public class ControlLoopCompiler implements Serializable {
public String getId() {
return closedLoopControlName;
}
-
+
}
-
+
private static class FinalResultNodeWrapper implements NodeWrapper {
private static final long serialVersionUID = 8540008796302474613L;
private FinalResult result;
@@ -614,11 +613,11 @@ public class ControlLoopCompiler implements Serializable {
return result.toString();
}
}
-
+
private static class PolicyNodeWrapper implements NodeWrapper {
private static final long serialVersionUID = 8170162175653823082L;
private transient Policy policy;
-
+
public PolicyNodeWrapper(Policy operPolicy) {
this.policy = operPolicy;
}
@@ -633,17 +632,17 @@ public class ControlLoopCompiler implements Serializable {
return policy.getId();
}
}
-
+
@FunctionalInterface
private interface EdgeWrapper extends Serializable {
public String getId();
-
+
}
-
+
private static class TriggerEdgeWrapper implements EdgeWrapper {
private static final long serialVersionUID = 2678151552623278863L;
private String trigger;
-
+
public TriggerEdgeWrapper(String trigger) {
this.trigger = trigger;
}
@@ -657,9 +656,9 @@ public class ControlLoopCompiler implements Serializable {
public String toString() {
return "TriggerEdgeWrapper [trigger=" + trigger + "]";
}
-
+
}
-
+
private static class PolicyResultEdgeWrapper implements EdgeWrapper {
private static final long serialVersionUID = 6078569477021558310L;
private PolicyResult policyResult;
@@ -678,14 +677,14 @@ public class ControlLoopCompiler implements Serializable {
public String getId() {
return policyResult.toString();
}
-
-
+
+
}
-
+
private static class FinalResultEdgeWrapper implements EdgeWrapper {
private static final long serialVersionUID = -1486381946896779840L;
private FinalResult finalResult;
-
+
public FinalResultEdgeWrapper(FinalResult result) {
this.finalResult = result;
}
@@ -694,37 +693,37 @@ public class ControlLoopCompiler implements Serializable {
public String toString() {
return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]";
}
-
+
@Override
public String getId() {
return finalResult.toString();
}
}
-
-
+
+
private static class LabeledEdge extends DefaultEdge {
private static final long serialVersionUID = 579384429573385524L;
-
+
private NodeWrapper from;
private NodeWrapper to;
private EdgeWrapper edge;
-
+
public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) {
this.from = from;
this.to = to;
this.edge = edge;
}
-
+
@SuppressWarnings("unused")
public NodeWrapper from() {
return from;
}
-
+
@SuppressWarnings("unused")
public NodeWrapper to() {
return to;
}
-
+
@SuppressWarnings("unused")
public EdgeWrapper edge() {
return edge;
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java
index fc3d82326..69f62b28e 100644
--- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java
+++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -49,7 +49,7 @@ public class ControlLoop implements Serializable {
/**
* Constructor.
- *
+ *
* @param controlLoop copy object
*/
public ControlLoop(ControlLoop controlLoop) {
@@ -172,10 +172,12 @@ public class ControlLoop implements Serializable {
return false;
}
ControlLoop other = (ControlLoop) obj;
- return equalsMayBeNull(controlLoopName, other.controlLoopName) && equalsMayBeNull(resources, other.resources)
- && equalsMayBeNull(services, other.services) && equalsMayBeNull(timeout, other.timeout)
- && equalsMayBeNull(triggerPolicy, other.triggerPolicy) && equalsMayBeNull(version, other.version)
- && equalsMayBeNull(abatement, other.abatement);
+
+ boolean isEq = equalsMayBeNull(controlLoopName, other.controlLoopName)
+ && equalsMayBeNull(resources, other.resources) && equalsMayBeNull(services, other.services);
+ isEq = isEq && equalsMayBeNull(timeout, other.timeout) && equalsMayBeNull(triggerPolicy, other.triggerPolicy)
+ && equalsMayBeNull(version, other.version);
+ return (isEq && equalsMayBeNull(abatement, other.abatement));
}
private boolean equalsMayBeNull(final Object obj1, final Object obj2) {
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java
index af50eaa00..728733d76 100644
--- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java
+++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -45,19 +45,19 @@ public class Policy implements Serializable {
private String failureTimeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString();
private String failureException = FinalResult.FINAL_FAILURE_EXCEPTION.toString();
private String failureGuard = FinalResult.FINAL_FAILURE_GUARD.toString();
-
-
+
+
public Policy() {
//Does Nothing Empty Constructor
}
-
+
public Policy(String id) {
this.id = id;
}
-
+
/**
* Constructor.
- *
+ *
* @param name name
* @param actor actor
* @param recipe recipe
@@ -73,10 +73,10 @@ public class Policy implements Serializable {
this.payload = Collections.unmodifiableMap(payload);
}
}
-
+
/**
* Constructor.
- *
+ *
* @param name name
* @param actor actor
* @param recipe recipe
@@ -91,7 +91,7 @@ public class Policy implements Serializable {
this.retry = retries;
this.timeout = timeout;
}
-
+
/**
* Constructor.
*
@@ -103,10 +103,10 @@ public class Policy implements Serializable {
this.id = policyParam.getId();
this.description = policyParam.getDescription();
}
-
+
/**
* Constructor.
- *
+ *
* @param policy copy object
*/
public Policy(Policy policy) {
@@ -259,13 +259,14 @@ public class Policy implements Serializable {
}
public boolean isValid() {
- return id != null && name != null && actor != null && recipe != null && target != null;
+ boolean isValid = id != null && name != null && actor != null;
+ return isValid && recipe != null && target != null;
}
@Override
public String toString() {
return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe="
- + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams="
+ + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams="
+ operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout
+ ", success=" + success + ", failure=" + failure + ", failure_retries=" + failureRetries
+ ", failure_timeout=" + failureTimeout + ", failure_exception=" + failureException
@@ -293,7 +294,7 @@ public class Policy implements Serializable {
result = addHashCodeForField(result, timeout);
return result;
}
-
+
private int addHashCodeForField(int hashCode, Object field) {
final int prime = 31;
return prime * hashCode + ((field == null) ? 0 : field.hashCode());
@@ -311,23 +312,29 @@ public class Policy implements Serializable {
return false;
}
Policy other = (Policy) obj;
- return equalsMayBeNull(actor, other.actor)
+ boolean isEq = equalsMayBeNull(actor, other.actor)
&& equalsMayBeNull(description, other.description)
- && equalsMayBeNull(failure, other.failure)
+ && equalsMayBeNull(failure, other.failure);
+ isEq = isEq
&& equalsMayBeNull(failureException, other.failureException)
- && equalsMayBeNull(failureGuard, other.failureGuard)
+ && equalsMayBeNull(failureGuard, other.failureGuard);
+ isEq = isEq
&& equalsMayBeNull(failureRetries, other.failureRetries)
- && equalsMayBeNull(id, other.id)
+ && equalsMayBeNull(id, other.id);
+ isEq = isEq
&& equalsMayBeNull(name, other.name)
- && equalsMayBeNull(payload, other.payload)
+ && equalsMayBeNull(payload, other.payload);
+ isEq = isEq
&& equalsMayBeNull(recipe, other.recipe)
- && equalsMayBeNull(retry, other.retry)
+ && equalsMayBeNull(retry, other.retry);
+ isEq = isEq
&& equalsMayBeNull(success, other.success)
- && equalsMayBeNull(operationsAccumulateParams, other.operationsAccumulateParams)
+ && equalsMayBeNull(operationsAccumulateParams, other.operationsAccumulateParams);
+ return isEq
&& equalsMayBeNull(target, other.target)
&& equalsMayBeNull(timeout, other.timeout);
}
-
+
private boolean equalsMayBeNull(final Object obj1, final Object obj2) {
if ( obj1 == null ) {
return obj2 == null;
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java
index b8432ba60..bc99975f8 100644
--- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java
+++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java
@@ -37,6 +37,28 @@ public class Target implements Serializable {
private String modelVersion;
private String modelCustomizationId;
+ public Target() {
+ //Does Nothing Empty Constructor
+ }
+
+ public Target(TargetType type) {
+ this.type = type;
+ }
+
+ public Target(String resourceId) {
+ this.resourceId = resourceId;
+ }
+
+ public Target(TargetType type, String resourceId) {
+ this.type = type;
+ this.resourceId = resourceId;
+ }
+
+ public Target(Target target) {
+ this.type = target.type;
+ this.resourceId = target.resourceId;
+ }
+
public String getModelInvariantId() {
return modelInvariantId;
}
@@ -77,28 +99,6 @@ public class Target implements Serializable {
this.modelCustomizationId = modelCustomizationId;
} //techm
- public Target() {
- //Does Nothing Empty Constructor
- }
-
- public Target(TargetType type) {
- this.type = type;
- }
-
- public Target(String resourceId) {
- this.resourceId = resourceId;
- }
-
- public Target(TargetType type, String resourceId) {
- this.type = type;
- this.resourceId = resourceId;
- }
-
- public Target(Target target) {
- this.type = target.type;
- this.resourceId = target.resourceId;
- }
-
public String getResourceID() {
return resourceId;
}
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java
index b2d243c4e..7144fe363 100644
--- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java
+++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -22,22 +22,23 @@
package org.onap.policy.controlloop.policy.guard;
import java.util.LinkedList;
+import java.util.List;
public class ControlLoopGuard {
-
+
private Guard guard;
-
- private LinkedList<GuardPolicy> guards;
-
+
+ private List<GuardPolicy> guards;
+
public ControlLoopGuard() {
//DO Nothing Empty Constructor
}
-
+
public ControlLoopGuard(ControlLoopGuard clGuard) {
this.guard = new Guard();
this.guards = new LinkedList<>(clGuard.guards);
}
-
+
public Guard getGuard() {
return guard;
}
@@ -46,11 +47,11 @@ public class ControlLoopGuard {
this.guard = guard;
}
- public LinkedList<GuardPolicy> getGuards() {
+ public List<GuardPolicy> getGuards() {
return guards;
}
- public void setGuards(LinkedList<GuardPolicy> guards) {
+ public void setGuards(List<GuardPolicy> guards) {
this.guards = guards;
}
@@ -97,5 +98,5 @@ public class ControlLoopGuard {
return true;
}
-
+
}
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java
index 4278b81e5..55b96e14e 100644
--- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java
+++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -21,7 +21,6 @@
package org.onap.policy.controlloop.policy.guard;
-import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
@@ -31,24 +30,24 @@ public class GuardPolicy {
private String name;
private String description;
private MatchParameters matchParameters;
- private LinkedList<Constraint> limitConstraints;
-
+ private List<Constraint> limitConstraints;
+
public GuardPolicy() {
- //Do Nothing Empty Constructor.
+ //Do Nothing Empty Constructor.
}
-
+
public GuardPolicy(String id) {
this.id = id;
}
-
+
public GuardPolicy(String name, MatchParameters matchParameters) {
this.name = name;
this.matchParameters = matchParameters;
}
-
+
/**
* Constructor.
- *
+ *
* @param id id
* @param name name
* @param description description
@@ -59,36 +58,34 @@ public class GuardPolicy {
this.id = id;
this.description = description;
}
-
+
/**
* Constructor.
- *
+ *
* @param name name
* @param matchParameters match parameters
* @param limitConstraints limit constraints
*/
public GuardPolicy(String name, MatchParameters matchParameters, List<Constraint> limitConstraints) {
this(name, matchParameters);
- if (limitConstraints != null) {
- this.limitConstraints = (LinkedList<Constraint>) limitConstraints;
- }
+ this.limitConstraints = limitConstraints;
}
-
- public GuardPolicy(String name, String description, MatchParameters matchParameters,
+
+ public GuardPolicy(String name, String description, MatchParameters matchParameters,
List<Constraint> limitConstraints) {
this(name, matchParameters, limitConstraints);
this.description = description;
}
-
- public GuardPolicy(String id, String name, String description, MatchParameters matchParameters,
+
+ public GuardPolicy(String id, String name, String description, MatchParameters matchParameters,
List<Constraint> limitConstraints) {
this(name, description, matchParameters, limitConstraints);
this.id = id;
}
-
+
/**
* Constructor.
- *
+ *
* @param policy copy object
*/
public GuardPolicy(GuardPolicy policy) {
@@ -96,11 +93,9 @@ public class GuardPolicy {
this.name = policy.name;
this.description = policy.description;
this.matchParameters = new MatchParameters(policy.matchParameters);
- if (policy.limitConstraints != null) {
- this.limitConstraints = policy.limitConstraints;
- }
+ this.limitConstraints = policy.limitConstraints;
}
-
+
public String getId() {
return id;
}
@@ -133,21 +128,21 @@ public class GuardPolicy {
this.matchParameters = matchParameters;
}
- public LinkedList<Constraint> getLimit_constraints() {
+ public List<Constraint> getLimit_constraints() {
return limitConstraints;
}
- public void setLimit_constraints(LinkedList<Constraint> limitConstraints) {
+ public void setLimit_constraints(List<Constraint> limitConstraints) {
this.limitConstraints = limitConstraints;
}
public boolean isValid() {
- return (id == null || name == null) ? false : true;
+ return (id != null && name != null);
}
-
+
@Override
public String toString() {
- return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters="
+ return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters="
+ matchParameters + ", limitConstraints=" + limitConstraints + "]";
}
@@ -175,17 +170,18 @@ public class GuardPolicy {
return false;
}
GuardPolicy other = (GuardPolicy) obj;
- return equalsMayBeNull(description, other.description)
+ boolean isEq = equalsMayBeNull(description, other.description)
&& equalsMayBeNull(id, other.id)
- && equalsMayBeNull(name, other.name)
+ && equalsMayBeNull(name, other.name);
+ return isEq
&& equalsMayBeNull(limitConstraints, other.limitConstraints)
&& equalsMayBeNull(matchParameters, other.matchParameters);
}
-
+
private boolean equalsMayBeNull(final Object obj1, final Object obj2) {
if ( obj1 == null ) {
return obj2 == null;
}
return obj1.equals(obj2);
- }
+ }
}
diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java
index a84783bc0..70d23bcba 100644
--- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java
+++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -44,16 +44,16 @@ import org.yaml.snakeyaml.Yaml;
public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder {
private static final String NO_EXISTING_GUARD_POLICY_MATCHING_THE_ID = "No existing guard policy matching the id: ";
- private static final String THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL =
+ private static final String THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL =
"The id of target guard policy must not be null";
private static Logger logger = LoggerFactory.getLogger(ControlLoopGuardBuilderImpl.class.getName());
private ControlLoopGuard clGuard;
-
+
public ControlLoopGuardBuilderImpl(Guard guard) {
clGuard = new ControlLoopGuard();
clGuard.setGuard(guard);
}
-
+
@Override
public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException {
if (policies == null) {
@@ -112,26 +112,28 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder {
}
private boolean addLimitConstraints(String id, Constraint... constraints) throws BuilderException {
- boolean exist = false;
for (GuardPolicy policy: clGuard.getGuards()) {
//
// We could have only one guard policy matching the id
//
if (policy.getId().equals(id)) {
- exist = true;
- for (Constraint cons: constraints) {
- if (!cons.isValid()) {
- throw new BuilderException("Invalid guard constraint - some required fields are missing");
- }
- if (policy.getLimit_constraints() == null) {
- policy.setLimit_constraints(new LinkedList<>());
- }
- policy.getLimit_constraints().add(cons);
- }
- break;
+ addConstraints(policy, constraints);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void addConstraints(GuardPolicy policy, Constraint... constraints) throws BuilderException {
+ for (Constraint cons: constraints) {
+ if (!cons.isValid()) {
+ throw new BuilderException("Invalid guard constraint - some required fields are missing");
+ }
+ if (policy.getLimit_constraints() == null) {
+ policy.setLimit_constraints(new LinkedList<>());
}
+ policy.getLimit_constraints().add(cons);
}
- return exist;
}
@Override
@@ -149,33 +151,35 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder {
}
private boolean removeConstraints(String id, Constraint... constraints) throws BuilderException {
- boolean exist = false;
for (GuardPolicy policy: clGuard.getGuards()) {
//
// We could have only one guard policy matching the id
//
if (policy.getId().equals(id)) {
- exist = true;
- for (Constraint cons: constraints) {
- if (!cons.isValid()) {
- throw new BuilderException("Invalid guard constraint - some required fields are missing");
- }
- boolean removed = policy.getLimit_constraints().remove(cons);
- if (!removed) {
- throw new BuilderException("Unknown guard constraint: " + cons);
- }
- }
- break;
+ removeConstraints(policy, constraints);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void removeConstraints(GuardPolicy policy, Constraint... constraints) throws BuilderException {
+ for (Constraint cons: constraints) {
+ if (!cons.isValid()) {
+ throw new BuilderException("Invalid guard constraint - some required fields are missing");
+ }
+ boolean removed = policy.getLimit_constraints().remove(cons);
+ if (!removed) {
+ throw new BuilderException("Unknown guard constraint: " + cons);
}
}
- return exist;
}
@Override
public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException {
if (clGuard.getGuards() == null || clGuard.getGuards().isEmpty()) {
throw new BuilderException("No guard policies exist");
- }
+ }
if (id == null) {
throw new BuilderException(THE_ID_OF_TARGET_GUARD_POLICY_MUST_NOT_BE_NULL);
}
@@ -192,11 +196,11 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder {
return this;
}
-
+
private class BuilderCompilerCallback implements ControlLoopCompilerCallback {
private ResultsImpl results = new ResultsImpl();
-
+
@Override
public boolean onWarning(String message) {
results.addMessage(new MessageImpl(message, MessageLevel.WARNING));
@@ -209,13 +213,13 @@ public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder {
return false;
}
}
-
+
@Override
public ControlLoopGuard getControlLoopGuard() {
return new ControlLoopGuard(this.clGuard);
- }
-
-
+ }
+
+
@Override
public Results buildSpecification() {
//
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java
index ef3a68233..e3ab76b6b 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/CompilerExceptionTest.java
@@ -2,13 +2,14 @@
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -25,7 +26,7 @@ import org.onap.policy.common.utils.test.ExceptionsTester;
public class CompilerExceptionTest extends ExceptionsTester {
@Test
- public void test() throws Exception {
+ public void test() {
test(CompilerException.class);
}
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java
index 1028bde0f..6603dcb82 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml unit test
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -27,12 +27,9 @@ import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -41,10 +38,13 @@ import org.onap.policy.controlloop.policy.FinalResult;
public class ControlLoopCompilerTest {
+ private static final String POLICY_RECIPE_IS_INVALID = "Policy recipe is invalid";
+ private static final String RESTART_UNKNOWN_POLICY =
+ "Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy";
@Rule
public ExpectedException expectedException = ExpectedException.none();
- @Test
+ @Test
public void testTest() throws Exception {
List<String> expectedOnErrorMessages = new ArrayList<>();
expectedOnErrorMessages.add("Operational Policy has an bad ID");
@@ -53,9 +53,9 @@ public class ControlLoopCompilerTest {
expectedOnErrorMessages.add("Policy actor is null");
expectedOnErrorMessages.add("Policy actor is invalid");
expectedOnErrorMessages.add("Policy recipe is null");
- expectedOnErrorMessages.add("Policy recipe is invalid");
- expectedOnErrorMessages.add("Policy recipe is invalid");
- expectedOnErrorMessages.add("Policy recipe is invalid");
+ expectedOnErrorMessages.add(POLICY_RECIPE_IS_INVALID);
+ expectedOnErrorMessages.add(POLICY_RECIPE_IS_INVALID);
+ expectedOnErrorMessages.add(POLICY_RECIPE_IS_INVALID);
expectedOnErrorMessages.add("Policy target is null");
expectedOnErrorMessages.add("Policy target is invalid");
expectedOnErrorMessages.add("Policy success is neither another policy nor FINAL_SUCCESS");
@@ -67,9 +67,9 @@ public class ControlLoopCompilerTest {
expectedOnErrorMessages.add("Unsupported version for this compiler");
expectedOnErrorMessages.add("controlLoop overall timeout is less than the sum of operational policy timeouts.");
- TestControlLoopCompilerCallback testControlLoopCompilerCallback =
+ TestControlLoopCompilerCallback testControlLoopCompilerCallback =
new TestControlLoopCompilerCallback(expectedOnErrorMessages);
- ControlLoopPolicy controlLoopPolicy = this.test("src/test/resources/v1.0.0/test.yaml",
+ ControlLoopPolicy controlLoopPolicy = this.test("src/test/resources/v1.0.0/test.yaml",
testControlLoopCompilerCallback);
assertEquals(22, controlLoopPolicy.getPolicies().size());
assertTrue(testControlLoopCompilerCallback.areAllExpectedOnErrorsReceived());
@@ -79,7 +79,7 @@ public class ControlLoopCompilerTest {
public void testSuccessConnectedToUnknownPolicy() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
- "Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy");
+ RESTART_UNKNOWN_POLICY);
this.test("src/test/resources/v1.0.0/bad_policy_success_connected_to_unknown_policy.yaml");
}
@@ -87,7 +87,7 @@ public class ControlLoopCompilerTest {
public void testFailureConnectedToUnknownPolicy() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
- "Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy");
+ RESTART_UNKNOWN_POLICY);
this.test("src/test/resources/v1.0.0/bad_policy_failure_connected_to_unknown_policy.yaml");
}
@@ -95,7 +95,7 @@ public class ControlLoopCompilerTest {
public void testFailureTimeoutToUnknownPolicy() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
- "Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy");
+ RESTART_UNKNOWN_POLICY);
this.test("src/test/resources/v1.0.0/bad_policy_failure_timeout_connected_to_unknown_policy.yaml");
}
@@ -103,7 +103,7 @@ public class ControlLoopCompilerTest {
public void testFailureRetriesToUnknownPolicy() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
- "Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy");
+ RESTART_UNKNOWN_POLICY);
this.test("src/test/resources/v1.0.0/bad_policy_failure_retries_connected_to_unknown_policy.yaml");
}
@@ -111,7 +111,7 @@ public class ControlLoopCompilerTest {
public void testFailureExceptionToUnknownPolicy() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
- "Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy");
+ RESTART_UNKNOWN_POLICY);
this.test("src/test/resources/v1.0.0/bad_policy_failure_exception_connected_to_unknown_policy.yaml");
}
@@ -119,38 +119,38 @@ public class ControlLoopCompilerTest {
public void testFailureGuardToUnknownPolicy() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
- "Operation Policy unique-policy-id-1-restart is connected to unknown policy unknown-policy");
+ RESTART_UNKNOWN_POLICY);
this.test("src/test/resources/v1.0.0/bad_policy_failure_guard_connected_to_unknown_policy.yaml");
}
- @Test
+ @Test
public void testInvalidTriggerPolicyId() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
- "Unexpected value for trigger_policy, should only be "
+ "Unexpected value for trigger_policy, should only be "
+ FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID");
this.test("src/test/resources/v1.0.0/bad_trigger_1.yaml");
}
- @Test
+ @Test
public void testNoTriggerPolicyId() throws Exception {
expectedException.expect(CompilerException.class);
this.test("src/test/resources/v1.0.0/bad_trigger_no_trigger_id.yaml");
}
- @Test
+ @Test
public void testNoControlLoopName() throws Exception {
List<String> expectedOnErrorMessages = new ArrayList<>();
expectedOnErrorMessages.add("Missing controlLoopName");
expectedOnErrorMessages.add("Unsupported version for this compiler");
- TestControlLoopCompilerCallback testControlLoopCompilerCallback =
+ TestControlLoopCompilerCallback testControlLoopCompilerCallback =
new TestControlLoopCompilerCallback(expectedOnErrorMessages);
- this.test("src/test/resources/v1.0.0/bad_control_loop_no_control_loop_name.yaml",
+ this.test("src/test/resources/v1.0.0/bad_control_loop_no_control_loop_name.yaml",
testControlLoopCompilerCallback);
assertTrue(testControlLoopCompilerCallback.areAllExpectedOnErrorsReceived());
}
- @Test
+ @Test
public void testInvalidFinalResult() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage(
@@ -158,7 +158,7 @@ public class ControlLoopCompilerTest {
this.test("src/test/resources/v1.0.0/bad_trigger_2.yaml");
}
- @Test
+ @Test
public void testCompileEmptyFile() throws Exception {
expectedException.expect(CompilerException.class);
expectedException.expectMessage("Could not parse yaml specification.");
@@ -171,24 +171,17 @@ public class ControlLoopCompilerTest {
/**
* Does the actual test.
- *
+ *
* @param testFile test file
* @param controlLoopCompilerCallback callback method
* @return the policy object
* @throws Exception exception
*/
- public ControlLoopPolicy test(String testFile,
+ public ControlLoopPolicy test(String testFile,
ControlLoopCompilerCallback controlLoopCompilerCallback) throws Exception {
try (InputStream is = new FileInputStream(new File(testFile))) {
return ControlLoopCompiler.compile(is, controlLoopCompilerCallback);
- } catch (FileNotFoundException e) {
- fail(e.getMessage());
- } catch (IOException e) {
- fail(e.getMessage());
- } catch (Exception e) {
- throw e;
}
- return null;
}
class TestControlLoopCompilerCallback implements ControlLoopCompilerCallback {
@@ -213,7 +206,7 @@ public class ControlLoopCompilerTest {
}
public boolean areAllExpectedOnErrorsReceived() {
- return expectedOnErrorMessages.size() == 0;
+ return expectedOnErrorMessages.isEmpty();
}
}
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java
index 850a4a374..b963a830d 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml unit test
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -21,89 +21,61 @@
package org.onap.policy.controlloop.compiler;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.io.InputStream;
-
import org.junit.Test;
-
import org.onap.policy.controlloop.guard.compiler.ControlLoopGuardCompiler;
public class ControlLoopGuardCompilerTest {
- @Test
- public void testTest1() {
- try {
- this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml");
- } catch (Exception e) {
- fail(e.getMessage());
- }
+ private static final String ACTOR_ERROR = "Unable to find property 'actor'";
+
+ @Test
+ public void testTest1() throws Exception {
+ this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml");
}
- @Test
- public void testTest2() {
- try {
- this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml");
- } catch (Exception e) {
- fail(e.getMessage());
- }
+ @Test
+ public void testTest2() throws Exception {
+ this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml");
}
- @Test
+ @Test
public void testBad1() {
- try {
- this.test("src/test/resources/v2.0.0-guard/no_guard_policy.yaml");
- } catch (Exception e) {
- e.printStackTrace();
- }
+ assertThatThrownBy(() -> this.test("src/test/resources/v2.0.0-guard/no_guard_policy.yaml"))
+ .hasMessage("Guard policies should not be null");
}
- @Test
+ @Test
public void testBad2() {
- try {
- this.test("src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml");
- } catch (Exception e) {
- e.printStackTrace();
- }
+ assertThatThrownBy(() -> this.test("src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml"))
+ .hasMessageContaining(ACTOR_ERROR);
}
- @Test
+ @Test
public void testBad3() {
- try {
- this.test("src/test/resources/v2.0.0-guard/no_guard_constraint.yaml");
- } catch (Exception e) {
- e.printStackTrace();
- }
+ assertThatThrownBy(() -> this.test("src/test/resources/v2.0.0-guard/no_guard_constraint.yaml"))
+ .hasMessageContaining(ACTOR_ERROR);
}
- @Test
+ @Test
public void testBad4() {
- try {
- this.test("src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml");
- } catch (Exception e) {
- e.printStackTrace();
- }
+ assertThatThrownBy(() -> this.test("src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml"))
+ .hasMessageContaining(ACTOR_ERROR);
}
/**
* Does the actual test.
- *
+ *
* @param testFile input test file
* @throws Exception exception thrown
*/
public void test(String testFile) throws Exception {
try (InputStream is = new FileInputStream(new File(testFile))) {
ControlLoopGuardCompiler.compile(is, null);
- } catch (FileNotFoundException e) {
- fail(e.getMessage());
- } catch (IOException e) {
- fail(e.getMessage());
- } catch (Exception e) {
- throw e;
}
}
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java
index b95d0e007..602e12d6e 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml unit test
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -21,20 +21,17 @@
package org.onap.policy.controlloop.policy;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
-
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
@@ -56,50 +53,54 @@ import org.yaml.snakeyaml.error.YAMLException;
public class ControlLoopPolicyBuilderTest {
+ private static final String RESOURCE1 = "resource1";
+ private static final String TRIGGER_RESTART = "Upon getting the trigger event, restart the VM";
+ private static final String UNKNOWN_POLICY = "Unknown policy ";
+ private static final String RESTART = "Restart";
+ private static final String RESTART_VM = "Restart the VM";
+ private static final String REBUILD = "Rebuild";
+ private static final String REBUILD_VM = "Rebuild VM";
+ private static final String REBUILD_RESTART = "If the restart fails, rebuild it.";
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
- public void testControlLoop() {
- try {
- //
- // Create a builder for our policy
- //
- ControlLoopPolicyBuilder builder =
- ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- //
- // Test add services
- //
- Service scp = new Service("vSCP");
- Service usp = new Service("vUSP");
- Service trinity = new Service("Trinity");
- builder = builder.addService(scp, usp, trinity);
- assertTrue(builder.getControlLoop().getServices().size() == 3);
- //
- // Test remove services
- //
- builder = builder.removeService(scp);
- assertTrue(builder.getControlLoop().getServices().size() == 2);
- builder = builder.removeAllServices();
- assertTrue(builder.getControlLoop().getServices().size() == 0);
- //
- // Test add resources
- //
- Resource cts = new Resource("vCTS", ResourceType.VF);
- Resource com = new Resource("vCTS", ResourceType.VF);
- Resource rar = new Resource("vCTS", ResourceType.VF);
- builder = builder.addResource(cts, com, rar);
- assertTrue(builder.getControlLoop().getResources().size() == 3);
- //
- // Test remove resources
- //
- builder = builder.removeResource(cts);
- assertTrue(builder.getControlLoop().getResources().size() == 2);
- builder = builder.removeAllResources();
- assertTrue(builder.getControlLoop().getResources().size() == 0);
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testControlLoop() throws BuilderException {
+ //
+ // Create a builder for our policy
+ //
+ ControlLoopPolicyBuilder builder =
+ ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
+ //
+ // Test add services
+ //
+ Service scp = new Service("vSCP");
+ Service usp = new Service("vUSP");
+ Service trinity = new Service("Trinity");
+ builder = builder.addService(scp, usp, trinity);
+ assertTrue(builder.getControlLoop().getServices().size() == 3);
+ //
+ // Test remove services
+ //
+ builder = builder.removeService(scp);
+ assertTrue(builder.getControlLoop().getServices().size() == 2);
+ builder = builder.removeAllServices();
+ assertTrue(builder.getControlLoop().getServices().isEmpty());
+ //
+ // Test add resources
+ //
+ Resource cts = new Resource("vCTS", ResourceType.VF);
+ Resource com = new Resource("vCTS", ResourceType.VF);
+ Resource rar = new Resource("vCTS", ResourceType.VF);
+ builder = builder.addResource(cts, com, rar);
+ assertTrue(builder.getControlLoop().getResources().size() == 3);
+ //
+ // Test remove resources
+ //
+ builder = builder.removeResource(cts);
+ assertTrue(builder.getControlLoop().getResources().size() == 2);
+ builder = builder.removeAllResources();
+ assertTrue(builder.getControlLoop().getResources().isEmpty());
}
@Test
@@ -159,14 +160,14 @@ public class ControlLoopPolicyBuilderTest {
assertTrue(builder.getControlLoop().getResources().size() == 1);
builder.removeResource(resourceWithUuid);
- assertTrue(builder.getControlLoop().getResources().size() == 0);
+ assertTrue(builder.getControlLoop().getResources().isEmpty());
}
@Test
public void testRemoveNullResource() throws BuilderException {
ControlLoopPolicyBuilder builder =
ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- Resource resource = new Resource("resource1", ResourceType.VF);
+ Resource resource = new Resource(RESOURCE1, ResourceType.VF);
builder.addResource(resource);
expectedException.expect(BuilderException.class);
expectedException.expectMessage("Resource must not be null");
@@ -179,14 +180,14 @@ public class ControlLoopPolicyBuilderTest {
ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
expectedException.expect(BuilderException.class);
expectedException.expectMessage("No existing resources to remove");
- builder.removeResource(new Resource("resource1", ResourceType.VF));
+ builder.removeResource(new Resource(RESOURCE1, ResourceType.VF));
}
@Test
public void testRemoveInvalidResource() throws BuilderException {
ControlLoopPolicyBuilder builder =
ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- Resource resource = new Resource("resource1", ResourceType.VF);
+ Resource resource = new Resource(RESOURCE1, ResourceType.VF);
builder.addResource(resource);
expectedException.expect(BuilderException.class);
expectedException.expectMessage("Invalid resource - need either a resourceUUID or resourceName");
@@ -197,7 +198,7 @@ public class ControlLoopPolicyBuilderTest {
public void testRemoveUnknownResource() throws BuilderException {
ControlLoopPolicyBuilder builder =
ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- Resource resource = new Resource("resource1", ResourceType.VF);
+ Resource resource = new Resource(RESOURCE1, ResourceType.VF);
builder.addResource(resource);
final String unknownResourceName = "reource2";
expectedException.expect(BuilderException.class);
@@ -206,33 +207,25 @@ public class ControlLoopPolicyBuilderTest {
}
@Test
- public void testControlLoopWithInitialResourceAndServices() {
- try {
- Resource cts = new Resource("vCTS", ResourceType.VF);
- Service scp = new Service("vSCP");
- Service usp = new Service("vUSP");
- ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
- .buildControlLoop(UUID.randomUUID().toString(), 2400, cts, scp, usp);
- assertTrue(builder.getControlLoop().getResources().size() == 1);
- assertTrue(builder.getControlLoop().getServices().size() == 2);
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testControlLoopWithInitialResourceAndServices() throws BuilderException {
+ Resource cts = new Resource("vCTS", ResourceType.VF);
+ Service scp = new Service("vSCP");
+ Service usp = new Service("vUSP");
+ ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
+ .buildControlLoop(UUID.randomUUID().toString(), 2400, cts, scp, usp);
+ assertTrue(builder.getControlLoop().getResources().size() == 1);
+ assertTrue(builder.getControlLoop().getServices().size() == 2);
}
@Test
- public void testControlLoopWithInitialResourcesAndService() {
- try {
- Resource cts = new Resource("vCTS", ResourceType.VF);
- Resource com = new Resource("vCTS", ResourceType.VF);
- Service scp = new Service("vSCP");
- ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
- .buildControlLoop(UUID.randomUUID().toString(), 2400, scp, cts, com);
- assertTrue(builder.getControlLoop().getServices().size() == 1);
- assertTrue(builder.getControlLoop().getResources().size() == 2);
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testControlLoopWithInitialResourcesAndService() throws BuilderException {
+ Resource cts = new Resource("vCTS", ResourceType.VF);
+ Resource com = new Resource("vCTS", ResourceType.VF);
+ Service scp = new Service("vSCP");
+ ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
+ .buildControlLoop(UUID.randomUUID().toString(), 2400, scp, cts, com);
+ assertTrue(builder.getControlLoop().getServices().size() == 1);
+ assertTrue(builder.getControlLoop().getResources().size() == 2);
}
@Test
@@ -244,19 +237,15 @@ public class ControlLoopPolicyBuilderTest {
// This constructor does not copy the value of pnf into the newly created object
// On the face of it, this looks like a bug, but perhaps there is a reason for this
// PLEASE ADVISE IF THE BEHAVIOUR IS INCORRECT OR THE TEST CASE IS INVALID
- public void testControlLoopForPnf() {
- try {
- Pnf pnf = new Pnf();
- pnf.setPnfType(PnfType.ENODEB);
- ControlLoopPolicyBuilder builder =
- ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400, pnf);
- assertEquals(pnf, builder.getControlLoop().getPnf());
-
- builder.removePNF();
- assertNull(builder.getControlLoop().getPnf());
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testControlLoopForPnf() throws BuilderException {
+ Pnf pnf = new Pnf();
+ pnf.setPnfType(PnfType.ENODEB);
+ ControlLoopPolicyBuilder builder =
+ ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400, pnf);
+ assertEquals(pnf, builder.getControlLoop().getPnf());
+
+ builder.removePNF();
+ assertNull(builder.getControlLoop().getPnf());
}
@Test
@@ -313,109 +302,99 @@ public class ControlLoopPolicyBuilderTest {
}
@Test
- public void testTimeout() {
- try {
- //
- // Create a builder for our policy
- //
- ControlLoopPolicyBuilder builder =
- ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- //
- // Test setTimeout
- //
- assertTrue(builder.getControlLoop().getTimeout() == 2400);
- builder = builder.setTimeout(800);
- assertTrue(builder.getControlLoop().getTimeout() == 800);
- //
- // Test calculateTimeout
- //
- Policy trigger =
- builder.setTriggerPolicy(PolicyParam.builder().id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Restart")
- .payload(null)
- .retries(2)
- .timeout(300).build());
- @SuppressWarnings("unused")
- Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult(
- PolicyParam.builder()
- .name("Rebuild VM")
- .description("If the restart fails, rebuild it")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Rebuild")
- .payload(null)
- .retries(1)
- .timeout(600)
- .id(trigger.getId()).build(),
- PolicyResult.FAILURE,
- PolicyResult.FAILURE_RETRIES,
- PolicyResult.FAILURE_TIMEOUT);
- assertTrue(builder.calculateTimeout().equals(new Integer(300 + 600)));
- //
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testTimeout() throws BuilderException {
+ //
+ // Create a builder for our policy
+ //
+ ControlLoopPolicyBuilder builder =
+ ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
+ //
+ // Test setTimeout
+ //
+ assertTrue(builder.getControlLoop().getTimeout() == 2400);
+ builder = builder.setTimeout(800);
+ assertTrue(builder.getControlLoop().getTimeout() == 800);
+ //
+ // Test calculateTimeout
+ //
+ Policy trigger =
+ builder.setTriggerPolicy(PolicyParam.builder().id(UUID.randomUUID().toString())
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(RESTART)
+ .payload(null)
+ .retries(2)
+ .timeout(300).build());
+ @SuppressWarnings("unused")
+ Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult(
+ PolicyParam.builder()
+ .name(REBUILD_VM)
+ .description("If the restart fails, rebuild it")
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(REBUILD)
+ .payload(null)
+ .retries(1)
+ .timeout(600)
+ .id(trigger.getId()).build(),
+ PolicyResult.FAILURE,
+ PolicyResult.FAILURE_RETRIES,
+ PolicyResult.FAILURE_TIMEOUT);
+ assertTrue(builder.calculateTimeout().equals(new Integer(300 + 600)));
}
@Test
- public void testTriggerPolicyMethods() {
- try {
- ControlLoopPolicyBuilder builder =
- ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- //
- // Test isOpenLoop
- //
- assertTrue(builder.isOpenLoop());
- //
- // Test set initial trigger policy
- //
- Policy triggerPolicy1 =
- builder.setTriggerPolicy(
- PolicyParam.builder().id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Restart")
- .payload(null)
- .retries(2)
- .timeout(300).build());
- assertTrue(builder.isOpenLoop() == false);
- assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId()));
- //
- // Set trigger policy to a new policy
- //
- @SuppressWarnings("unused")
- Policy triggerPolicy2 =
- builder.setTriggerPolicy(
- PolicyParam.builder()
- .id(UUID.randomUUID().toString())
- .name("Rebuild the VM")
- .description("Upon getting the trigger event, rebuild the VM")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Rebuild")
- .payload(null)
- .retries(2)
- .timeout(300).build());
- //
- // Test set trigger policy to another existing policy
- //
- @SuppressWarnings("unused")
- ControlLoop cl = builder.setExistingTriggerPolicy(triggerPolicy1.getId());
- assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId()));
- //
- // Test get trigger policy
- //
- assertTrue(builder.getTriggerPolicy().equals(triggerPolicy1));
- //
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testTriggerPolicyMethods() throws BuilderException {
+ ControlLoopPolicyBuilder builder =
+ ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
+ //
+ // Test isOpenLoop
+ //
+ assertTrue(builder.isOpenLoop());
+ //
+ // Test set initial trigger policy
+ //
+ Policy triggerPolicy1 =
+ builder.setTriggerPolicy(
+ PolicyParam.builder().id(UUID.randomUUID().toString())
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(RESTART)
+ .payload(null)
+ .retries(2)
+ .timeout(300).build());
+ assertFalse(builder.isOpenLoop());
+ assertEquals(builder.getControlLoop().getTrigger_policy(), triggerPolicy1.getId());
+ //
+ // Set trigger policy to a new policy
+ //
+ @SuppressWarnings("unused")
+ Policy triggerPolicy2 =
+ builder.setTriggerPolicy(
+ PolicyParam.builder()
+ .id(UUID.randomUUID().toString())
+ .name("Rebuild the VM")
+ .description("Upon getting the trigger event, rebuild the VM")
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(REBUILD)
+ .payload(null)
+ .retries(2)
+ .timeout(300).build());
+ //
+ // Test set trigger policy to another existing policy
+ //
+ @SuppressWarnings("unused")
+ ControlLoop cl = builder.setExistingTriggerPolicy(triggerPolicy1.getId());
+ assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId()));
+ //
+ // Test get trigger policy
+ //
+ assertTrue(builder.getTriggerPolicy().equals(triggerPolicy1));
}
@Test
@@ -433,7 +412,7 @@ public class ControlLoopPolicyBuilderTest {
ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
final String unknownPolicyId = "100";
expectedException.expect(BuilderException.class);
- expectedException.expectMessage("Unknown policy " + unknownPolicyId);
+ expectedException.expectMessage(UNKNOWN_POLICY + unknownPolicyId);
builder.setExistingTriggerPolicy(unknownPolicyId);
}
@@ -444,152 +423,147 @@ public class ControlLoopPolicyBuilderTest {
builder.setTriggerPolicy(
PolicyParam.builder()
.id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
.actor("APPC")
.target(new Target(TargetType.VM))
- .recipe("Restart")
+ .recipe(RESTART)
.payload(null)
.retries(2)
.timeout(300).build());
final String unknownPolicyId = "100";
expectedException.expect(BuilderException.class);
- expectedException.expectMessage("Unknown policy " + unknownPolicyId);
+ expectedException.expectMessage(UNKNOWN_POLICY + unknownPolicyId);
builder.setExistingTriggerPolicy(unknownPolicyId);
}
@Test
- public void testAddRemovePolicies() {
- try {
- ControlLoopPolicyBuilder builder =
- ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- Policy triggerPolicy =
- builder.setTriggerPolicy(
- PolicyParam.builder()
- .id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Restart")
- .payload(null)
- .retries(2)
- .timeout(300).build());
- //
- // Test create a policy and chain it to the results of trigger policy
- //
- Policy onRestartFailurePolicy1 = builder.setPolicyForPolicyResult(
- PolicyParam.builder()
- .name("Rebuild VM")
- .description("If the restart fails, rebuild it.")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Rebuild")
- .payload(null)
- .retries(1)
- .timeout(600)
- .id(triggerPolicy.getId()).build(),
- PolicyResult.FAILURE,
- PolicyResult.FAILURE_EXCEPTION,
- PolicyResult.FAILURE_RETRIES,
- PolicyResult.FAILURE_TIMEOUT,
- PolicyResult.FAILURE_GUARD);
- //
- assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy1.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId()));
-
- //
- // Test create a policy and chain it to the results of trigger policy success
- //
- Policy onSuccessPolicy1 = builder.setPolicyForPolicyResult(
- PolicyParam.builder()
- .name("Do something")
- .description("If the restart succeeds, do something else.")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("SomethingElse")
- .payload(null)
- .retries(1)
- .timeout(600)
- .id(triggerPolicy.getId()).build(),
- PolicyResult.SUCCESS);
- //
- assertTrue(builder.getTriggerPolicy().getSuccess().equals(onSuccessPolicy1.getId()));
-
- //
- // Test remove policy
- //
- boolean removed = builder.removePolicy(onRestartFailurePolicy1.getId());
- assertTrue(removed);
- assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
- assertTrue(builder.getTriggerPolicy().getFailure_retries()
- .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
- assertTrue(builder.getTriggerPolicy().getFailure_timeout()
- .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
- assertTrue(
- builder.getTriggerPolicy().getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString()));
- //
- // Create another policy and chain it to the results of trigger policy
- //
- final Policy onRestartFailurePolicy2 =
- builder.setPolicyForPolicyResult(
- PolicyParam.builder()
- .name("Rebuild VM")
- .description("If the restart fails, rebuild it.")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Rebuild")
- .payload(null)
- .retries(2)
- .timeout(600)
- .id(triggerPolicy.getId()).build(),
- PolicyResult.FAILURE,
- PolicyResult.FAILURE_RETRIES,
- PolicyResult.FAILURE_TIMEOUT);
- //
- // Test reset policy results
- //
- triggerPolicy = builder.resetPolicyResults(triggerPolicy.getId());
- assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
- assertTrue(builder.getTriggerPolicy().getFailure_retries()
- .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
- assertTrue(builder.getTriggerPolicy().getFailure_timeout()
- .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
- //
- // Test set the policy results to an existing operational policy
- //
- Policy onRestartFailurePolicy3 =
- builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
- PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
- assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy3.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy3.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy3.getId()));
- //
- // Test set the policy result for success to an existing operational policy
- //
- Policy onRestartFailurePolicy4 =
- builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
- PolicyResult.FAILURE, PolicyResult.FAILURE_EXCEPTION, PolicyResult.FAILURE_GUARD,
- PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.SUCCESS);
- assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy4.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy4.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy4.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy4.getId()));
- assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy4.getId()));
- assertTrue(builder.getTriggerPolicy().getSuccess().equals(onRestartFailurePolicy4.getId()));
-
- //
- // Test remove all existing operational policies
- //
- builder = builder.removeAllPolicies();
- assertTrue(builder.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString()));
- //
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testAddRemovePolicies() throws BuilderException {
+ ControlLoopPolicyBuilder builder =
+ ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
+ Policy triggerPolicy =
+ builder.setTriggerPolicy(
+ PolicyParam.builder()
+ .id(UUID.randomUUID().toString())
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(RESTART)
+ .payload(null)
+ .retries(2)
+ .timeout(300).build());
+ //
+ // Test create a policy and chain it to the results of trigger policy
+ //
+ Policy onRestartFailurePolicy1 = builder.setPolicyForPolicyResult(
+ PolicyParam.builder()
+ .name(REBUILD_VM)
+ .description(REBUILD_RESTART)
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(REBUILD)
+ .payload(null)
+ .retries(1)
+ .timeout(600)
+ .id(triggerPolicy.getId()).build(),
+ PolicyResult.FAILURE,
+ PolicyResult.FAILURE_EXCEPTION,
+ PolicyResult.FAILURE_RETRIES,
+ PolicyResult.FAILURE_TIMEOUT,
+ PolicyResult.FAILURE_GUARD);
+ //
+ assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy1.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId()));
+
+ //
+ // Test create a policy and chain it to the results of trigger policy success
+ //
+ Policy onSuccessPolicy1 = builder.setPolicyForPolicyResult(
+ PolicyParam.builder()
+ .name("Do something")
+ .description("If the restart succeeds, do something else.")
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe("SomethingElse")
+ .payload(null)
+ .retries(1)
+ .timeout(600)
+ .id(triggerPolicy.getId()).build(),
+ PolicyResult.SUCCESS);
+ //
+ assertTrue(builder.getTriggerPolicy().getSuccess().equals(onSuccessPolicy1.getId()));
+
+ //
+ // Test remove policy
+ //
+ boolean removed = builder.removePolicy(onRestartFailurePolicy1.getId());
+ assertTrue(removed);
+ assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
+ assertTrue(builder.getTriggerPolicy().getFailure_retries()
+ .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
+ assertTrue(builder.getTriggerPolicy().getFailure_timeout()
+ .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
+ assertTrue(
+ builder.getTriggerPolicy().getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString()));
+ //
+ // Create another policy and chain it to the results of trigger policy
+ //
+ final Policy onRestartFailurePolicy2 =
+ builder.setPolicyForPolicyResult(
+ PolicyParam.builder()
+ .name(REBUILD_VM)
+ .description(REBUILD_RESTART)
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(REBUILD)
+ .payload(null)
+ .retries(2)
+ .timeout(600)
+ .id(triggerPolicy.getId()).build(),
+ PolicyResult.FAILURE,
+ PolicyResult.FAILURE_RETRIES,
+ PolicyResult.FAILURE_TIMEOUT);
+ //
+ // Test reset policy results
+ //
+ triggerPolicy = builder.resetPolicyResults(triggerPolicy.getId());
+ assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
+ assertTrue(builder.getTriggerPolicy().getFailure_retries()
+ .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
+ assertTrue(builder.getTriggerPolicy().getFailure_timeout()
+ .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
+ //
+ // Test set the policy results to an existing operational policy
+ //
+ Policy onRestartFailurePolicy3 =
+ builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
+ PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
+ assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy3.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy3.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy3.getId()));
+ //
+ // Test set the policy result for success to an existing operational policy
+ //
+ Policy onRestartFailurePolicy4 =
+ builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
+ PolicyResult.FAILURE, PolicyResult.FAILURE_EXCEPTION, PolicyResult.FAILURE_GUARD,
+ PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.SUCCESS);
+ assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy4.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy4.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy4.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy4.getId()));
+ assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy4.getId()));
+ assertTrue(builder.getTriggerPolicy().getSuccess().equals(onRestartFailurePolicy4.getId()));
+
+ //
+ // Test remove all existing operational policies
+ //
+ builder = builder.removeAllPolicies();
+ assertTrue(builder.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString()));
}
@Test
@@ -598,15 +572,15 @@ public class ControlLoopPolicyBuilderTest {
ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
final String policyId = "100";
expectedException.expect(BuilderException.class);
- expectedException.expectMessage("Unknown policy " + policyId);
+ expectedException.expectMessage(UNKNOWN_POLICY + policyId);
builder.setPolicyForPolicyResult(
PolicyParam.builder()
- .name("Rebuild VM")
- .description("If the restart fails, rebuild it.")
+ .name(REBUILD_VM)
+ .description(REBUILD_RESTART)
.actor("APPC")
.target(new Target(TargetType.VM))
- .recipe("Rebuild")
+ .recipe(REBUILD)
.payload(null)
.retries(1)
.timeout(600)
@@ -625,11 +599,11 @@ public class ControlLoopPolicyBuilderTest {
builder.setTriggerPolicy(
PolicyParam.builder()
.id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
.actor("APPC")
.target(new Target(TargetType.VM))
- .recipe("Restart")
+ .recipe(RESTART)
.payload(null)
.retries(2)
.timeout(300).build());
@@ -637,11 +611,11 @@ public class ControlLoopPolicyBuilderTest {
Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult(
PolicyParam.builder()
- .name("Rebuild VM")
- .description("If the restart fails, rebuild it.")
+ .name(REBUILD_VM)
+ .description(REBUILD_RESTART)
.actor("APPC")
.target(new Target(TargetType.VM))
- .recipe("Rebuild")
+ .recipe(REBUILD)
.payload(null)
.retries(1)
.timeout(600)
@@ -663,11 +637,11 @@ public class ControlLoopPolicyBuilderTest {
builder.setTriggerPolicy(
PolicyParam.builder()
.id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
.actor("APPC")
.target(new Target(TargetType.VM))
- .recipe("Restart")
+ .recipe(RESTART)
.payload(null)
.retries(2)
.timeout(300).build());
@@ -680,200 +654,182 @@ public class ControlLoopPolicyBuilderTest {
}
@Test
- public void testAddOperationsAccumulateParams() {
- try {
- ControlLoopPolicyBuilder builder =
- ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
- Policy triggerPolicy =
- builder.setTriggerPolicy(
- PolicyParam.builder()
- .id(UUID.randomUUID().toString())
- .name("Restart the eNodeB")
- .description("Upon getting the trigger event, restart the eNodeB")
- .actor("RANController")
- .target(new Target(TargetType.PNF))
- .recipe("Restart")
- .payload(null)
- .retries(2)
- .timeout(300).build());
- //
- // Add the operationsAccumulateParams
- //
- triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.getId(),
- new OperationsAccumulateParams("15m", 5));
- assertNotNull(builder.getTriggerPolicy().getOperationsAccumulateParams());
- assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getPeriod().equals("15m"));
- assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getLimit() == 5);
- //
- } catch (BuilderException e) {
- fail(e.getMessage());
- }
+ public void testAddOperationsAccumulateParams() throws BuilderException {
+ ControlLoopPolicyBuilder builder =
+ ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
+ Policy triggerPolicy =
+ builder.setTriggerPolicy(
+ PolicyParam.builder()
+ .id(UUID.randomUUID().toString())
+ .name("Restart the eNodeB")
+ .description("Upon getting the trigger event, restart the eNodeB")
+ .actor("RANController")
+ .target(new Target(TargetType.PNF))
+ .recipe(RESTART)
+ .payload(null)
+ .retries(2)
+ .timeout(300).build());
+ //
+ // Add the operationsAccumulateParams
+ //
+ triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.getId(),
+ new OperationsAccumulateParams("15m", 5));
+ assertNotNull(builder.getTriggerPolicy().getOperationsAccumulateParams());
+ assertEquals("15m", builder.getTriggerPolicy().getOperationsAccumulateParams().getPeriod());
+ assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getLimit() == 5);
}
@Test
- public void testBuildSpecification() {
- try {
- //
- // Create the builder
- //
- ControlLoopPolicyBuilder builder =
- ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800);
- //
- // Set the first invalid trigger policy
- //
- final Policy policy1 = builder.setTriggerPolicy(
- PolicyParam.builder()
- .id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
- .actor(null)
- .target(null)
- .recipe("Instantiate")
- .payload(null)
- .retries(2)
- .timeout(300).build());
- Results results = builder.buildSpecification();
- //
- // Check that ERRORs are in results for invalid policy arguments
- //
- boolean invalidActor = false;
- boolean invalidRecipe = false;
- boolean invalidTarget = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) {
- invalidActor = true;
- }
- if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) {
- invalidRecipe = true;
- }
- if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) {
- invalidTarget = true;
- }
+ public void testBuildSpecification() throws BuilderException {
+ //
+ // Create the builder
+ //
+ ControlLoopPolicyBuilder builder =
+ ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800);
+ //
+ // Set the first invalid trigger policy
+ //
+ final Policy policy1 = builder.setTriggerPolicy(
+ PolicyParam.builder()
+ .id(UUID.randomUUID().toString())
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
+ .actor(null)
+ .target(null)
+ .recipe("Instantiate")
+ .payload(null)
+ .retries(2)
+ .timeout(300).build());
+ Results results = builder.buildSpecification();
+ //
+ // Check that ERRORs are in results for invalid policy arguments
+ //
+ boolean invalidActor = false;
+ boolean invalidRecipe = false;
+ boolean invalidTarget = false;
+ for (Message m : results.getMessages()) {
+ if ("Policy actor is null".equals(m.getMessage()) && m.getLevel() == MessageLevel.ERROR) {
+ invalidActor = true;
}
- //
- assertTrue(invalidActor);
- assertTrue(invalidRecipe);
- assertTrue(invalidTarget);
- //
- // Remove the invalid policy
- //
- // @SuppressWarnings("unused")
- boolean removed = builder.removePolicy(policy1.getId());
- assertTrue(removed);
- assertTrue(builder.getTriggerPolicy() == null);
- //
- // Set a valid trigger policy
- //
- Policy policy1a = builder.setTriggerPolicy(
- PolicyParam.builder()
- .id(UUID.randomUUID().toString())
- .name("Rebuild VM")
- .description("If the restart fails, rebuild it.")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Rebuild")
- .payload(null)
- .retries(1)
- .timeout(600).build());
- //
- // Set a second valid trigger policy
- //
- final Policy policy2 =
- builder.setTriggerPolicy(
- PolicyParam.builder()
- .id(UUID.randomUUID().toString())
- .name("Restart the VM")
- .description("Upon getting the trigger event, restart the VM")
- .actor("APPC")
- .target(new Target(TargetType.VM))
- .recipe("Restart")
- .payload(null)
- .retries(2)
- .timeout(300).build());
- //
- // Now, we have policy1 unreachable
- //
- results = builder.buildSpecification();
- boolean unreachable = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage().equals("Policy " + policy1a.getId() + " is not reachable.")
- && m.getLevel() == MessageLevel.WARNING) {
- unreachable = true;
- break;
- }
+ if ("Policy recipe is invalid".equals(m.getMessage()) && m.getLevel() == MessageLevel.ERROR) {
+ invalidRecipe = true;
}
- assertTrue(unreachable);
- //
- // Set policy1a for the failure results of policy2
- //
- policy1a = builder.setPolicyForPolicyResult(policy1a.getId(), policy2.getId(), PolicyResult.FAILURE,
- PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
- results = builder.buildSpecification();
- boolean invalidTimeout = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage()
- .equals("controlLoop overall timeout is less than the sum of operational policy timeouts.")
- && m.getLevel() == MessageLevel.ERROR) {
- invalidTimeout = true;
- break;
- }
+ if ("Policy target is null".equals(m.getMessage()) && m.getLevel() == MessageLevel.ERROR) {
+ invalidTarget = true;
}
- assertTrue(invalidTimeout);
- //
- // Remove policy2 (revert controlLoop back to open loop)
- //
- removed = builder.removePolicy(policy2.getId());
- //
- // ControlLoop is open loop now, but it still has policies (policy1)
- //
- results = builder.buildSpecification();
- unreachable = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.")
- && m.getLevel() == MessageLevel.WARNING) {
- unreachable = true;
- break;
- }
+ }
+ //
+ assertTrue(invalidActor);
+ assertTrue(invalidRecipe);
+ assertTrue(invalidTarget);
+ //
+ // Remove the invalid policy
+ //
+ // @SuppressWarnings("unused")
+ boolean removed = builder.removePolicy(policy1.getId());
+ assertTrue(removed);
+ assertTrue(builder.getTriggerPolicy() == null);
+ //
+ // Set a valid trigger policy
+ //
+ Policy policy1a = builder.setTriggerPolicy(
+ PolicyParam.builder()
+ .id(UUID.randomUUID().toString())
+ .name(REBUILD_VM)
+ .description(REBUILD_RESTART)
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(REBUILD)
+ .payload(null)
+ .retries(1)
+ .timeout(600).build());
+ //
+ // Set a second valid trigger policy
+ //
+ final Policy policy2 =
+ builder.setTriggerPolicy(
+ PolicyParam.builder()
+ .id(UUID.randomUUID().toString())
+ .name(RESTART_VM)
+ .description(TRIGGER_RESTART)
+ .actor("APPC")
+ .target(new Target(TargetType.VM))
+ .recipe(RESTART)
+ .payload(null)
+ .retries(2)
+ .timeout(300).build());
+ //
+ // Now, we have policy1 unreachable
+ //
+ results = builder.buildSpecification();
+ boolean unreachable = false;
+ for (Message m : results.getMessages()) {
+ if (m.getMessage().equals("Policy " + policy1a.getId() + " is not reachable.")
+ && m.getLevel() == MessageLevel.WARNING) {
+ unreachable = true;
+ break;
+ }
+ }
+ assertTrue(unreachable);
+ //
+ // Set policy1a for the failure results of policy2
+ //
+ policy1a = builder.setPolicyForPolicyResult(policy1a.getId(), policy2.getId(), PolicyResult.FAILURE,
+ PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
+ results = builder.buildSpecification();
+ boolean invalidTimeout = false;
+ for (Message m : results.getMessages()) {
+ if ("controlLoop overall timeout is less than the sum of operational policy timeouts."
+ .equals(m.getMessage()) && m.getLevel() == MessageLevel.ERROR) {
+ invalidTimeout = true;
+ break;
+ }
+ }
+ assertTrue(invalidTimeout);
+ //
+ // Remove policy2 (revert controlLoop back to open loop)
+ //
+ removed = builder.removePolicy(policy2.getId());
+ //
+ // ControlLoop is open loop now, but it still has policies (policy1)
+ //
+ results = builder.buildSpecification();
+ unreachable = false;
+ for (Message m : results.getMessages()) {
+ if ("Open Loop policy contains policies. The policies will never be invoked.".equals(m.getMessage())
+ && m.getLevel() == MessageLevel.WARNING) {
+ unreachable = true;
+ break;
}
- assertTrue(unreachable);
- //
- } catch (BuilderException e) {
- fail(e.getMessage());
}
+ assertTrue(unreachable);
}
@Test
- public void test1() {
+ public void test1() throws Exception {
this.test("src/test/resources/v1.0.0/policy_Test.yaml");
}
@Test
- public void testEvilYaml() {
+ public void testEvilYaml() throws Exception {
try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) {
//
- // Read the yaml into our Java Object
+ // Attempt to read the yaml into our Java Object
//
Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
- yaml.load(is);
- } catch (FileNotFoundException e) {
- fail(e.getLocalizedMessage());
- } catch (IOException e) {
- fail(e.getLocalizedMessage());
- } catch (YAMLException e) {
- //
- // Should have this
- //
+ assertThatThrownBy(() -> yaml.load(is)).isInstanceOf(YAMLException.class);
}
}
/**
* Does the actual test.
- *
+ *
* @param testFile input file
+ * @throws Exception if an error occurs
*/
- public void test(String testFile) {
+ public void test(String testFile) throws Exception {
try (InputStream is = new FileInputStream(new File(testFile))) {
//
// Read the yaml into our Java Object
@@ -912,36 +868,34 @@ public class ControlLoopPolicyBuilderTest {
// Add the policies and be sure to set the trigger policy
//
if (policyTobuild.getPolicies() != null) {
- for (Policy policy : policyTobuild.getPolicies()) {
- if (policy.getId() == policyTobuild.getControlLoop().getTrigger_policy()) {
- builder.setTriggerPolicy(
- PolicyParam.builder()
- .id(UUID.randomUUID().toString())
- .name(policy.getName())
- .description(policy.getDescription())
- .actor(policy.getActor())
- .target(policy.getTarget())
- .recipe(policy.getRecipe())
- .payload(null)
- .retries(policy.getRetry())
- .timeout(policy.getTimeout()).build());
- }
- }
+ setTriggerPolicies(policyTobuild, builder);
}
// Question : how to change policy ID and results by using builder ??
@SuppressWarnings("unused")
Results results = builder.buildSpecification();
-
- } catch (FileNotFoundException e) {
- fail(e.getLocalizedMessage());
- } catch (IOException e) {
- fail(e.getLocalizedMessage());
- } catch (BuilderException e) {
- fail(e.getLocalizedMessage());
}
}
+ private void setTriggerPolicies(ControlLoopPolicy policyTobuild, ControlLoopPolicyBuilder builder)
+ throws BuilderException {
+ for (Policy policy : policyTobuild.getPolicies()) {
+ if (policy.getId() == policyTobuild.getControlLoop().getTrigger_policy()) {
+ builder.setTriggerPolicy(
+ PolicyParam.builder()
+ .id(UUID.randomUUID().toString())
+ .name(policy.getName())
+ .description(policy.getDescription())
+ .actor(policy.getActor())
+ .target(policy.getTarget())
+ .recipe(policy.getRecipe())
+ .payload(null)
+ .retries(policy.getRetry())
+ .timeout(policy.getTimeout()).build());
+ }
+ }
+ }
+
}
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java
index 9c92b7573..61d9ed45c 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml unit test
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -21,16 +21,13 @@
package org.onap.policy.controlloop.policy;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.io.InputStream;
-
import org.junit.Test;
import org.onap.policy.common.utils.io.Serializer;
import org.slf4j.Logger;
@@ -43,54 +40,55 @@ import org.yaml.snakeyaml.constructor.Constructor;
public class ControlLoopPolicyTest {
private static final Logger logger = LoggerFactory.getLogger(ControlLoopPolicyTest.class);
-
- @Test
- public void test1() {
+
+ @Test
+ public void test1() throws Exception {
this.test("src/test/resources/v1.0.0/policy_Test.yaml");
}
- @Test
- public void testvService1() {
+ @Test
+ public void testvService1() throws Exception {
this.test("src/test/resources/v1.0.0/policy_vService.yaml");
}
- @Test
- public void testOpenLoop() {
+ @Test
+ public void testOpenLoop() throws Exception {
this.test("src/test/resources/v1.0.0/policy_OpenLoop.yaml");
}
- @Test
- public void testvdns() {
+ @Test
+ public void testvdns() throws Exception {
this.test("src/test/resources/v2.0.0/policy_ONAP_demo_vDNS.yaml");
}
- @Test
+ @Test
public void testvFirewall() {
// Chenfei to fix this.
// this.test("src/test/resources/v2.0.0/policy_ONAP_demo_vFirewall.yaml");
}
- @Test
- public void testvcpe() {
+ @Test
+ public void testvcpe() throws Exception {
this.test("src/test/resources/v2.0.0/policy_ONAP_UseCase_vCPE.yaml");
}
- @Test
- public void testvpci() {
+ @Test
+ public void testvpci() throws Exception {
this.test("src/test/resources/v2.0.0/policy_ONAP_UseCase_vPCI.yaml");
}
- @Test
- public void testvolte() {
+ @Test
+ public void testvolte() throws Exception {
this.test("src/test/resources/v2.0.0/policy_ONAP_UseCase_VOLTE.yaml");
}
/**
* Does the actual test.
- *
+ *
* @param testFile input file
+ * @throws Exception if an error occurs
*/
- public void test(String testFile) {
+ public void test(String testFile) throws Exception {
try (InputStream is = new FileInputStream(new File(testFile))) {
//
// Read the yaml into our Java Object
@@ -116,21 +114,12 @@ public class ControlLoopPolicyTest {
dump(newObject);
assertNotNull(newObject);
assertTrue(newObject instanceof ControlLoopPolicy);
- //
- // Have to comment it out tentatively since it causes junit to fail.
- // Seems we cannot use assertEquals here. Need advice.
- //
- //assertEquals(newObject, obj);
-
+ assertEquals(obj, newObject);
+
// test serialization
ControlLoopPolicy policy = (ControlLoopPolicy) obj;
ControlLoopPolicy policy2 = Serializer.roundTrip(policy);
assertTrue(policy.equals(policy2));
-
- } catch (FileNotFoundException e) {
- fail(e.getLocalizedMessage());
- } catch (IOException e) {
- fail(e.getLocalizedMessage());
}
}
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java
index 142b51b18..23287da68 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -39,6 +39,11 @@ import org.onap.policy.sdc.Service;
public class ControlLoopTest {
+ private static final String SERVICE2 = "service2";
+ private static final String SERVICE1 = "service1";
+ private static final String RESOURCE2 = "resource2";
+ private static final String RESOURCE1 = "resource1";
+ private static final String PNF1 = "pnf 1";
private String controlLoopName = "control loop 1";
private String version = "1.0.1";
private String triggerPolicy = FinalResult.FINAL_OPENLOOP.toString();
@@ -66,7 +71,7 @@ public class ControlLoopTest {
@Test
public void testEqualsNoServicesAndResourcesOrTimeout() {
final Pnf pnf = new Pnf();
- pnf.setPnfName("pnf 1");
+ pnf.setPnfName(PNF1);
ControlLoop controlLoop1 = new ControlLoop();
controlLoop1.setControlLoopName(controlLoopName);
@@ -88,19 +93,19 @@ public class ControlLoopTest {
@Test
public void testEquals() throws IOException {
final Pnf pnf = new Pnf();
- pnf.setPnfName("pnf 1");
+ pnf.setPnfName(PNF1);
ControlLoop controlLoop1 = new ControlLoop();
controlLoop1.setControlLoopName(controlLoopName);
controlLoop1.setVersion(version);
- Service service1 = new Service("service1");
- Service service2 = new Service("service2");
+ Service service1 = new Service(SERVICE1);
+ Service service2 = new Service(SERVICE2);
List<Service> services = new ArrayList<>();
services.add(service1);
services.add(service2);
controlLoop1.setServices(services);
- Resource resource1 = new Resource("resource1", ResourceType.VF);
- Resource resource2 = new Resource("resource2", ResourceType.VFC);
+ Resource resource1 = new Resource(RESOURCE1, ResourceType.VF);
+ Resource resource2 = new Resource(RESOURCE2, ResourceType.VFC);
List<Resource> resources = new ArrayList<>();
resources.add(resource1);
resources.add(resource2);
@@ -113,14 +118,14 @@ public class ControlLoopTest {
ControlLoop controlLoop2 = new ControlLoop();
controlLoop2.setControlLoopName(controlLoopName);
controlLoop2.setVersion(version);
- Service controlLoop2Service1 = new Service("service1");
- Service controlLoop2Service2 = new Service("service2");
+ Service controlLoop2Service1 = new Service(SERVICE1);
+ Service controlLoop2Service2 = new Service(SERVICE2);
List<Service> controlLoop2Services = new ArrayList<>();
controlLoop2Services.add(controlLoop2Service1);
controlLoop2Services.add(controlLoop2Service2);
controlLoop2.setServices(controlLoop2Services);
- Resource controlLoop2Resource1 = new Resource("resource1", ResourceType.VF);
- Resource controlLoop2Resource2 = new Resource("resource2", ResourceType.VFC);
+ Resource controlLoop2Resource1 = new Resource(RESOURCE1, ResourceType.VF);
+ Resource controlLoop2Resource2 = new Resource(RESOURCE2, ResourceType.VFC);
List<Resource> controlLoop2Resources = new ArrayList<>();
controlLoop2Resources.add(controlLoop2Resource1);
controlLoop2Resources.add(controlLoop2Resource2);
@@ -146,19 +151,19 @@ public class ControlLoopTest {
// PLEASE ADVISE IF THE EXISTING BEHAVIOUR IS CORRECT
public void testControlLoop() {
final Pnf pnf = new Pnf();
- pnf.setPnfName("pnf 1");
+ pnf.setPnfName(PNF1);
ControlLoop controlLoop1 = new ControlLoop();
controlLoop1.setControlLoopName(controlLoopName);
controlLoop1.setVersion(version);
- Service service1 = new Service("service1");
- Service service2 = new Service("service2");
+ Service service1 = new Service(SERVICE1);
+ Service service2 = new Service(SERVICE2);
List<Service> services = new ArrayList<>();
services.add(service1);
services.add(service2);
controlLoop1.setServices(services);
- Resource resource1 = new Resource("resource1", ResourceType.VF);
- Resource resource2 = new Resource("resource2", ResourceType.VFC);
+ Resource resource1 = new Resource(RESOURCE1, ResourceType.VF);
+ Resource resource2 = new Resource(RESOURCE2, ResourceType.VFC);
List<Resource> resources = new ArrayList<>();
resources.add(resource1);
resources.add(resource2);
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java
index 0c8901ffb..e0e6e9772 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ConstraintTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -34,6 +34,10 @@ import org.junit.Test;
public class ConstraintTest {
+ private static final String TIME_WINDOW_VALUE = "timeWindowValue";
+ private static final String TIME_WINDOW_KEY = "timeWindowKey";
+ private static final String BLACKLIST_ITEM = "blacklist item";
+
@Test
public void testConstraint() {
Constraint constraint = new Constraint();
@@ -55,7 +59,7 @@ public class ConstraintTest {
@Test
public void testGetAndSetTime_window() {
Map<String, String> timeWindow = new HashMap<>();
- timeWindow.put("timeWindowKey", "timeWindowValue");
+ timeWindow.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE);
Constraint constraint = new Constraint();
constraint.setTime_window(timeWindow);
assertEquals(timeWindow, constraint.getTime_window());
@@ -64,7 +68,7 @@ public class ConstraintTest {
@Test
public void testGetAndSetActive_time_range() {
Map<String, String> activeTimeRange = new HashMap<>();
- activeTimeRange.put("timeWindowKey", "timeWindowValue");
+ activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE);
Constraint constraint = new Constraint();
constraint.setActive_time_range(activeTimeRange);;
assertEquals(activeTimeRange, constraint.getActive_time_range());
@@ -73,7 +77,7 @@ public class ConstraintTest {
@Test
public void testGetAndSetBlacklist() {
List<String> blacklist = new ArrayList<>();
- blacklist.add("blacklist item");
+ blacklist.add(BLACKLIST_ITEM);
Constraint constraint = new Constraint();
constraint.setBlacklist(blacklist);
assertEquals(blacklist, constraint.getBlacklist());
@@ -95,7 +99,7 @@ public class ConstraintTest {
@Test
public void testConstraintListOfString() {
List<String> blacklist = new ArrayList<>();
- blacklist.add("blacklist item");
+ blacklist.add(BLACKLIST_ITEM);
Constraint constraint = new Constraint(blacklist);
assertNull(constraint.getFreq_limit_per_target());
@@ -109,7 +113,7 @@ public class ConstraintTest {
Integer freqLimitPerTarget = 10;
Map<String, String> timeWindow = new HashMap<>();
List<String> blacklist = new ArrayList<>();
- blacklist.add("blacklist item");
+ blacklist.add(BLACKLIST_ITEM);
Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, blacklist);
assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target());
@@ -123,7 +127,7 @@ public class ConstraintTest {
Integer freqLimitPerTarget = 10;
Map<String, String> timeWindow = new HashMap<>();
Map<String, String> activeTimeRange = new HashMap<>();
- activeTimeRange.put("timeWindowKey", "timeWindowValue");
+ activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE);
Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange);
assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target());
@@ -138,9 +142,9 @@ public class ConstraintTest {
Integer freqLimitPerTarget = 10;
Map<String, String> timeWindow = new HashMap<>();
Map<String, String> activeTimeRange = new HashMap<>();
- activeTimeRange.put("timeWindowKey", "timeWindowValue");
+ activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE);
List<String> blacklist = new ArrayList<>();
- blacklist.add("blacklist item");
+ blacklist.add(BLACKLIST_ITEM);
Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange, blacklist);
assertEquals(freqLimitPerTarget, constraint.getFreq_limit_per_target());
@@ -154,9 +158,9 @@ public class ConstraintTest {
Integer freqLimitPerTarget = 10;
Map<String, String> timeWindow = new HashMap<>();
Map<String, String> activeTimeRange = new HashMap<>();
- activeTimeRange.put("timeWindowKey", "timeWindowValue");
+ activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE);
List<String> blacklist = new ArrayList<>();
- blacklist.add("blacklist item");
+ blacklist.add(BLACKLIST_ITEM);
Constraint constraint1 = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange, blacklist);
Constraint constraint2 = new Constraint(constraint1);
@@ -189,9 +193,9 @@ public class ConstraintTest {
Integer freqLimitPerTarget = 10;
Map<String, String> timeWindow = new HashMap<>();
Map<String, String> activeTimeRange = new HashMap<>();
- activeTimeRange.put("timeWindowKey", "timeWindowValue");
+ activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE);
List<String> blacklist = new ArrayList<>();
- blacklist.add("blacklist item");
+ blacklist.add(BLACKLIST_ITEM);
Constraint constraint = new Constraint(freqLimitPerTarget, timeWindow, activeTimeRange, blacklist);
assertEquals(constraint.toString(), "Constraint [freq_limit_per_target=" + freqLimitPerTarget + ", time_window="
@@ -204,7 +208,7 @@ public class ConstraintTest {
final Map<String, String> timeWindow = new HashMap<>();
final Map<String, String> activeTimeRange = new HashMap<>();
List<String> blacklist = new ArrayList<>();
- blacklist.add("blacklist item");
+ blacklist.add(BLACKLIST_ITEM);
Constraint constraint1 = new Constraint();
Constraint constraint2 = new Constraint();
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java
index f289d931f..a2148120b 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml unit test
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -23,18 +23,14 @@ package org.onap.policy.controlloop.policy.guard;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.onap.policy.controlloop.policy.builder.BuilderException;
import org.onap.policy.controlloop.policy.builder.Message;
@@ -48,135 +44,131 @@ import org.yaml.snakeyaml.constructor.Constructor;
public class ControlLoopGuardBuilderTest {
private static final Logger logger = LoggerFactory.getLogger(ControlLoopGuardBuilderTest.class);
-
+
@Test
- public void testControlLoopGuard() {
- try {
- //
- // Create a builder
- //
- ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
- //
- // Assert there is no guard policies yet
- //
- Results results = builder.buildSpecification();
- boolean noGuardPolicies = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage().equals("ControlLoop Guard should have at least one guard policies")
- && m.getLevel() == MessageLevel.ERROR) {
- noGuardPolicies = true;
- break;
- }
+ public void testControlLoopGuard() throws BuilderException {
+ //
+ // Create a builder
+ //
+ ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
+ //
+ // Assert there is no guard policies yet
+ //
+ Results results = builder.buildSpecification();
+ boolean noGuardPolicies = false;
+ for (Message m : results.getMessages()) {
+ if ("ControlLoop Guard should have at least one guard policies".equals(m.getMessage())
+ && m.getLevel() == MessageLevel.ERROR) {
+ noGuardPolicies = true;
+ break;
}
- assertTrue(noGuardPolicies);
- //
- // Add a guard policy without limit constraint
- //
- String clname = "CL_vUSP123";
- LinkedList<String> targets = new LinkedList<String>();
- targets.add("s1");
- targets.add("s2");
- targets.add("s3");
- MatchParameters matchParameters = new MatchParameters(clname, "APPC", "Restart", targets);
- GuardPolicy policy1 = new GuardPolicy("id123", "guardpolicy1", "description aaa", matchParameters);
- builder = builder.addGuardPolicy(policy1);
- //
- // Assert there is no limit constraint associated with the only guard policy
- //
- results = builder.buildSpecification();
- boolean noConstraint = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage().equals("Guard policy guardpolicy1 does not have any limit constraint")
- && m.getLevel() == MessageLevel.ERROR) {
- noConstraint = true;
- break;
- }
+ }
+ assertTrue(noGuardPolicies);
+ //
+ // Add a guard policy without limit constraint
+ //
+ String clname = "CL_vUSP123";
+ List<String> targets = new LinkedList<>();
+ targets.add("s1");
+ targets.add("s2");
+ targets.add("s3");
+ MatchParameters matchParameters = new MatchParameters(clname, "APPC", "Restart", targets);
+ GuardPolicy policy1 = new GuardPolicy("id123", "guardpolicy1", "description aaa", matchParameters);
+ builder = builder.addGuardPolicy(policy1);
+ //
+ // Assert there is no limit constraint associated with the only guard policy
+ //
+ results = builder.buildSpecification();
+ boolean noConstraint = false;
+ for (Message m : results.getMessages()) {
+ if ("Guard policy guardpolicy1 does not have any limit constraint".equals(m.getMessage())
+ && m.getLevel() == MessageLevel.ERROR) {
+ noConstraint = true;
+ break;
}
- assertTrue(noConstraint);
- //
- // Add a constraint to policy1
- //
- Map<String, String> activeTimeRange = new HashMap<String, String>();
- activeTimeRange.put("start", "00:00:00-05:00");
- activeTimeRange.put("end", "23:59:59-05:00");
- List<String> blacklist = new LinkedList<String>();
- blacklist.add("eNodeB_common_id1");
- blacklist.add("eNodeB_common_id2");
- Map<String, String> timeWindow = new HashMap<String, String>();
- timeWindow.put("value", "10");
- timeWindow.put("units", "minute");
- Constraint cons = new Constraint(5, timeWindow, activeTimeRange, blacklist);
- builder = builder.addLimitConstraint(policy1.getId(), cons);
- //
- // Add a duplicate constraint to policy1
- //
- builder = builder.addLimitConstraint(policy1.getId(), cons);
- //
- // Assert there are duplicate constraints associated with the only guard policy
- //
- results = builder.buildSpecification();
- boolean duplicateConstraint = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage().equals("Guard policy guardpolicy1 has duplicate limit constraints")
- && m.getLevel() == MessageLevel.WARNING) {
- duplicateConstraint = true;
- break;
- }
+ }
+ assertTrue(noConstraint);
+ //
+ // Add a constraint to policy1
+ //
+ Map<String, String> activeTimeRange = new HashMap<>();
+ activeTimeRange.put("start", "00:00:00-05:00");
+ activeTimeRange.put("end", "23:59:59-05:00");
+ List<String> blacklist = new LinkedList<>();
+ blacklist.add("eNodeB_common_id1");
+ blacklist.add("eNodeB_common_id2");
+ Map<String, String> timeWindow = new HashMap<>();
+ timeWindow.put("value", "10");
+ timeWindow.put("units", "minute");
+ Constraint cons = new Constraint(5, timeWindow, activeTimeRange, blacklist);
+ builder = builder.addLimitConstraint(policy1.getId(), cons);
+ //
+ // Add a duplicate constraint to policy1
+ //
+ builder = builder.addLimitConstraint(policy1.getId(), cons);
+ //
+ // Assert there are duplicate constraints associated with the only guard policy
+ //
+ results = builder.buildSpecification();
+ boolean duplicateConstraint = false;
+ for (Message m : results.getMessages()) {
+ if ("Guard policy guardpolicy1 has duplicate limit constraints".equals(m.getMessage())
+ && m.getLevel() == MessageLevel.WARNING) {
+ duplicateConstraint = true;
+ break;
}
- assertTrue(duplicateConstraint);
- //
- // Remove the duplicate constraint
- //
- builder = builder.removeLimitConstraint(policy1.getId(), cons);
- //
- // Add a duplicate guard policy
- //
- builder = builder.addGuardPolicy(policy1);
- builder = builder.addLimitConstraint(policy1.getId(), cons);
- //
- // Assert there are duplicate guard policies
- //
- results = builder.buildSpecification();
- boolean duplicateGuardPolicy = false;
- for (Message m : results.getMessages()) {
- if (m.getMessage().equals("There are duplicate guard policies")
- && m.getLevel() == MessageLevel.WARNING) {
- duplicateGuardPolicy = true;
- break;
- }
+ }
+ assertTrue(duplicateConstraint);
+ //
+ // Remove the duplicate constraint
+ //
+ builder = builder.removeLimitConstraint(policy1.getId(), cons);
+ //
+ // Add a duplicate guard policy
+ //
+ builder = builder.addGuardPolicy(policy1);
+ builder = builder.addLimitConstraint(policy1.getId(), cons);
+ //
+ // Assert there are duplicate guard policies
+ //
+ results = builder.buildSpecification();
+ boolean duplicateGuardPolicy = false;
+ for (Message m : results.getMessages()) {
+ if ("There are duplicate guard policies".equals(m.getMessage())
+ && m.getLevel() == MessageLevel.WARNING) {
+ duplicateGuardPolicy = true;
+ break;
}
- assertTrue(duplicateGuardPolicy);
- //
- // Remove the duplicate guard policy
- //
- builder = builder.removeGuardPolicy(policy1);
- //
- // Assert there are no Error/Warning message
- //
- results = builder.buildSpecification();
- assertTrue(results.getMessages().size() == 1);
- //
- } catch (BuilderException e) {
- fail(e.getMessage());
}
+ assertTrue(duplicateGuardPolicy);
+ //
+ // Remove the duplicate guard policy
+ //
+ builder = builder.removeGuardPolicy(policy1);
+ //
+ // Assert there are no Error/Warning message
+ //
+ results = builder.buildSpecification();
+ assertTrue(results.getMessages().size() == 1);
}
-
+
@Test
- public void test1() {
+ public void test1() throws Exception {
this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml");
}
-
+
@Test
- public void test2() {
+ public void test2() throws Exception {
this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml");
}
-
+
/**
* Do the actual test.
- *
+ *
* @param testFile input test file
+ * @throws Exception if an error occurs
*/
- public void test(String testFile) {
+ public void test(String testFile) throws Exception {
try (InputStream is = new FileInputStream(new File(testFile))) {
//
// Read the yaml into our Java Object
@@ -189,7 +181,7 @@ public class ControlLoopGuardBuilderTest {
//
// Now we're going to try to use the builder to build this.
//
- ControlLoopGuardBuilder builder =
+ ControlLoopGuardBuilder builder =
ControlLoopGuardBuilder.Factory.buildControlLoopGuard(guardTobuild.getGuard());
//
// Add guard policy
@@ -206,13 +198,6 @@ public class ControlLoopGuardBuilderTest {
// Print out the specification
//
logger.debug(results.getSpecification());
- //
- } catch (FileNotFoundException e) {
- fail(e.getLocalizedMessage());
- } catch (IOException e) {
- fail(e.getLocalizedMessage());
- } catch (BuilderException e) {
- fail(e.getLocalizedMessage());
}
}
}
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java
index 01d6eb1fe..d90f5418d 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* policy-yaml unit test
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -25,15 +25,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
-
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,14 +41,14 @@ import org.yaml.snakeyaml.constructor.Constructor;
public class ControlLoopGuardTest {
private static final Logger logger = LoggerFactory.getLogger(ControlLoopGuardTest.class);
-
- @Test
- public void testGuardvdns() {
+
+ @Test
+ public void testGuardvdns() throws Exception {
this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml");
}
- @Test
- public void testGuardvusp() {
+ @Test
+ public void testGuardvusp() throws Exception {
this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml");
}
@@ -122,10 +118,11 @@ public class ControlLoopGuardTest {
/**
* Does the actual test.
- *
+ *
* @param testFile input file
+ * @throws Exception if an error occurs
*/
- public void test(String testFile) {
+ public void test(String testFile) throws Exception {
try (InputStream is = new FileInputStream(new File(testFile))) {
//
// Read the yaml into our Java Object
@@ -151,15 +148,8 @@ public class ControlLoopGuardTest {
dump(newObject);
assertNotNull(newObject);
assertTrue(newObject instanceof ControlLoopGuard);
- //
- // Have to comment it out tentatively since it causes junit to fail.
- // Seems we cannot use assertEquals here. Need advice.
- //
- //assertEquals(newObject, obj);
- } catch (FileNotFoundException e) {
- fail(e.getLocalizedMessage());
- } catch (IOException e) {
- fail(e.getLocalizedMessage());
+
+ assertEquals(obj, newObject);
}
}
diff --git a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java
index a8d183c8c..7599dcf31 100644
--- a/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java
+++ b/models-interactions/model-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/GuardPolicyTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -33,6 +33,10 @@ import org.junit.Test;
public class GuardPolicyTest {
+ private static final String GUARD_DESCRIPTION = "guard description";
+ private static final String GUARD_ID = "guard id";
+ private static final String GUARD_NAME = "guard name";
+
@Test
public void testConstructor() {
GuardPolicy guardPolicy = new GuardPolicy();
@@ -46,7 +50,7 @@ public class GuardPolicyTest {
@Test
public void testConstructorString() {
- String id = "guard id";
+ String id = GUARD_ID;
GuardPolicy guardPolicy = new GuardPolicy(id);
assertEquals(id, guardPolicy.getId());
@@ -58,9 +62,9 @@ public class GuardPolicyTest {
@Test
public void testConstructorStringStringStringMatchParameters() {
- String id = "guard id";
- String name = "guard name";
- String description = "guard description";
+ String id = GUARD_ID;
+ String name = GUARD_NAME;
+ String description = GUARD_DESCRIPTION;
MatchParameters matchParameters = new MatchParameters();
List<Constraint> limitConstraints = new LinkedList<>();
limitConstraints.add(new Constraint());
@@ -75,7 +79,7 @@ public class GuardPolicyTest {
@Test
public void testConstructorStringMatchParametersList() {
- String name = "guard name";
+ String name = GUARD_NAME;
MatchParameters matchParameters = new MatchParameters();
List<Constraint> limitConstraints = new LinkedList<>();
limitConstraints.add(new Constraint());
@@ -90,8 +94,8 @@ public class GuardPolicyTest {
@Test
public void testConstructorStringStringMatchParametersList() {
- String name = "guard name";
- String description = "guard description";
+ String name = GUARD_NAME;
+ String description = GUARD_DESCRIPTION;
MatchParameters matchParameters = new MatchParameters();
List<Constraint> limitConstraints = new LinkedList<>();
limitConstraints.add(new Constraint());
@@ -106,9 +110,9 @@ public class GuardPolicyTest {
@Test
public void testConstructorStringStringStringMatchParametersList() {
- String id = "guard id";
- String name = "guard name";
- String description = "guard description";
+ String id = GUARD_ID;
+ String name = GUARD_NAME;
+ String description = GUARD_DESCRIPTION;
MatchParameters matchParameters = new MatchParameters();
List<Constraint> limitConstraints = new LinkedList<>();
limitConstraints.add(new Constraint());
@@ -123,9 +127,9 @@ public class GuardPolicyTest {
@Test
public void testConstructorGuardPolicy() {
- String id = "guard id";
- String name = "guard name";
- String description = "guard description";
+ String id = GUARD_ID;
+ String name = GUARD_NAME;
+ String description = GUARD_DESCRIPTION;
MatchParameters matchParameters = new MatchParameters();
List<Constraint> limitConstraints = new LinkedList<>();
limitConstraints.add(new Constraint());
@@ -143,7 +147,7 @@ public class GuardPolicyTest {
@Test
public void testSetAndGetId() {
- String id = "guard id";
+ String id = GUARD_ID;
GuardPolicy guardPolicy = new GuardPolicy();
guardPolicy.setId(id);
assertEquals(id, guardPolicy.getId());
@@ -151,7 +155,7 @@ public class GuardPolicyTest {
@Test
public void testSetAndGetName() {
- String name = "guard name";
+ String name = GUARD_NAME;
GuardPolicy guardPolicy = new GuardPolicy();
guardPolicy.setName(name);
assertEquals(name, guardPolicy.getName());
@@ -159,7 +163,7 @@ public class GuardPolicyTest {
@Test
public void testSetAndGetDescription() {
- String description = "guard description";
+ String description = GUARD_DESCRIPTION;
GuardPolicy guardPolicy = new GuardPolicy();
guardPolicy.setDescription(description);
assertEquals(description, guardPolicy.getDescription());
@@ -187,7 +191,7 @@ public class GuardPolicyTest {
GuardPolicy guardPolicy = new GuardPolicy();
assertFalse(guardPolicy.isValid());
- guardPolicy.setName("guard name");
+ guardPolicy.setName(GUARD_NAME);
assertTrue(guardPolicy.isValid());
guardPolicy.setId(null);
@@ -196,9 +200,9 @@ public class GuardPolicyTest {
@Test
public void testToString() {
- String id = "guard id";
- String name = "guard name";
- String description = "guard description";
+ String id = GUARD_ID;
+ String name = GUARD_NAME;
+ String description = GUARD_DESCRIPTION;
MatchParameters matchParameters = new MatchParameters();
List<Constraint> limitConstraints = new LinkedList<>();
limitConstraints.add(new Constraint());
@@ -212,9 +216,9 @@ public class GuardPolicyTest {
@Test
public void testEquals() {
- final String id = "guard id";
- final String name = "guard name";
- final String description = "guard description";
+ final String id = GUARD_ID;
+ final String name = GUARD_NAME;
+ final String description = GUARD_DESCRIPTION;
GuardPolicy guardPolicy1 = new GuardPolicy(id);
GuardPolicy guardPolicy2 = new GuardPolicy();
assertFalse(guardPolicy1.equals(guardPolicy2));
diff --git a/models-interactions/model-yaml/src/test/resources/v1.0.0/test_evil.yaml b/models-interactions/model-yaml/src/test/resources/v1.0.0/test_evil.yaml
index d6127fe96..499f2ca28 100644
--- a/models-interactions/model-yaml/src/test/resources/v1.0.0/test_evil.yaml
+++ b/models-interactions/model-yaml/src/test/resources/v1.0.0/test_evil.yaml
@@ -1,4 +1,4 @@
-# Copyright 2018 AT&T Intellectual Property. All rights reserved
+# Copyright 2018-2019 AT&T Intellectual Property. All rights reserved
# Modifications Copyright (C) 2019 Nordix Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,7 +21,7 @@ controlLoop:
- resourceName: Bar VNF
resourceType: VF
trigger_policy: unique-policy-id-1-restart
- timeout: 1200
+ timeout: NOT_A_NUMBER
policies:
- id: unique-policy-id-1-restart
diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java
index efdf5f2c8..9dafc411c 100644
--- a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java
+++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java
@@ -96,7 +96,7 @@ public class PdpProvider {
throws PfModelException {
for (PdpGroup pdpGroup : pdpGroups) {
- JpaPdpGroup jpaPdpGroup = new JpaPdpGroup();;
+ JpaPdpGroup jpaPdpGroup = new JpaPdpGroup();
jpaPdpGroup.fromAuthorative(pdpGroup);
PfValidationResult validationResult = jpaPdpGroup.validate(new PfValidationResult());
@@ -133,7 +133,7 @@ public class PdpProvider {
throws PfModelException {
for (PdpGroup pdpGroup : pdpGroups) {
- JpaPdpGroup jpaPdpGroup = new JpaPdpGroup();;
+ JpaPdpGroup jpaPdpGroup = new JpaPdpGroup();
jpaPdpGroup.fromAuthorative(pdpGroup);
PfValidationResult validationResult = jpaPdpGroup.validate(new PfValidationResult());
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java
index 89ee5b90d..808bfe7d4 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -42,6 +43,20 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifi
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class PdpGroupFilterTest {
+ private static final String POLICY_TYPE3 = "policy.type.3";
+ private static final String POLICY_TYPE2 = "policy.type.2";
+ private static final String POLICY_TYPE1 = "policy.type.1";
+ private static final String POLICY_TYPE0 = "policy.type.0";
+ private static final String POLICY3 = "Policy3";
+ private static final String POLICY2 = "Policy2";
+ private static final String POLICY1 = "Policy1";
+ private static final String POLICY0 = "Policy0";
+ private static final String NON_EXISTANT = "Nonexistant";
+ private static final String VERSION9 = "9.9.9";
+ private static final String VERSION7 = "7.8.9";
+ private static final String VERSION4 = "4.5.6";
+ private static final String VERSION1 = "1.2.3";
+ private static final String VERSION0 = "0.1.2";
private List<PdpGroup> pdpGroupList;
/**
@@ -161,43 +176,43 @@ public class PdpGroupFilterTest {
public void testFilterPolicyType() {
List<ToscaPolicyTypeIdentifier> identifierList = new ArrayList<>();
- identifierList.add(new ToscaPolicyTypeIdentifier("Nonexistant", "1.2.3"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(NON_EXISTANT, VERSION1));
PdpGroupFilter filter =
PdpGroupFilter.builder().policyTypeList(identifierList).build();
List<PdpGroup> filteredList = filter.filter(pdpGroupList);
assertEquals(0, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.0", "1.2.3"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE0, VERSION1));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(4, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.1", "4.5.6"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE1, VERSION4));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(4, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.2", "7.8.9"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE2, VERSION7));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(2, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.3", "0.1.2"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE3, VERSION0));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(2, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("Nonexistant", "1.2.3"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.0", "9.9.9"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.0", "1.2.3"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.1", "4.5.6"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.2", "7.8.9"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.3", "0.1.2"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(NON_EXISTANT, VERSION1));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE0, VERSION9));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE0, VERSION1));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE1, VERSION4));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE2, VERSION7));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE3, VERSION0));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(5, filteredList.size());
@@ -207,30 +222,30 @@ public class PdpGroupFilterTest {
assertEquals(0, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.0", "1.2.3"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE0, VERSION1));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).matchPolicyTypesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(2, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.0", "1.2.3"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.1", "4.5.6"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.2", "7.8.9"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE0, VERSION1));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE1, VERSION4));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE2, VERSION7));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).matchPolicyTypesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.0", "1.2.3"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.1", "4.5.6"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.3", "0.1.2"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE0, VERSION1));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE1, VERSION4));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE3, VERSION0));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).matchPolicyTypesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.1", "4.5.6"));
- identifierList.add(new ToscaPolicyTypeIdentifier("policy.type.3", "0.1.2"));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE1, VERSION4));
+ identifierList.add(new ToscaPolicyTypeIdentifier(POLICY_TYPE3, VERSION0));
filter = PdpGroupFilter.builder().policyTypeList(identifierList).matchPolicyTypesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
@@ -240,49 +255,49 @@ public class PdpGroupFilterTest {
public void testFilterPolicy() {
List<ToscaPolicyIdentifier> identifierList = new ArrayList<>();
- identifierList.add(new ToscaPolicyIdentifier("Nonexistant", "1.2.3"));
+ identifierList.add(new ToscaPolicyIdentifier(NON_EXISTANT, VERSION1));
PdpGroupFilter filter =
PdpGroupFilter.builder().policyList(identifierList).build();
List<PdpGroup> filteredList = filter.filter(pdpGroupList);
assertEquals(0, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy0", "9.9.9"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY0, VERSION9));
filter = PdpGroupFilter.builder().policyList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(0, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy0", "4.5.6"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY0, VERSION4));
filter = PdpGroupFilter.builder().policyList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(4, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy1", "4.5.6"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY1, VERSION4));
filter = PdpGroupFilter.builder().policyList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy2", "4.5.6"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY2, VERSION4));
filter = PdpGroupFilter.builder().policyList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(2, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy3", "1.2.3"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY3, VERSION1));
filter = PdpGroupFilter.builder().policyList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Nonexistant", "1.2.3"));
- identifierList.add(new ToscaPolicyIdentifier("Policy0", "9.9.9"));
- identifierList.add(new ToscaPolicyIdentifier("Policy0", "4.5.6"));
- identifierList.add(new ToscaPolicyIdentifier("Policy1", "4.5.6"));
- identifierList.add(new ToscaPolicyIdentifier("Policy2", "4.5.6"));
- identifierList.add(new ToscaPolicyIdentifier("Policy3", "1.2.3"));
+ identifierList.add(new ToscaPolicyIdentifier(NON_EXISTANT, VERSION1));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY0, VERSION9));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY0, VERSION4));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY1, VERSION4));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY2, VERSION4));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY3, VERSION1));
filter = PdpGroupFilter.builder().policyList(identifierList).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(5, filteredList.size());
@@ -292,27 +307,27 @@ public class PdpGroupFilterTest {
assertEquals(0, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy0", "4.5.6"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY0, VERSION4));
filter = PdpGroupFilter.builder().policyList(identifierList).matchPoliciesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(3, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy0", "4.5.6"));
- identifierList.add(new ToscaPolicyIdentifier("Policy1", "4.5.6"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY0, VERSION4));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY1, VERSION4));
filter = PdpGroupFilter.builder().policyList(identifierList).matchPoliciesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy2", "4.5.6"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY2, VERSION4));
filter = PdpGroupFilter.builder().policyList(identifierList).matchPoliciesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
identifierList.clear();
- identifierList.add(new ToscaPolicyIdentifier("Policy2", "4.5.6"));
- identifierList.add(new ToscaPolicyIdentifier("Policy3", "1.2.3"));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY2, VERSION4));
+ identifierList.add(new ToscaPolicyIdentifier(POLICY3, VERSION1));
filter = PdpGroupFilter.builder().policyList(identifierList).matchPoliciesExactly(true).build();
filteredList = filter.filter(pdpGroupList);
assertEquals(1, filteredList.size());
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java
index a717dc2d8..a282b7dba 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java
@@ -43,6 +43,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifi
* Test methods not tested by {@link ModelsTest}.
*/
public class PdpGroupTest {
+ private static final String VERSION = "1.2.3";
private static final String NAME = "my-name";
private static final String PDP_TYPE1 = "type-1";
private static final String PDP_TYPE2 = "type-2";
@@ -61,7 +62,7 @@ public class PdpGroupTest {
// verify with all values
orig.setDescription("my-descript");
orig.setName(NAME);
- orig.setVersion("1.2.3");
+ orig.setVersion(VERSION);
orig.setDescription("my-description");
orig.setPdpGroupState(PdpState.SAFE);
@@ -100,11 +101,11 @@ public class PdpGroupTest {
public void testCompareTo() {
PdpGroup pdpGroup0 = new PdpGroup();
pdpGroup0.setName("Name0");
- pdpGroup0.setVersion("1.2.3");
+ pdpGroup0.setVersion(VERSION);
PdpGroup pdpGroup1 = new PdpGroup();
pdpGroup1.setName("Name0");
- pdpGroup1.setVersion("1.2.3");
+ pdpGroup1.setVersion(VERSION);
assertEquals(0, pdpGroup0.compareTo(pdpGroup1));
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java
index 10f31312c..9047a7ae1 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java
@@ -30,6 +30,7 @@ import org.junit.Test;
import org.onap.policy.models.pdp.enums.PdpMessageType;
public class PdpMessageTest {
+ private static final String PDP_GROUP_STRING = " pdp group ";
private static final String PDP_NAME = "pdpA";
private static final String PDP_GROUP = "groupA";
private static final String PDP_SUBGROUP = "subgroupA";
@@ -67,7 +68,7 @@ public class PdpMessageTest {
for (String pdpGroup : new String[] {null, PDP_GROUP, DIFFERENT}) {
for (String pdpSubgroup : new String[] {null, PDP_SUBGROUP, DIFFERENT}) {
- assertTrue("name msg " + message + " pdp group " + pdpGroup + "/" + pdpSubgroup,
+ assertTrue("name msg " + message + PDP_GROUP_STRING + pdpGroup + "/" + pdpSubgroup,
message.appliesTo(PDP_NAME, pdpGroup, pdpSubgroup));
}
}
@@ -83,7 +84,7 @@ public class PdpMessageTest {
for (String pdpGroup : new String[] {null, PDP_GROUP, DIFFERENT}) {
for (String pdpSubgroup : new String[] {null, PDP_SUBGROUP, DIFFERENT}) {
- assertFalse("name msg " + message + " pdp group " + pdpGroup + "/" + pdpSubgroup,
+ assertFalse("name msg " + message + PDP_GROUP_STRING + pdpGroup + "/" + pdpSubgroup,
message.appliesTo(DIFFERENT, pdpGroup, pdpSubgroup));
}
}
@@ -110,7 +111,7 @@ public class PdpMessageTest {
message = makeMessage(null, msgGroup, msgSubgroup);
for (String pdpGroup : new String[] {null, DIFFERENT}) {
- assertFalse("group msg " + message + " pdp group " + pdpGroup,
+ assertFalse("group msg " + message + PDP_GROUP_STRING + pdpGroup,
message.appliesTo(PDP_NAME, pdpGroup, PDP_SUBGROUP));
}
}
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageUtils.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageUtils.java
index ee7e15b6a..a308ab036 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageUtils.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageUtils.java
@@ -25,6 +25,10 @@ package org.onap.policy.models.pdp.concepts;
*/
public class PdpMessageUtils {
+ private PdpMessageUtils() {
+
+ }
+
public static String removeVariableFields(String text) {
return text.replaceAll("requestId=[^,]*", "requestId=xxx").replaceAll("timestampMs=[^,]*", "timestampMs=nnn");
}
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java
index c0545fa36..a2f502bcc 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -47,6 +48,10 @@ import org.onap.policy.models.pdp.testconcepts.DummyJpaPdpSubgroupChild;
*/
public class JpaPdpGroupTest {
+ private static final String NULL_KEY_ERROR = "key is marked @NonNull but is null";
+ private static final String PDP_GROUP0 = "PDPGroup0";
+ private static final String VERSION = "1.0.0";
+
@Test
public void testJpaPdpGroup() {
assertThatThrownBy(() -> {
@@ -55,7 +60,7 @@ public class JpaPdpGroupTest {
assertThatThrownBy(() -> {
new JpaPdpGroup((PfConceptKey) null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpGroup((PdpGroup) null);
@@ -67,7 +72,7 @@ public class JpaPdpGroupTest {
assertThatThrownBy(() -> {
new JpaPdpGroup(null, null, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpGroup(new PfConceptKey(), null, null);
@@ -79,31 +84,31 @@ public class JpaPdpGroupTest {
assertThatThrownBy(() -> {
new JpaPdpGroup(null, PdpState.PASSIVE, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpGroup(null, PdpState.PASSIVE, new ArrayList<>());
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpGroup(null, null, new ArrayList<>());
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertNotNull(new JpaPdpGroup((new PfConceptKey())));
assertNotNull(new JpaPdpGroup((new JpaPdpGroup())));
PdpGroup testPdpGroup = new PdpGroup();
- testPdpGroup.setName("PDPGroup0");
+ testPdpGroup.setName(PDP_GROUP0);
testPdpGroup.setPdpSubgroups(new ArrayList<>());
JpaPdpGroup testJpaPdpGroup = new JpaPdpGroup();
testJpaPdpGroup.setKey(null);
testJpaPdpGroup.setKey(new PfConceptKey());
- testPdpGroup.setVersion("1.0.0");
+ testPdpGroup.setVersion(VERSION);
testJpaPdpGroup.fromAuthorative(testPdpGroup);
- assertEquals("PDPGroup0", testJpaPdpGroup.getKey().getName());
+ assertEquals(PDP_GROUP0, testJpaPdpGroup.getKey().getName());
testJpaPdpGroup.setKey(PfConceptKey.getNullKey());
testJpaPdpGroup.fromAuthorative(testPdpGroup);
@@ -111,19 +116,19 @@ public class JpaPdpGroupTest {
testJpaPdpGroup.fromAuthorative(null);
}).hasMessage("pdpGroup is marked @NonNull but is null");
- testJpaPdpGroup.setKey(new PfConceptKey("PDPGroup0", "1.0.0"));
+ testJpaPdpGroup.setKey(new PfConceptKey(PDP_GROUP0, VERSION));
testJpaPdpGroup.fromAuthorative(testPdpGroup);
assertThatThrownBy(() -> {
testJpaPdpGroup.copyTo(null);
}).hasMessage("target is marked @NonNull but is null");
- assertEquals("PDPGroup0", testJpaPdpGroup.getKey().getName());
- assertEquals("PDPGroup0", new JpaPdpGroup(testPdpGroup).getKey().getName());
- assertEquals("PDPGroup0", ((PfConceptKey) new JpaPdpGroup(testPdpGroup).getKeys().get(0)).getName());
+ assertEquals(PDP_GROUP0, testJpaPdpGroup.getKey().getName());
+ assertEquals(PDP_GROUP0, new JpaPdpGroup(testPdpGroup).getKey().getName());
+ assertEquals(PDP_GROUP0, ((PfConceptKey) new JpaPdpGroup(testPdpGroup).getKeys().get(0)).getName());
testJpaPdpGroup.clean();
- assertEquals("PDPGroup0", testJpaPdpGroup.getKey().getName());
+ assertEquals(PDP_GROUP0, testJpaPdpGroup.getKey().getName());
assertThatThrownBy(() -> {
testJpaPdpGroup.validate(null);
@@ -135,7 +140,7 @@ public class JpaPdpGroupTest {
testJpaPdpGroup.setKey(PfConceptKey.getNullKey());
assertFalse(testJpaPdpGroup.validate(new PfValidationResult()).isOk());
- testJpaPdpGroup.setKey(new PfConceptKey("PdpGroup0", "1.0.0"));
+ testJpaPdpGroup.setKey(new PfConceptKey("PdpGroup0", VERSION));
assertTrue(testJpaPdpGroup.validate(new PfValidationResult()).isOk());
testJpaPdpGroup.setDescription(" ");
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpSubGroupTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpSubGroupTest.java
index d066d9be7..981f40f06 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpSubGroupTest.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpSubGroupTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -46,6 +47,9 @@ import org.onap.policy.models.pdp.testconcepts.DummyJpaPdpSubgroupChild;
*/
public class JpaPdpSubGroupTest {
+ private static final String NULL_KEY_ERROR = "key is marked @NonNull but is null";
+ private static final String PDP_A = "PDP-A";
+
@Test
public void testJpaPdpSubGroup() {
assertThatThrownBy(() -> {
@@ -54,7 +58,7 @@ public class JpaPdpSubGroupTest {
assertThatThrownBy(() -> {
new JpaPdpSubGroup((PfReferenceKey) null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup((PdpSubGroup) null);
@@ -62,7 +66,7 @@ public class JpaPdpSubGroupTest {
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, null, null, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup(new PfReferenceKey(), null, null, null);
@@ -74,19 +78,19 @@ public class JpaPdpSubGroupTest {
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, new ArrayList<>(), null, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, new ArrayList<>(), new ArrayList<>(), null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, null, new ArrayList<>(), null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, null, null, new ArrayList<>());
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup(new PfReferenceKey(), null, null, new ArrayList<>());
@@ -98,24 +102,24 @@ public class JpaPdpSubGroupTest {
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, new ArrayList<>(), null, new ArrayList<>());
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdpSubGroup(null, null, new ArrayList<>(), null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertNotNull(new JpaPdpSubGroup((new PfReferenceKey())));
PdpSubGroup testPdpSubgroup = new PdpSubGroup();
- testPdpSubgroup.setPdpType("PDP-A");
+ testPdpSubgroup.setPdpType(PDP_A);
JpaPdpSubGroup testJpaPdpSubGroup = new JpaPdpSubGroup();
testJpaPdpSubGroup.setKey(null);
testJpaPdpSubGroup.fromAuthorative(testPdpSubgroup);
- assertEquals("PDP-A", testJpaPdpSubGroup.getKey().getLocalName());
+ assertEquals(PDP_A, testJpaPdpSubGroup.getKey().getLocalName());
testJpaPdpSubGroup.setKey(PfReferenceKey.getNullKey());
testJpaPdpSubGroup.fromAuthorative(testPdpSubgroup);
@@ -127,12 +131,12 @@ public class JpaPdpSubGroupTest {
testJpaPdpSubGroup.copyTo(null);
}).hasMessage("target is marked @NonNull but is null");
- assertEquals("PDP-A", testJpaPdpSubGroup.getKey().getLocalName());
- assertEquals("PDP-A", new JpaPdpSubGroup(testPdpSubgroup).getKey().getLocalName());
- assertEquals("PDP-A", ((PfReferenceKey) new JpaPdpSubGroup(testPdpSubgroup).getKeys().get(0)).getLocalName());
+ assertEquals(PDP_A, testJpaPdpSubGroup.getKey().getLocalName());
+ assertEquals(PDP_A, new JpaPdpSubGroup(testPdpSubgroup).getKey().getLocalName());
+ assertEquals(PDP_A, ((PfReferenceKey) new JpaPdpSubGroup(testPdpSubgroup).getKeys().get(0)).getLocalName());
testJpaPdpSubGroup.clean();
- assertEquals("PDP-A", testJpaPdpSubGroup.getKey().getLocalName());
+ assertEquals(PDP_A, testJpaPdpSubGroup.getKey().getLocalName());
assertThatThrownBy(() -> {
testJpaPdpSubGroup.validate(null);
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java
index ebdf31c2f..5ffba10b9 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -33,7 +34,6 @@ import org.onap.policy.models.base.PfValidationResult;
import org.onap.policy.models.pdp.concepts.Pdp;
import org.onap.policy.models.pdp.enums.PdpHealthStatus;
import org.onap.policy.models.pdp.enums.PdpState;
-import org.onap.policy.models.pdp.persistence.concepts.JpaPdp;
import org.onap.policy.models.pdp.testconcepts.DummyJpaPdpChild;
/**
@@ -43,6 +43,9 @@ import org.onap.policy.models.pdp.testconcepts.DummyJpaPdpChild;
*/
public class JpaPdpTest {
+ private static final String NULL_KEY_ERROR = "key is marked @NonNull but is null";
+ private static final String PDP1 = "ThePDP";
+
@Test
public void testJpaPdp() {
assertThatThrownBy(() -> {
@@ -51,11 +54,11 @@ public class JpaPdpTest {
assertThatThrownBy(() -> {
new JpaPdp((PfReferenceKey) null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdp(null, null, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdp(new PfReferenceKey(), null, null);
@@ -67,15 +70,15 @@ public class JpaPdpTest {
assertThatThrownBy(() -> {
new JpaPdp(null, PdpState.ACTIVE, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdp(null, PdpState.ACTIVE, PdpHealthStatus.UNKNOWN);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdp(null, null, PdpHealthStatus.UNKNOWN);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(NULL_KEY_ERROR);
assertThatThrownBy(() -> {
new JpaPdp((Pdp) null);
@@ -84,11 +87,11 @@ public class JpaPdpTest {
assertNotNull(new JpaPdp((new PfReferenceKey())));
Pdp testPdp = new Pdp();
- testPdp.setInstanceId("ThePDP");
+ testPdp.setInstanceId(PDP1);
JpaPdp testJpaPdp = new JpaPdp();
testJpaPdp.setKey(null);
testJpaPdp.fromAuthorative(testPdp);
- assertEquals("ThePDP", testJpaPdp.getKey().getLocalName());
+ assertEquals(PDP1, testJpaPdp.getKey().getLocalName());
testJpaPdp.setKey(PfReferenceKey.getNullKey());
testJpaPdp.fromAuthorative(testPdp);
@@ -100,12 +103,12 @@ public class JpaPdpTest {
testJpaPdp.copyTo(null);
}).hasMessage("target is marked @NonNull but is null");
- assertEquals("ThePDP", testJpaPdp.getKey().getLocalName());
- assertEquals("ThePDP", new JpaPdp(testPdp).getKey().getLocalName());
- assertEquals("ThePDP", ((PfReferenceKey) new JpaPdp(testPdp).getKeys().get(0)).getLocalName());
+ assertEquals(PDP1, testJpaPdp.getKey().getLocalName());
+ assertEquals(PDP1, new JpaPdp(testPdp).getKey().getLocalName());
+ assertEquals(PDP1, ((PfReferenceKey) new JpaPdp(testPdp).getKeys().get(0)).getLocalName());
testJpaPdp.clean();
- assertEquals("ThePDP", testJpaPdp.getKey().getLocalName());
+ assertEquals(PDP1, testJpaPdp.getKey().getLocalName());
testJpaPdp.setMessage(" A Message ");
testJpaPdp.clean();
diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java
index f0af69ea4..4314b81c1 100644
--- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java
+++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java
@@ -29,7 +29,6 @@ import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
-
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.junit.After;
import org.junit.Before;
@@ -49,7 +48,6 @@ import org.onap.policy.models.pdp.concepts.PdpStatistics;
import org.onap.policy.models.pdp.concepts.PdpSubGroup;
import org.onap.policy.models.pdp.enums.PdpHealthStatus;
import org.onap.policy.models.pdp.enums.PdpState;
-import org.onap.policy.models.pdp.persistence.provider.PdpProvider;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider;
@@ -99,7 +97,7 @@ public class PdpProviderTest {
}
@After
- public void teardown() throws Exception {
+ public void teardown() {
pfDao.close();
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java
index cba3fe591..bf9f92e28 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java
@@ -27,12 +27,10 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.GsonBuilder;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.utils.coder.CoderException;
@@ -49,6 +47,10 @@ import org.yaml.snakeyaml.Yaml;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class ToscaPolicyFilterTest {
+ private static final String VERSION_100 = "1.0.0";
+
+ private static final String VERSION_000 = "0.0.0";
+
// Logger for this class
private static final Logger LOGGER = LoggerFactory.getLogger(ToscaPolicyFilterTest.class);
@@ -91,22 +93,7 @@ public class ToscaPolicyFilterTest {
assertNotNull(serviceTemplate);
for (Map<String, ToscaPolicy> foundPolicyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) {
- for (Entry<String, ToscaPolicy> policyEntry : foundPolicyMap.entrySet()) {
- ToscaPolicy policy = policyEntry.getValue();
- if (policy.getName() == null) {
- policy.setName(policyEntry.getKey());
- }
-
- if (policy.getVersion() == null) {
- policy.setVersion(PfKey.NULL_KEY_VERSION);
- }
- if (policy.getTypeVersion() == null) {
- policy.setTypeVersion(PfKey.NULL_KEY_VERSION);
- }
- if (!policyList.contains(policy)) {
- policyList.add(policy);
- }
- }
+ addPolicies(foundPolicyMap);
}
}
@@ -116,6 +103,25 @@ public class ToscaPolicyFilterTest {
}
}
+ private static void addPolicies(Map<String, ToscaPolicy> foundPolicyMap) {
+ for (Entry<String, ToscaPolicy> policyEntry : foundPolicyMap.entrySet()) {
+ ToscaPolicy policy = policyEntry.getValue();
+ if (policy.getName() == null) {
+ policy.setName(policyEntry.getKey());
+ }
+
+ if (policy.getVersion() == null) {
+ policy.setVersion(PfKey.NULL_KEY_VERSION);
+ }
+ if (policy.getTypeVersion() == null) {
+ policy.setTypeVersion(PfKey.NULL_KEY_VERSION);
+ }
+ if (!policyList.contains(policy)) {
+ policyList.add(policy);
+ }
+ }
+ }
+
@Test
public void testNullList() {
ToscaPolicyFilter filter = ToscaPolicyFilter.builder().build();
@@ -139,8 +145,8 @@ public class ToscaPolicyFilterTest {
List<ToscaPolicy> filteredList = filter.filter(policyList);
assertEquals(15, filteredList.size());
- assertEquals("1.0.0", filteredList.get(7).getVersion());
- assertEquals("1.0.0", filteredList.get(12).getVersion());
+ assertEquals(VERSION_100, filteredList.get(7).getVersion());
+ assertEquals(VERSION_100, filteredList.get(12).getVersion());
assertEquals(17, policyList.size());
assertEquals(15, filteredList.size());
@@ -152,12 +158,12 @@ public class ToscaPolicyFilterTest {
assertEquals("2.0.0", filteredList.get(7).getVersion());
assertEquals("3.4.5", filteredList.get(12).getVersion());
- policyList.get(10).setVersion("1.0.0");
- policyList.get(16).setVersion("1.0.0");
+ policyList.get(10).setVersion(VERSION_100);
+ policyList.get(16).setVersion(VERSION_100);
filteredList = filter.filter(policyList);
assertEquals(15, filteredList.size());
- assertEquals("1.0.0", filteredList.get(7).getVersion());
- assertEquals("1.0.0", filteredList.get(12).getVersion());
+ assertEquals(VERSION_100, filteredList.get(7).getVersion());
+ assertEquals(VERSION_100, filteredList.get(12).getVersion());
}
@Test
@@ -174,15 +180,15 @@ public class ToscaPolicyFilterTest {
filteredList = filter.filter(policyList);
assertEquals(0, filteredList.size());
- filter = ToscaPolicyFilter.builder().version("1.0.0").build();
+ filter = ToscaPolicyFilter.builder().version(VERSION_100).build();
filteredList = filter.filter(policyList);
assertEquals(17, filteredList.size());
- filter = ToscaPolicyFilter.builder().name("OSDF_CASABLANCA.SubscriberPolicy_v1").version("1.0.0").build();
+ filter = ToscaPolicyFilter.builder().name("OSDF_CASABLANCA.SubscriberPolicy_v1").version(VERSION_100).build();
filteredList = filter.filter(policyList);
assertEquals(1, filteredList.size());
- filter = ToscaPolicyFilter.builder().name("operational.modifyconfig").version("1.0.0").build();
+ filter = ToscaPolicyFilter.builder().name("operational.modifyconfig").version(VERSION_100).build();
filteredList = filter.filter(policyList);
assertEquals(2, filteredList.size());
}
@@ -217,15 +223,17 @@ public class ToscaPolicyFilterTest {
filteredList = filter.filter(policyList);
assertEquals(0, filteredList.size());
- filter = ToscaPolicyFilter.builder().typeVersion("0.0.0").build();
+ filter = ToscaPolicyFilter.builder().typeVersion(VERSION_000).build();
filteredList = filter.filter(policyList);
assertEquals(17, filteredList.size());
- filter = ToscaPolicyFilter.builder().type("onap.policies.optimization.HpaPolicy").typeVersion("0.0.0").build();
+ filter = ToscaPolicyFilter.builder().type("onap.policies.optimization.HpaPolicy").typeVersion(VERSION_000)
+ .build();
filteredList = filter.filter(policyList);
assertEquals(1, filteredList.size());
- filter = ToscaPolicyFilter.builder().type("onap.policies.controlloop.Operational").typeVersion("0.0.0").build();
+ filter = ToscaPolicyFilter.builder().type("onap.policies.controlloop.Operational").typeVersion(VERSION_000)
+ .build();
filteredList = filter.filter(policyList);
assertEquals(4, filteredList.size());
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java
index 2ec2422a9..0b43173ad 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java
@@ -65,7 +65,7 @@ public class ToscaPolicyIdentifierOptVersionTest extends ToscaIdentifierTestBase
}
@Test
- public void testCopyToscaPolicyIdentifierConstructor() throws Exception {
+ public void testCopyToscaPolicyIdentifierConstructor() {
assertThatThrownBy(() -> new ToscaPolicyIdentifierOptVersion((ToscaPolicyIdentifier) null))
.isInstanceOf(NullPointerException.class);
@@ -85,6 +85,7 @@ public class ToscaPolicyIdentifierOptVersionTest extends ToscaIdentifierTestBase
}
@Test
+ @Override
public void testCompareTo() throws Exception {
super.testCompareTo();
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java
index f31abf837..cc40e2410 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java
@@ -85,6 +85,7 @@ public class ToscaPolicyIdentifierTest extends ToscaIdentifierTestBase<ToscaPoli
}
@Test
+ @Override
public void testCompareTo() throws Exception {
super.testCompareTo();
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeFilterTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeFilterTest.java
index e0143e676..5fbad5559 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeFilterTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeFilterTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -48,6 +49,10 @@ import org.yaml.snakeyaml.Yaml;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class ToscaPolicyTypeFilterTest {
+ private static final String VERSION_100 = "1.0.0";
+
+ private static final String VERSION_000 = "0.0.0";
+
// Logger for this class
private static final Logger LOGGER = LoggerFactory.getLogger(ToscaPolicyTypeFilterTest.class);
@@ -86,18 +91,7 @@ public class ToscaPolicyTypeFilterTest {
assertNotNull(serviceTemplate);
for (Map<String, ToscaPolicyType> foundPolicyTypeMap : serviceTemplate.getPolicyTypes()) {
- for (Entry<String, ToscaPolicyType> policyTypeEntry : foundPolicyTypeMap.entrySet()) {
- ToscaPolicyType policyType = policyTypeEntry.getValue();
- if (policyType.getName() == null) {
- policyType.setName(policyTypeEntry.getKey());
- }
- if (policyType.getVersion() == null) {
- policyType.setVersion(PfKey.NULL_KEY_VERSION);
- }
- if (!typeList.contains(policyType)) {
- typeList.add(policyType);
- }
- }
+ addPolicyTypes(foundPolicyTypeMap);
}
}
@@ -106,6 +100,21 @@ public class ToscaPolicyTypeFilterTest {
}
}
+ private static void addPolicyTypes(Map<String, ToscaPolicyType> foundPolicyTypeMap) {
+ for (Entry<String, ToscaPolicyType> policyTypeEntry : foundPolicyTypeMap.entrySet()) {
+ ToscaPolicyType policyType = policyTypeEntry.getValue();
+ if (policyType.getName() == null) {
+ policyType.setName(policyTypeEntry.getKey());
+ }
+ if (policyType.getVersion() == null) {
+ policyType.setVersion(PfKey.NULL_KEY_VERSION);
+ }
+ if (!typeList.contains(policyType)) {
+ typeList.add(policyType);
+ }
+ }
+ }
+
@Test
public void testNullList() {
ToscaPolicyTypeFilter filter = ToscaPolicyTypeFilter.builder().build();
@@ -130,20 +139,20 @@ public class ToscaPolicyTypeFilterTest {
List<ToscaPolicyType> filteredList = filter.filter(typeList);
assertEquals(13, filteredList.size());
- assertEquals("1.0.0", filteredList.get(0).getVersion());
- assertEquals("0.0.0", filteredList.get(4).getVersion());
+ assertEquals(VERSION_100, filteredList.get(0).getVersion());
+ assertEquals(VERSION_000, filteredList.get(4).getVersion());
typeList.get(12).setVersion("2.0.0");
filteredList = filter.filter(typeList);
assertEquals(13, filteredList.size());
assertEquals("2.0.0", filteredList.get(0).getVersion());
- assertEquals("0.0.0", filteredList.get(4).getVersion());
+ assertEquals(VERSION_000, filteredList.get(4).getVersion());
- typeList.get(12).setVersion("1.0.0");
+ typeList.get(12).setVersion(VERSION_100);
filteredList = filter.filter(typeList);
assertEquals(13, filteredList.size());
- assertEquals("1.0.0", filteredList.get(0).getVersion());
- assertEquals("0.0.0", filteredList.get(4).getVersion());
+ assertEquals(VERSION_100, filteredList.get(0).getVersion());
+ assertEquals(VERSION_000, filteredList.get(4).getVersion());
}
@Test
@@ -160,11 +169,12 @@ public class ToscaPolicyTypeFilterTest {
filteredList = filter.filter(typeList);
assertEquals(0, filteredList.size());
- filter = ToscaPolicyTypeFilter.builder().version("0.0.0").build();
+ filter = ToscaPolicyTypeFilter.builder().version(VERSION_000).build();
filteredList = filter.filter(typeList);
assertEquals(9, filteredList.size());
- filter = ToscaPolicyTypeFilter.builder().name("onap.policies.optimization.Vim_fit").version("0.0.0").build();
+ filter = ToscaPolicyTypeFilter.builder().name("onap.policies.optimization.Vim_fit").version(VERSION_000)
+ .build();
filteredList = filter.filter(typeList);
assertEquals(1, filteredList.size());
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java
index e440dd6da..a5e0431b2 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java
@@ -85,6 +85,7 @@ public class ToscaPolicyTypeIdentifierTest extends ToscaIdentifierTestBase<Tosca
}
@Test
+ @Override
public void testCompareTo() throws Exception {
super.testCompareTo();
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java
index 10f3b0db2..6c87d7681 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -55,6 +56,12 @@ import org.yaml.snakeyaml.Yaml;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class AuthorativeToscaProviderPolicyTest {
+ private static final String VERSION = "version";
+ private static final String VCPE_JSON = "policies/vCPE.policy.monitoring.input.tosca.json";
+ private static final String POLICY_AND_VERSION = "onap.restart.tca:1.0.0";
+ private static final String POLICY1 = "onap.restart.tca";
+ private static final String DAO_IS_NULL = "dao is marked @NonNull but is null";
+ private static final String VERSION_100 = "1.0.0";
private PfDao pfDao;
private StandardCoder standardCoder;
@@ -93,7 +100,7 @@ public class AuthorativeToscaProviderPolicyTest {
}
@After
- public void teardown() throws Exception {
+ public void teardown() {
pfDao.close();
}
@@ -101,23 +108,23 @@ public class AuthorativeToscaProviderPolicyTest {
public void testPoliciesGet() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getPolicies(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getPolicyList(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
createPolicyTypes();
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_JSON),
ToscaServiceTemplate.class);
assertNotNull(toscaServiceTemplate);
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate);
- PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0");
+ PfConceptKey policyKey = new PfConceptKey(POLICY_AND_VERSION);
ToscaPolicy beforePolicy =
toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName());
@@ -135,11 +142,11 @@ public class AuthorativeToscaProviderPolicyTest {
assertTrue(beforePolicy.getType().equals(gotPolicy.getType()));
List<ToscaPolicy> gotPolicyList =
- new AuthorativeToscaProvider().getPolicyList(pfDao, "onap.restart.tca", "1.0.0");
+ new AuthorativeToscaProvider().getPolicyList(pfDao, POLICY1, VERSION_100);
assertEquals(1, gotPolicyList.size());
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0)));
- gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, "onap.restart.tca", null);
+ gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, POLICY1, null);
assertEquals(1, gotPolicyList.size());
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0)));
@@ -147,11 +154,11 @@ public class AuthorativeToscaProviderPolicyTest {
assertEquals(1, gotPolicyList.size());
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0)));
- gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, null, "1.0.0");
+ gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, null, VERSION_100);
assertEquals(1, gotPolicyList.size());
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0)));
- gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, "Nonexistant", "1.0.0");
+ gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, "Nonexistant", VERSION_100);
assertEquals(0, gotPolicyList.size());
}
@@ -159,11 +166,11 @@ public class AuthorativeToscaProviderPolicyTest {
public void testPoliciesGetFiltered() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicies(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicies(null, ToscaPolicyFilter.builder().build());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicies(pfDao, null);
@@ -171,11 +178,11 @@ public class AuthorativeToscaProviderPolicyTest {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyList(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyList(null, ToscaPolicyFilter.builder().build());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, null);
@@ -184,14 +191,14 @@ public class AuthorativeToscaProviderPolicyTest {
createPolicyTypes();
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_JSON),
ToscaServiceTemplate.class);
assertNotNull(toscaServiceTemplate);
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate);
- PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0");
+ PfConceptKey policyKey = new PfConceptKey(POLICY_AND_VERSION);
ToscaPolicy beforePolicy =
toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName());
@@ -216,14 +223,14 @@ public class AuthorativeToscaProviderPolicyTest {
assertTrue(beforePolicy.getType().equals(gotPolicy.getType()));
gotServiceTemplate = new AuthorativeToscaProvider().getFilteredPolicies(pfDao,
- ToscaPolicyFilter.builder().name(policyKey.getName()).version("1.0.0").build());
+ ToscaPolicyFilter.builder().name(policyKey.getName()).version(VERSION_100).build());
gotPolicy = gotServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName());
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicy));
assertTrue(beforePolicy.getType().equals(gotPolicy.getType()));
List<ToscaPolicy> gotPolicyList =
- new AuthorativeToscaProvider().getPolicyList(pfDao, "onap.restart.tca", "1.0.0");
+ new AuthorativeToscaProvider().getPolicyList(pfDao, POLICY1, VERSION_100);
assertEquals(1, gotPolicyList.size());
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0)));
@@ -238,7 +245,7 @@ public class AuthorativeToscaProviderPolicyTest {
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0)));
gotPolicyList = new AuthorativeToscaProvider().getFilteredPolicyList(pfDao,
- ToscaPolicyFilter.builder().name(policyKey.getName()).version("1.0.0").build());
+ ToscaPolicyFilter.builder().name(policyKey.getName()).version(VERSION_100).build());
assertEquals(1, gotPolicyList.size());
assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0)));
}
@@ -247,11 +254,11 @@ public class AuthorativeToscaProviderPolicyTest {
public void testPolicyCreate() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicies(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicies(null, new ToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicies(pfDao, null);
@@ -260,14 +267,14 @@ public class AuthorativeToscaProviderPolicyTest {
createPolicyTypes();
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_JSON),
ToscaServiceTemplate.class);
assertNotNull(toscaServiceTemplate);
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate);
- PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0");
+ PfConceptKey policyKey = new PfConceptKey(POLICY_AND_VERSION);
ToscaPolicy beforePolicy =
toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName());
@@ -281,15 +288,15 @@ public class AuthorativeToscaProviderPolicyTest {
public void testPolicyUpdate() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicies(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().updatePolicies(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().updatePolicies(null, new ToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().updatePolicies(pfDao, null);
@@ -298,14 +305,14 @@ public class AuthorativeToscaProviderPolicyTest {
createPolicyTypes();
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_JSON),
ToscaServiceTemplate.class);
assertNotNull(toscaServiceTemplate);
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate);
- PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0");
+ PfConceptKey policyKey = new PfConceptKey(POLICY_AND_VERSION);
ToscaPolicy beforePolicy =
toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName());
@@ -327,26 +334,26 @@ public class AuthorativeToscaProviderPolicyTest {
public void testPoliciesDelete() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().deletePolicy(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
- new AuthorativeToscaProvider().deletePolicy(null, null, "version");
- }).hasMessage("dao is marked @NonNull but is null");
+ new AuthorativeToscaProvider().deletePolicy(null, null, VERSION);
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().deletePolicy(null, "name", null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
- new AuthorativeToscaProvider().deletePolicy(null, "name", "version");
- }).hasMessage("dao is marked @NonNull but is null");
+ new AuthorativeToscaProvider().deletePolicy(null, "name", VERSION);
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().deletePolicy(pfDao, null, null);
}).hasMessage("name is marked @NonNull but is null");
assertThatThrownBy(() -> {
- new AuthorativeToscaProvider().deletePolicy(pfDao, null, "version");
+ new AuthorativeToscaProvider().deletePolicy(pfDao, null, VERSION);
}).hasMessage("name is marked @NonNull but is null");
assertThatThrownBy(() -> {
@@ -356,14 +363,14 @@ public class AuthorativeToscaProviderPolicyTest {
createPolicyTypes();
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_JSON),
ToscaServiceTemplate.class);
assertNotNull(toscaServiceTemplate);
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate);
- PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0");
+ PfConceptKey policyKey = new PfConceptKey(POLICY_AND_VERSION);
ToscaPolicy beforePolicy =
toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName());
@@ -387,7 +394,7 @@ public class AuthorativeToscaProviderPolicyTest {
}
@Test
- public void testAssertPoliciesExist() throws PfModelException {
+ public void testAssertPoliciesExist() {
ToscaServiceTemplate testServiceTemplate = new ToscaServiceTemplate();
assertThatThrownBy(() -> {
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java
index 4ae56149a..c2b387952 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -26,11 +27,9 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.gson.GsonBuilder;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
-
import org.apache.commons.lang3.ObjectUtils;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.junit.After;
@@ -40,7 +39,6 @@ import org.junit.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.models.base.PfConceptKey;
-import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.dao.DaoParameters;
import org.onap.policy.models.dao.PfDao;
import org.onap.policy.models.dao.PfDaoFactory;
@@ -57,6 +55,12 @@ import org.yaml.snakeyaml.Yaml;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class AuthorativeToscaProviderPolicyTypeTest {
+ private static final String VERSION = "version";
+ private static final String POLICY_AFFINITY_VERSION0 = "onap.policies.optimization.AffinityPolicy:0.0.0";
+ private static final String POLICY_AFFINITY = "onap.policies.optimization.AffinityPolicy";
+ private static final String MISSING_POLICY_TYPES = "no policy types specified on service template";
+ private static final String DAO_IS_NULL = "dao is marked @NonNull but is null";
+ private static final String VERSION_000 = "0.0.0";
private static String yamlAsJsonString;
private PfDao pfDao;
private StandardCoder standardCoder;
@@ -111,7 +115,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
}
@After
- public void teardown() throws Exception {
+ public void teardown() {
pfDao.close();
}
@@ -119,11 +123,11 @@ public class AuthorativeToscaProviderPolicyTypeTest {
public void testPolicyTypesGet() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getPolicyTypes(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getPolicyList(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
@@ -131,7 +135,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate);
- PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0");
+ PfConceptKey policyTypeKey = new PfConceptKey(POLICY_AFFINITY_VERSION0);
ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
@@ -146,12 +150,12 @@ public class AuthorativeToscaProviderPolicyTypeTest {
assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), createdPolicyType.getDescription()));
List<ToscaPolicyType> gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao,
- "onap.policies.optimization.AffinityPolicy", "0.0.0");
+ POLICY_AFFINITY, VERSION_000);
assertEquals(1, gotPolicyTypeList.size());
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao,
- "onap.policies.optimization.AffinityPolicy", null);
+ POLICY_AFFINITY, null);
assertEquals(1, gotPolicyTypeList.size());
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
@@ -159,7 +163,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
assertEquals(2, gotPolicyTypeList.size());
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
- gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao, null, "0.0.0");
+ gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao, null, VERSION_000);
assertEquals(2, gotPolicyTypeList.size());
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
}
@@ -169,11 +173,11 @@ public class AuthorativeToscaProviderPolicyTypeTest {
public void testPolicyTypesGetFiltered() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyTypes(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyTypes(null, ToscaPolicyTypeFilter.builder().build());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, null);
@@ -181,11 +185,11 @@ public class AuthorativeToscaProviderPolicyTypeTest {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyTypeList(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyTypeList(null, ToscaPolicyTypeFilter.builder().build());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, null);
@@ -197,7 +201,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate);
- PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0");
+ PfConceptKey policyTypeKey = new PfConceptKey(POLICY_AFFINITY_VERSION0);
ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
@@ -219,14 +223,14 @@ public class AuthorativeToscaProviderPolicyTypeTest {
assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), gotPolicyType.getDescription()));
gotServiceTemplate = new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao,
- ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).version("0.0.0").build());
+ ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).version(VERSION_000).build());
gotPolicyType = gotServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName());
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), gotPolicyType.getDescription()));
List<ToscaPolicyType> gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao,
- "onap.policies.optimization.AffinityPolicy", "0.0.0");
+ POLICY_AFFINITY, VERSION_000);
assertEquals(1, gotPolicyTypeList.size());
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
@@ -241,7 +245,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
gotPolicyTypeList = new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao,
- ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).version("0.0.0").build());
+ ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).version(VERSION_000).build());
assertEquals(1, gotPolicyTypeList.size());
assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName()));
@@ -255,11 +259,11 @@ public class AuthorativeToscaProviderPolicyTypeTest {
public void testPolicyTypesCreate() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicyTypes(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicyTypes(null, new ToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicyTypes(pfDao, null);
@@ -268,7 +272,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
ToscaServiceTemplate testToscaServiceTemplate = new ToscaServiceTemplate();
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicyTypes(pfDao, testToscaServiceTemplate);
- }).hasMessage("no policy types specified on service template");
+ }).hasMessage(MISSING_POLICY_TYPES);
testToscaServiceTemplate.setPolicyTypes(new ArrayList<>());
assertThatThrownBy(() -> {
@@ -281,7 +285,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate);
- PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0");
+ PfConceptKey policyTypeKey = new PfConceptKey(POLICY_AFFINITY_VERSION0);
ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
@@ -293,15 +297,15 @@ public class AuthorativeToscaProviderPolicyTypeTest {
public void testPolicyTypesUpdate() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicyTypes(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().updatePolicyTypes(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().updatePolicyTypes(null, new ToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().updatePolicyTypes(pfDao, null);
@@ -313,7 +317,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate);
- PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0");
+ PfConceptKey policyTypeKey = new PfConceptKey(POLICY_AFFINITY_VERSION0);
ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
@@ -332,26 +336,26 @@ public class AuthorativeToscaProviderPolicyTypeTest {
public void testPolicyTypesDelete() throws Exception {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().deletePolicyType(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
- new AuthorativeToscaProvider().deletePolicyType(null, null, "version");
- }).hasMessage("dao is marked @NonNull but is null");
+ new AuthorativeToscaProvider().deletePolicyType(null, null, VERSION);
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().deletePolicyType(null, "name", null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
- new AuthorativeToscaProvider().deletePolicyType(null, "name", "version");
- }).hasMessage("dao is marked @NonNull but is null");
+ new AuthorativeToscaProvider().deletePolicyType(null, "name", VERSION);
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().deletePolicyType(pfDao, null, null);
}).hasMessage("name is marked @NonNull but is null");
assertThatThrownBy(() -> {
- new AuthorativeToscaProvider().deletePolicyType(pfDao, null, "version");
+ new AuthorativeToscaProvider().deletePolicyType(pfDao, null, VERSION);
}).hasMessage("name is marked @NonNull but is null");
assertThatThrownBy(() -> {
@@ -364,7 +368,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
ToscaServiceTemplate createdServiceTemplate =
new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate);
- PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0");
+ PfConceptKey policyTypeKey = new PfConceptKey(POLICY_AFFINITY_VERSION0);
ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName());
@@ -385,7 +389,7 @@ public class AuthorativeToscaProviderPolicyTypeTest {
}
@Test
- public void testAssertPoliciesExist() throws PfModelException {
+ public void testAssertPoliciesExist() {
ToscaServiceTemplate testServiceTemplate = new ToscaServiceTemplate();
assertThatThrownBy(() -> {
@@ -394,12 +398,12 @@ public class AuthorativeToscaProviderPolicyTypeTest {
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicyTypes(pfDao, testServiceTemplate);
- }).hasMessage("no policy types specified on service template");
+ }).hasMessage(MISSING_POLICY_TYPES);
testServiceTemplate.setToscaTopologyTemplate(new ToscaTopologyTemplate());
assertThatThrownBy(() -> {
new AuthorativeToscaProvider().createPolicyTypes(pfDao, testServiceTemplate);
- }).hasMessage("no policy types specified on service template");
+ }).hasMessage(MISSING_POLICY_TYPES);
testServiceTemplate.setPolicyTypes(new ArrayList<>());
assertThatThrownBy(() -> {
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/ToscaServiceTemplateMappingTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/ToscaServiceTemplateMappingTest.java
index b44853428..82f75a721 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/ToscaServiceTemplateMappingTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/ToscaServiceTemplateMappingTest.java
@@ -25,7 +25,6 @@ package org.onap.policy.models.tosca.authorative.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
@@ -35,8 +34,6 @@ import org.onap.policy.models.base.PfValidationResult;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
/**
@@ -45,7 +42,6 @@ import org.yaml.snakeyaml.Yaml;
* @author Chenfei Gao (cgao@research.att.com)
*/
public class ToscaServiceTemplateMappingTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(ToscaServiceTemplateMappingTest.class);
private StandardCoder standardCoder;
@@ -56,51 +52,38 @@ public class ToscaServiceTemplateMappingTest {
@Test
public void testPlainToscaPolicies() throws Exception {
- try {
- String inputJson = ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json");
+ String inputJson = ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json");
- ToscaServiceTemplate plainPolicies = standardCoder.decode(inputJson, ToscaServiceTemplate.class);
- JpaToscaServiceTemplate internalPolicies = new JpaToscaServiceTemplate();
- internalPolicies.fromAuthorative(plainPolicies);
+ ToscaServiceTemplate plainPolicies = standardCoder.decode(inputJson, ToscaServiceTemplate.class);
+ JpaToscaServiceTemplate internalPolicies = new JpaToscaServiceTemplate();
+ internalPolicies.fromAuthorative(plainPolicies);
- assertTrue(internalPolicies.validate(new PfValidationResult()).isValid());
- ToscaServiceTemplate plainPolicies2 = internalPolicies.toAuthorative();
+ assertTrue(internalPolicies.validate(new PfValidationResult()).isValid());
+ ToscaServiceTemplate plainPolicies2 = internalPolicies.toAuthorative();
- ToscaPolicy pp1 = plainPolicies.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
- ToscaPolicy pp2 = plainPolicies2.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
+ ToscaPolicy pp1 = plainPolicies.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
+ ToscaPolicy pp2 = plainPolicies2.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
- assertEquals(pp1.getProperties().keySet(), pp2.getProperties().keySet());
-
- } catch (Exception e) {
- LOGGER.warn("no exception should be thrown", e);
- fail("no exception should be thrown");
- }
+ assertEquals(pp1.getProperties().keySet(), pp2.getProperties().keySet());
}
@Test
public void testPlainToscaPolicyTypes() throws Exception {
- try {
- Yaml yaml = new Yaml();
- String inputYaml = ResourceUtils.getResourceAsString(
- "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml");
- Object yamlObject = yaml.load(inputYaml);
- String yamlAsJsonString = standardCoder.encode(yamlObject);
-
- ToscaServiceTemplate plainPolicyTypes = standardCoder.decode(yamlAsJsonString,
- ToscaServiceTemplate.class);
- JpaToscaServiceTemplate internalPolicyTypes = new JpaToscaServiceTemplate();
- internalPolicyTypes.fromAuthorative(plainPolicyTypes);
- assertTrue(internalPolicyTypes.validate(new PfValidationResult()).isValid());
- ToscaServiceTemplate plainPolicyTypes2 = internalPolicyTypes.toAuthorative();
- JpaToscaServiceTemplate internalPolicyTypes2 = new JpaToscaServiceTemplate();
- internalPolicyTypes2.fromAuthorative(plainPolicyTypes2);
- assertTrue(internalPolicyTypes2.validate(new PfValidationResult()).isValid());
- assertTrue(internalPolicyTypes.compareTo(internalPolicyTypes2) == 0);
-
- } catch (Exception e) {
- LOGGER.warn("no exception should be thrown", e);
- fail("no exception should be thrown");
- }
-
+ Yaml yaml = new Yaml();
+ String inputYaml = ResourceUtils.getResourceAsString(
+ "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml");
+ Object yamlObject = yaml.load(inputYaml);
+ String yamlAsJsonString = standardCoder.encode(yamlObject);
+
+ ToscaServiceTemplate plainPolicyTypes = standardCoder.decode(yamlAsJsonString,
+ ToscaServiceTemplate.class);
+ JpaToscaServiceTemplate internalPolicyTypes = new JpaToscaServiceTemplate();
+ internalPolicyTypes.fromAuthorative(plainPolicyTypes);
+ assertTrue(internalPolicyTypes.validate(new PfValidationResult()).isValid());
+ ToscaServiceTemplate plainPolicyTypes2 = internalPolicyTypes.toAuthorative();
+ JpaToscaServiceTemplate internalPolicyTypes2 = new JpaToscaServiceTemplate();
+ internalPolicyTypes2.fromAuthorative(plainPolicyTypes2);
+ assertTrue(internalPolicyTypes2.validate(new PfValidationResult()).isValid());
+ assertTrue(internalPolicyTypes.compareTo(internalPolicyTypes2) == 0);
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java
index 9c2344080..e06692ab0 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java
@@ -49,8 +49,6 @@ public class LegacyGuardPolicyTest {
assertEquals("SO", guard.getContent().getActor());
DummyBadLegacyGuardPolicyContent dblgpc = new DummyBadLegacyGuardPolicyContent();
- assertThatThrownBy(() -> {
- dblgpc.getAsPropertyMap();
- }).hasMessage("could not convert content to a property map");
+ assertThatThrownBy(dblgpc::getAsPropertyMap).hasMessage("could not convert content to a property map");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java
index 4df62aff0..e9761c669 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -77,7 +78,7 @@ public class LegacyOperationalPolicyMapperTest {
}
@Test
- public void testOperationalPolicyMapper() throws Exception {
+ public void testOperationalPolicyMapper() {
JpaToscaServiceTemplate serviceTemplate = new JpaToscaServiceTemplate();
serviceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate());
serviceTemplate.getTopologyTemplate().setPolicies(new JpaToscaPolicies());
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java
index be5fa5dc3..59605ed5b 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -52,6 +53,11 @@ import org.yaml.snakeyaml.Yaml;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class LegacyProvider4LegacyGuardTest {
+ private static final String POLICY_ID_IS_NULL = "policyId is marked @NonNull but is null";
+ private static final String VDNS_OUTPUT_JSON = "policies/vDNS.policy.guard.frequency.output.json";
+ private static final String VDNS_INPUT_JSON = "policies/vDNS.policy.guard.frequency.input.json";
+ private static final String LEGACY_POLICY_IS_NULL = "legacyGuardPolicy is marked @NonNull but is null";
+ private static final String DAO_IS_NULL = "dao is marked @NonNull but is null";
private PfDao pfDao;
private StandardCoder standardCoder;
@@ -91,7 +97,7 @@ public class LegacyProvider4LegacyGuardTest {
}
@After
- public void teardown() throws Exception {
+ public void teardown() {
pfDao.close();
}
@@ -99,15 +105,15 @@ public class LegacyProvider4LegacyGuardTest {
public void testPoliciesGet() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().getGuardPolicy(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().getGuardPolicy(null, null, "");
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().getGuardPolicy(pfDao, null, null);
- }).hasMessage("policyId is marked @NonNull but is null");
+ }).hasMessage(POLICY_ID_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().getGuardPolicy(pfDao, "I Dont Exist", null);
@@ -116,7 +122,7 @@ public class LegacyProvider4LegacyGuardTest {
createPolicyTypes();
LegacyGuardPolicyInput originalGip = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.input.json"),
+ ResourceUtils.getResourceAsString(VDNS_INPUT_JSON),
LegacyGuardPolicyInput.class);
assertNotNull(originalGip);
@@ -135,7 +141,7 @@ public class LegacyProvider4LegacyGuardTest {
gotGopm.get(originalGip.getPolicyId()).getProperties().values().iterator().next());
String expectedJsonOutput =
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.output.json");
+ ResourceUtils.getResourceAsString(VDNS_OUTPUT_JSON);
String actualJsonOutput = standardCoder.encode(gotGopm);
assertEquals(expectedJsonOutput.replaceAll("\\s+", ""), actualJsonOutput.replaceAll("\\s+", ""));
@@ -159,20 +165,20 @@ public class LegacyProvider4LegacyGuardTest {
public void testPolicyCreate() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().createGuardPolicy(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().createGuardPolicy(null, new LegacyGuardPolicyInput());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().createGuardPolicy(pfDao, null);
- }).hasMessage("legacyGuardPolicy is marked @NonNull but is null");
+ }).hasMessage(LEGACY_POLICY_IS_NULL);
createPolicyTypes();
LegacyGuardPolicyInput originalGip = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.input.json"),
+ ResourceUtils.getResourceAsString(VDNS_INPUT_JSON),
LegacyGuardPolicyInput.class);
assertNotNull(originalGip);
@@ -191,7 +197,7 @@ public class LegacyProvider4LegacyGuardTest {
gotGopm.get(originalGip.getPolicyId()).getProperties().values().iterator().next());
String expectedJsonOutput =
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.output.json");
+ ResourceUtils.getResourceAsString(VDNS_OUTPUT_JSON);
String actualJsonOutput = standardCoder.encode(gotGopm);
assertEquals(expectedJsonOutput.replaceAll("\\s+", ""), actualJsonOutput.replaceAll("\\s+", ""));
@@ -201,20 +207,20 @@ public class LegacyProvider4LegacyGuardTest {
public void testPolicyCreateBad() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().createGuardPolicy(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().createGuardPolicy(null, new LegacyGuardPolicyInput());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().createGuardPolicy(pfDao, null);
- }).hasMessage("legacyGuardPolicy is marked @NonNull but is null");
+ }).hasMessage(LEGACY_POLICY_IS_NULL);
createPolicyTypes();
LegacyGuardPolicyInput originalGip = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.input.json"),
+ ResourceUtils.getResourceAsString(VDNS_INPUT_JSON),
LegacyGuardPolicyInput.class);
assertNotNull(originalGip);
@@ -230,15 +236,15 @@ public class LegacyProvider4LegacyGuardTest {
public void testPolicyUpdate() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().updateGuardPolicy(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().updateGuardPolicy(null, new LegacyGuardPolicyInput());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().updateGuardPolicy(pfDao, null);
- }).hasMessage("legacyGuardPolicy is marked @NonNull but is null");
+ }).hasMessage(LEGACY_POLICY_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().updateGuardPolicy(pfDao, new LegacyGuardPolicyInput());
@@ -247,7 +253,7 @@ public class LegacyProvider4LegacyGuardTest {
createPolicyTypes();
LegacyGuardPolicyInput originalGip = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.input.json"),
+ ResourceUtils.getResourceAsString(VDNS_INPUT_JSON),
LegacyGuardPolicyInput.class);
assertNotNull(originalGip);
@@ -284,27 +290,27 @@ public class LegacyProvider4LegacyGuardTest {
public void testPoliciesDelete() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().deleteGuardPolicy(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteGuardPolicy(null, null, "");
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteGuardPolicy(null, "", null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteGuardPolicy(null, "", "");
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteGuardPolicy(pfDao, null, null);
- }).hasMessage("policyId is marked @NonNull but is null");
+ }).hasMessage(POLICY_ID_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteGuardPolicy(pfDao, null, "");
- }).hasMessage("policyId is marked @NonNull but is null");
+ }).hasMessage(POLICY_ID_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteGuardPolicy(pfDao, "", null);
@@ -317,7 +323,7 @@ public class LegacyProvider4LegacyGuardTest {
createPolicyTypes();
LegacyGuardPolicyInput originalGip = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.input.json"),
+ ResourceUtils.getResourceAsString(VDNS_INPUT_JSON),
LegacyGuardPolicyInput.class);
assertNotNull(originalGip);
@@ -335,7 +341,7 @@ public class LegacyProvider4LegacyGuardTest {
gotGopm.get(originalGip.getPolicyId()).getProperties().values().iterator().next());
String expectedJsonOutput =
- ResourceUtils.getResourceAsString("policies/vDNS.policy.guard.frequency.output.json");
+ ResourceUtils.getResourceAsString(VDNS_OUTPUT_JSON);
String actualJsonOutput = standardCoder.encode(gotGopm);
assertEquals(expectedJsonOutput.replaceAll("\\s+", ""), actualJsonOutput.replaceAll("\\s+", ""));
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java
index 636063641..dfbba4497 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -49,6 +50,10 @@ import org.yaml.snakeyaml.Yaml;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class LegacyProvider4LegacyOperationalTest {
+ private static final String POLICY_ID_IS_NULL = "policyId is marked @NonNull but is null";
+ private static final String VCPE_OUTPUT_JSON = "policies/vCPE.policy.operational.output.json";
+ private static final String VCPE_INPUT_JSON = "policies/vCPE.policy.operational.input.json";
+ private static final String DAO_IS_NULL = "dao is marked @NonNull but is null";
private PfDao pfDao;
private StandardCoder standardCoder;
@@ -87,7 +92,7 @@ public class LegacyProvider4LegacyOperationalTest {
}
@After
- public void teardown() throws Exception {
+ public void teardown() {
pfDao.close();
}
@@ -95,15 +100,15 @@ public class LegacyProvider4LegacyOperationalTest {
public void testPoliciesGet() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().getOperationalPolicy(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().getOperationalPolicy(null, "", null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().getOperationalPolicy(pfDao, null, null);
- }).hasMessage("policyId is marked @NonNull but is null");
+ }).hasMessage(POLICY_ID_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().getOperationalPolicy(pfDao, "I Dont Exist", null);
@@ -112,7 +117,7 @@ public class LegacyProvider4LegacyOperationalTest {
createPolicyTypes();
LegacyOperationalPolicy originalLop =
- standardCoder.decode(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+ standardCoder.decode(ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
LegacyOperationalPolicy.class);
assertNotNull(originalLop);
@@ -126,7 +131,7 @@ public class LegacyProvider4LegacyOperationalTest {
assertEquals(gotLop, originalLop);
- String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json");
+ String expectedJsonOutput = ResourceUtils.getResourceAsString(VCPE_OUTPUT_JSON);
String actualJsonOutput = standardCoder.encode(gotLop);
assertEquals(expectedJsonOutput.replaceAll("\\s+", ""), actualJsonOutput.replaceAll("\\s+", ""));
@@ -141,11 +146,11 @@ public class LegacyProvider4LegacyOperationalTest {
public void testPolicyCreate() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().createOperationalPolicy(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().createOperationalPolicy(null, new LegacyOperationalPolicy());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().createOperationalPolicy(pfDao, null);
@@ -154,7 +159,7 @@ public class LegacyProvider4LegacyOperationalTest {
createPolicyTypes();
LegacyOperationalPolicy originalLop =
- standardCoder.decode(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+ standardCoder.decode(ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
LegacyOperationalPolicy.class);
assertNotNull(originalLop);
@@ -168,7 +173,7 @@ public class LegacyProvider4LegacyOperationalTest {
assertEquals(gotLop, originalLop);
- String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json");
+ String expectedJsonOutput = ResourceUtils.getResourceAsString(VCPE_OUTPUT_JSON);
String actualJsonOutput = standardCoder.encode(gotLop);
assertEquals(expectedJsonOutput.replaceAll("\\s+", ""), actualJsonOutput.replaceAll("\\s+", ""));
@@ -178,11 +183,11 @@ public class LegacyProvider4LegacyOperationalTest {
public void testPolicyUpdate() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().updateOperationalPolicy(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().updateOperationalPolicy(null, new LegacyOperationalPolicy());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().updateOperationalPolicy(pfDao, null);
@@ -195,7 +200,7 @@ public class LegacyProvider4LegacyOperationalTest {
createPolicyTypes();
LegacyOperationalPolicy originalLop =
- standardCoder.decode(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+ standardCoder.decode(ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
LegacyOperationalPolicy.class);
assertNotNull(originalLop);
@@ -221,29 +226,29 @@ public class LegacyProvider4LegacyOperationalTest {
public void testPoliciesDelete() throws Exception {
assertThatThrownBy(() -> {
new LegacyProvider().deleteOperationalPolicy(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteOperationalPolicy(null, null, "");
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteOperationalPolicy(null, "", null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteOperationalPolicy(null, "", "");
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteOperationalPolicy(pfDao, null, null);
- }).hasMessage("policyId is marked @NonNull but is null");
+ }).hasMessage(POLICY_ID_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteOperationalPolicy(pfDao, null, "");
- }).hasMessage("policyId is marked @NonNull but is null");
+ }).hasMessage(POLICY_ID_IS_NULL);
assertThatThrownBy(() -> {
new LegacyProvider().deleteOperationalPolicy(pfDao, "", null);
@@ -256,7 +261,7 @@ public class LegacyProvider4LegacyOperationalTest {
createPolicyTypes();
LegacyOperationalPolicy originalLop =
- standardCoder.decode(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"),
+ standardCoder.decode(ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
LegacyOperationalPolicy.class);
assertNotNull(originalLop);
@@ -269,7 +274,7 @@ public class LegacyProvider4LegacyOperationalTest {
assertEquals(gotLop, originalLop);
- String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json");
+ String expectedJsonOutput = ResourceUtils.getResourceAsString(VCPE_OUTPUT_JSON);
String actualJsonOutput = standardCoder.encode(gotLop);
assertEquals(expectedJsonOutput.replaceAll("\\s+", ""), actualJsonOutput.replaceAll("\\s+", ""));
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java
index d3239da73..e48f5f895 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -36,30 +37,32 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaConstraint;
*/
public class JpaToscaConstraintLogicalTest {
+ private static final String HELLO = "Hello";
+
@Test
public void testLogicalConstraint() {
ToscaConstraint c0 = new ToscaConstraint();
- c0.setEqual("Hello");
+ c0.setEqual(HELLO);
JpaToscaConstraintLogical jc0 = new JpaToscaConstraintLogical(c0);
assertEquals(c0, jc0.toAuthorative());
ToscaConstraint c1 = new ToscaConstraint();
- c1.setGreaterOrEqual("Hello");
+ c1.setGreaterOrEqual(HELLO);
JpaToscaConstraintLogical jc1 = new JpaToscaConstraintLogical(c1);
assertEquals(c1, jc1.toAuthorative());
ToscaConstraint c2 = new ToscaConstraint();
- c2.setGreaterThan("Hello");
+ c2.setGreaterThan(HELLO);
JpaToscaConstraintLogical jc2 = new JpaToscaConstraintLogical(c2);
assertEquals(c2, jc2.toAuthorative());
ToscaConstraint c3 = new ToscaConstraint();
- c3.setLessOrEqual("Hello");
+ c3.setLessOrEqual(HELLO);
JpaToscaConstraintLogical jc3 = new JpaToscaConstraintLogical(c3);
assertEquals(c3, jc3.toAuthorative());
ToscaConstraint c4 = new ToscaConstraint();
- c4.setLessThan("Hello");
+ c4.setLessThan(HELLO);
JpaToscaConstraintLogical jc4 = new JpaToscaConstraintLogical(c4);
assertEquals(c4, jc4.toAuthorative());
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java
index ff4187a47..ce5ace1c0 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,17 +21,15 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConstraint;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraintLogical;
/**
* DAO test for ToscaConstraintLogicalString.
@@ -39,32 +38,22 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraintLogical;
*/
public class JpaToscaConstraintTest {
+ private static final String CONSTRAINT = "Constraint";
+
@Test
public void testConstraintLogicalStringPojo() {
- assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint"));
+ assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, CONSTRAINT));
- try {
- new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("operation is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, null))
+ .hasMessage("operation is marked @NonNull but is null");
- try {
- new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, "Hello");
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("operation is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, "Hello"))
+ .hasMessage("operation is marked @NonNull but is null");
- try {
- new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("compareTo is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, null))
+ .hasMessage("compareTo is marked @NonNull but is null");
- assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint"));
+ assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, CONSTRAINT));
assertEquals(0, new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "")
.compareTo(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "")));
@@ -78,7 +67,7 @@ public class JpaToscaConstraintTest {
JpaToscaConstraintValidValues cvv0 = new JpaToscaConstraintValidValues(validValues);
assertEquals(-1, cvv0.compareTo(null));
assertEquals(0, cvv0.compareTo(cvv0));
- assertNotEquals(0, cvv0.compareTo(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint")));
+ assertNotEquals(0, cvv0.compareTo(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, CONSTRAINT)));
JpaToscaConstraintValidValues cvv1 = new JpaToscaConstraintValidValues(validValues);
assertEquals(0, cvv0.compareTo(cvv1));
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java
index 66cde51fc..591c65518 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -48,6 +49,8 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaProperty;
*/
public class JpaToscaDataTypeTest {
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testDataTypePojo() {
assertNotNull(new JpaToscaDataType());
@@ -63,7 +66,7 @@ public class JpaToscaDataTypeTest {
new JpaToscaDataType((JpaToscaDataType) null);
}).hasMessage("copyConcept is marked @NonNull but is null");
- PfConceptKey dtKey = new PfConceptKey("tdt", "0.0.1");
+ PfConceptKey dtKey = new PfConceptKey("tdt", VERSION_001);
JpaToscaDataType tdt = new JpaToscaDataType(dtKey);
List<JpaToscaConstraint> constraints = new ArrayList<>();
@@ -73,7 +76,8 @@ public class JpaToscaDataTypeTest {
assertEquals(constraints, tdt.getConstraints());
Map<String, JpaToscaProperty> properties = new LinkedHashMap<>();
- JpaToscaProperty tp = new JpaToscaProperty(new PfReferenceKey(dtKey, "pr"), new PfConceptKey("type", "0.0.1"));
+ JpaToscaProperty tp =
+ new JpaToscaProperty(new PfReferenceKey(dtKey, "pr"), new PfConceptKey("type", VERSION_001));
properties.put(tp.getKey().getLocalName(), tp);
tdt.setProperties(properties);
assertEquals(properties, tdt.getProperties());
@@ -91,7 +95,7 @@ public class JpaToscaDataTypeTest {
assertEquals(0, tdt.compareTo(tdt));
assertFalse(tdt.compareTo(tdt.getKey()) == 0);
- PfConceptKey otherDtKey = new PfConceptKey("otherDt", "0.0.1");
+ PfConceptKey otherDtKey = new PfConceptKey("otherDt", VERSION_001);
JpaToscaDataType otherDt = new JpaToscaDataType(otherDtKey);
assertFalse(tdt.compareTo(otherDt) == 0);
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java
index c732fa604..5421b953e 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,24 +21,22 @@
package org.onap.policy.models.tosca.simple.concepts;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataTypes;
public class JpaToscaDataTypesTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+
@Test
public void testDataTypes() {
assertNotNull(new JpaToscaDataTypes());
@@ -45,40 +44,18 @@ public class JpaToscaDataTypesTest {
assertNotNull(new JpaToscaDataTypes(new PfConceptKey(), new TreeMap<PfConceptKey, JpaToscaDataType>()));
assertNotNull(new JpaToscaDataTypes(new JpaToscaDataTypes()));
- try {
- new JpaToscaDataTypes((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaDataTypes((PfConceptKey) null)).hasMessage(KEY_IS_NULL);
- try {
- new JpaToscaDataTypes((JpaToscaDataTypes) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaDataTypes((JpaToscaDataTypes) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
- try {
- new JpaToscaDataTypes(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaDataTypes(null, null)).hasMessage(KEY_IS_NULL);
- try {
- new JpaToscaDataTypes(new PfConceptKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("conceptMap is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaDataTypes(new PfConceptKey(), null))
+ .hasMessage("conceptMap is marked @NonNull but is null");
- try {
- new JpaToscaDataTypes(null, new TreeMap<PfConceptKey, JpaToscaDataType>());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaDataTypes(null, new TreeMap<PfConceptKey, JpaToscaDataType>()))
+ .hasMessage(KEY_IS_NULL);
List<Map<String, ToscaDataType>> dtMapList = new ArrayList<>();
dtMapList.add(new LinkedHashMap<>());
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchemaTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchemaTest.java
index 4a9bdbe2e..b306685d0 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchemaTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchemaTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,20 +21,17 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfValidationResult;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraint;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaEntrySchema;
/**
* DAO test for ToscaEntrySchema.
@@ -42,30 +40,24 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaEntrySchema;
*/
public class JpaToscaEntrySchemaTest {
+ private static final String A_DESCRIPTION = "A Description";
+
@Test
public void testEntrySchemaPojo() {
assertNotNull(new JpaToscaEntrySchema(new PfConceptKey()));
assertNotNull(new JpaToscaEntrySchema(new JpaToscaEntrySchema(new PfConceptKey())));
- try {
- new JpaToscaEntrySchema((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("type is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaEntrySchema((PfConceptKey) null))
+ .hasMessage("type is marked @NonNull but is null");
- try {
- new JpaToscaEntrySchema((JpaToscaEntrySchema) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaEntrySchema((JpaToscaEntrySchema) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
PfConceptKey typeKey = new PfConceptKey("type", "0.0.1");
JpaToscaEntrySchema tes = new JpaToscaEntrySchema(typeKey);
- tes.setDescription("A Description");
- assertEquals("A Description", tes.getDescription());
+ tes.setDescription(A_DESCRIPTION);
+ assertEquals(A_DESCRIPTION, tes.getDescription());
List<JpaToscaConstraint> constraints = new ArrayList<>();
JpaToscaConstraintLogical lsc = new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "hello");
@@ -89,17 +81,12 @@ public class JpaToscaEntrySchemaTest {
assertFalse(tes.compareTo(otherEs) == 0);
otherEs.setType(typeKey);
assertFalse(tes.compareTo(otherEs) == 0);
- otherEs.setDescription("A Description");
+ otherEs.setDescription(A_DESCRIPTION);
assertFalse(tes.compareTo(otherEs) == 0);
otherEs.setConstraints(constraints);
assertEquals(0, tes.compareTo(otherEs));
- try {
- tes.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tes.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(1, tes.getKeys().size());
assertEquals(1, new JpaToscaEntrySchema(typeKey).getKeys().size());
@@ -120,7 +107,7 @@ public class JpaToscaEntrySchemaTest {
tes.setDescription("");;
assertFalse(tes.validate(new PfValidationResult()).isValid());
- tes.setDescription("A Description");
+ tes.setDescription(A_DESCRIPTION);
assertTrue(tes.validate(new PfValidationResult()).isValid());
tes.getConstraints().add(null);
@@ -128,11 +115,6 @@ public class JpaToscaEntrySchemaTest {
tes.getConstraints().remove(null);
assertTrue(tes.validate(new PfValidationResult()).isValid());
- try {
- tes.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tes.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEventFilterTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEventFilterTest.java
index 19846a0cc..602985dda 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEventFilterTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEventFilterTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,17 +21,16 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfReferenceKey;
import org.onap.policy.models.base.PfValidationResult;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaEventFilter;
/**
* DAO test for ToscaEventFilter.
@@ -39,6 +39,11 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaEventFilter;
*/
public class JpaToscaEventFilterTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+ private static final String A_REQUREMENT = "A Requrement";
+ private static final String A_CAPABILITY = "A Capability";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testEventFilterPojo() {
assertNotNull(new JpaToscaEventFilter());
@@ -46,51 +51,28 @@ public class JpaToscaEventFilterTest {
assertNotNull(new JpaToscaEventFilter(new PfReferenceKey(), new PfConceptKey()));
assertNotNull(new JpaToscaEventFilter(new JpaToscaEventFilter()));
- try {
- new JpaToscaEventFilter((PfReferenceKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaEventFilter(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaEventFilter(null, new PfConceptKey());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaEventFilter(new PfReferenceKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("node is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaEventFilter((JpaToscaEventFilter) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- PfConceptKey efParentKey = new PfConceptKey("tParentKey", "0.0.1");
+ assertThatThrownBy(() -> new JpaToscaEventFilter((PfReferenceKey) null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaEventFilter(null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaEventFilter(null, new PfConceptKey())).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaEventFilter(new PfReferenceKey(), null))
+ .hasMessage("node is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaEventFilter((JpaToscaEventFilter) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ PfConceptKey efParentKey = new PfConceptKey("tParentKey", VERSION_001);
PfReferenceKey efKey = new PfReferenceKey(efParentKey, "trigger0");
- PfConceptKey nodeKey = new PfConceptKey("tParentKey", "0.0.1");
+ PfConceptKey nodeKey = new PfConceptKey("tParentKey", VERSION_001);
JpaToscaEventFilter tef = new JpaToscaEventFilter(efKey, nodeKey);
- tef.setRequirement("A Requrement");
- assertEquals("A Requrement", tef.getRequirement());
+ tef.setRequirement(A_REQUREMENT);
+ assertEquals(A_REQUREMENT, tef.getRequirement());
- tef.setCapability("A Capability");
- assertEquals("A Capability", tef.getCapability());
+ tef.setCapability(A_CAPABILITY);
+ assertEquals(A_CAPABILITY, tef.getCapability());
JpaToscaEventFilter tdtClone0 = new JpaToscaEventFilter(tef);
assertEquals(tef, tdtClone0);
@@ -105,7 +87,7 @@ public class JpaToscaEventFilterTest {
assertEquals(0, tef.compareTo(tef));
assertFalse(tef.compareTo(tef.getKey()) == 0);
- PfReferenceKey otherDtKey = new PfReferenceKey("otherDt", "0.0.1", "OtherEventFilter");
+ PfReferenceKey otherDtKey = new PfReferenceKey("otherDt", VERSION_001, "OtherEventFilter");
JpaToscaEventFilter otherDt = new JpaToscaEventFilter(otherDtKey);
assertFalse(tef.compareTo(otherDt) == 0);
@@ -113,17 +95,12 @@ public class JpaToscaEventFilterTest {
assertFalse(tef.compareTo(otherDt) == 0);
otherDt.setNode(nodeKey);
assertFalse(tef.compareTo(otherDt) == 0);
- otherDt.setRequirement("A Requrement");
+ otherDt.setRequirement(A_REQUREMENT);
assertFalse(tef.compareTo(otherDt) == 0);
- otherDt.setCapability("A Capability");
+ otherDt.setCapability(A_CAPABILITY);
assertEquals(0, tef.compareTo(otherDt));
- try {
- tef.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tef.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(2, tef.getKeys().size());
assertEquals(2, new JpaToscaEventFilter().getKeys().size());
@@ -139,14 +116,14 @@ public class JpaToscaEventFilterTest {
assertTrue(tef.validate(new PfValidationResult()).isValid());
tef.setRequirement("");
assertFalse(tef.validate(new PfValidationResult()).isValid());
- tef.setRequirement("A Requrement");
+ tef.setRequirement(A_REQUREMENT);
assertTrue(tef.validate(new PfValidationResult()).isValid());
tef.setCapability(null);
assertTrue(tef.validate(new PfValidationResult()).isValid());
tef.setCapability("");
assertFalse(tef.validate(new PfValidationResult()).isValid());
- tef.setCapability("A Capability");
+ tef.setCapability(A_CAPABILITY);
assertTrue(tef.validate(new PfValidationResult()).isValid());
tef.setNode(null);
@@ -156,11 +133,6 @@ public class JpaToscaEventFilterTest {
tef.setNode(nodeKey);
assertTrue(tef.validate(new PfValidationResult()).isValid());
- try {
- tef.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tef.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModelTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModelTest.java
index a62c79956..40fbc0515 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModelTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModelTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,22 +21,18 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.Map;
import java.util.TreeMap;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfModelService;
import org.onap.policy.models.base.PfValidationResult;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaModel;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplates;
/**
* DAO test for ToscaDatatype.
@@ -44,6 +41,9 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplates;
*/
public class JpaToscaModelTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testModelPojo() {
assertNotNull(new JpaToscaModel());
@@ -51,45 +51,22 @@ public class JpaToscaModelTest {
assertNotNull(new JpaToscaModel(new PfConceptKey(), new JpaToscaServiceTemplates()));
assertNotNull(new JpaToscaModel(new JpaToscaModel()));
- try {
- new JpaToscaModel((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaModel(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaModel(null, new JpaToscaServiceTemplates());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaModel(new PfConceptKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("serviceTemplates is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaModel((JpaToscaModel) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- PfConceptKey tstsKey = new PfConceptKey("tsts", "0.0.1");
+ assertThatThrownBy(() -> new JpaToscaModel((PfConceptKey) null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaModel(null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaModel(null, new JpaToscaServiceTemplates())).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaModel(new PfConceptKey(), null))
+ .hasMessage("serviceTemplates is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaModel((JpaToscaModel) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ PfConceptKey tstsKey = new PfConceptKey("tsts", VERSION_001);
Map<PfConceptKey, JpaToscaServiceTemplate> tstMap = new TreeMap<>();
JpaToscaServiceTemplates tsts = new JpaToscaServiceTemplates(tstsKey, tstMap);
- PfConceptKey tmKey = new PfConceptKey("tst", "0.0.1");
+ PfConceptKey tmKey = new PfConceptKey("tst", VERSION_001);
JpaToscaModel tm = new JpaToscaModel(tmKey, tsts);
JpaToscaModel tttClone0 = new JpaToscaModel(tm);
@@ -105,7 +82,7 @@ public class JpaToscaModelTest {
assertEquals(0, tm.compareTo(tm));
assertFalse(tm.compareTo(tm.getKey()) == 0);
- PfConceptKey otherDtKey = new PfConceptKey("otherDt", "0.0.1");
+ PfConceptKey otherDtKey = new PfConceptKey("otherDt", VERSION_001);
JpaToscaModel otherDt = new JpaToscaModel(otherDtKey);
assertFalse(tm.compareTo(otherDt) == 0);
@@ -114,12 +91,7 @@ public class JpaToscaModelTest {
otherDt.setServiceTemplates(tsts);
assertEquals(0, tm.compareTo(otherDt));
- try {
- tm.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("targetObject is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tm.copyTo(null)).hasMessage("targetObject is marked @NonNull but is null");
assertEquals(2, tm.getKeys().size());
assertEquals(2, new JpaToscaModel().getKeys().size());
@@ -135,11 +107,6 @@ public class JpaToscaModelTest {
assertTrue(PfModelService.existsModel(tm.getServiceTemplates().getId()));
PfModelService.deregisterModel(tm.getServiceTemplates().getId());
- try {
- tm.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tm.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java
index db3635ecb..10616f2eb 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,24 +21,22 @@
package org.onap.policy.models.tosca.simple.concepts;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy;
public class JpaToscaPoliciesTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+
@Test
public void testPolicies() {
assertNotNull(new JpaToscaPolicies());
@@ -45,40 +44,18 @@ public class JpaToscaPoliciesTest {
assertNotNull(new JpaToscaPolicies(new PfConceptKey(), new TreeMap<PfConceptKey, JpaToscaPolicy>()));
assertNotNull(new JpaToscaPolicies(new JpaToscaPolicies()));
- try {
- new JpaToscaPolicies((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicies((PfConceptKey) null)).hasMessage(KEY_IS_NULL);
- try {
- new JpaToscaPolicies((JpaToscaPolicies) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicies((JpaToscaPolicies) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
- try {
- new JpaToscaPolicies(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicies(null, null)).hasMessage(KEY_IS_NULL);
- try {
- new JpaToscaPolicies(new PfConceptKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("conceptMap is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicies(new PfConceptKey(), null))
+ .hasMessage("conceptMap is marked @NonNull but is null");
- try {
- new JpaToscaPolicies(null, new TreeMap<PfConceptKey, JpaToscaPolicy>());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicies(null, new TreeMap<PfConceptKey, JpaToscaPolicy>()))
+ .hasMessage(KEY_IS_NULL);
List<Map<String, ToscaPolicy>> polMapList = new ArrayList<>();
polMapList.add(new LinkedHashMap<>());
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java
index 924cdab53..bb961783c 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -45,6 +46,9 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy;
*/
public class JpaToscaPolicyTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testPolicyPojo() {
assertNotNull(new JpaToscaPolicy());
@@ -58,11 +62,11 @@ public class JpaToscaPolicyTest {
assertThatThrownBy(() -> {
new JpaToscaPolicy((PfConceptKey) null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(KEY_IS_NULL);
assertThatThrownBy(() -> {
new JpaToscaPolicy(null, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(KEY_IS_NULL);
assertThatThrownBy(() -> {
new JpaToscaPolicy(new PfConceptKey(), null);
@@ -70,14 +74,14 @@ public class JpaToscaPolicyTest {
assertThatThrownBy(() -> {
new JpaToscaPolicy(null, new PfConceptKey());
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(KEY_IS_NULL);
assertThatThrownBy(() -> {
new JpaToscaPolicy((JpaToscaPolicy) null);
}).hasMessage("copyConcept is marked @NonNull but is null");
- PfConceptKey tpKey = new PfConceptKey("tdt", "0.0.1");
- PfConceptKey ptKey = new PfConceptKey("policyType", "0.0.1");
+ PfConceptKey tpKey = new PfConceptKey("tdt", VERSION_001);
+ PfConceptKey ptKey = new PfConceptKey("policyType", VERSION_001);
JpaToscaPolicy tp = new JpaToscaPolicy(tpKey, ptKey);
Map<String, String> propertyMap = new HashMap<>();
@@ -86,7 +90,7 @@ public class JpaToscaPolicyTest {
assertEquals(propertyMap, tp.getProperties());
List<PfConceptKey> targets = new ArrayList<>();
- PfConceptKey target = new PfConceptKey("target", "0.0.1");
+ PfConceptKey target = new PfConceptKey("target", VERSION_001);
targets.add(target);
tp.setTargets(targets);
assertEquals(targets, tp.getTargets());
@@ -104,7 +108,7 @@ public class JpaToscaPolicyTest {
assertEquals(0, tp.compareTo(tp));
assertFalse(tp.compareTo(tp.getKey()) == 0);
- PfConceptKey otherDtKey = new PfConceptKey("otherDt", "0.0.1");
+ PfConceptKey otherDtKey = new PfConceptKey("otherDt", VERSION_001);
JpaToscaPolicy otherDt = new JpaToscaPolicy(otherDtKey);
assertFalse(tp.compareTo(otherDt) == 0);
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java
index 3cdcd9552..eb94a5ecc 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,28 +21,23 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfReferenceKey;
import org.onap.policy.models.base.PfValidationResult;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaEntityType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaProperty;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaTrigger;
/**
* DAO test for ToscaPolicyType.
@@ -49,30 +45,25 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaTrigger;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class JpaToscaPolicyTypeTest {
+ private static final String A_DESCRIPTION = "A Description";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testPolicyTypePojo() {
assertNotNull(new JpaToscaPolicyType());
assertNotNull(new JpaToscaPolicyType(new PfConceptKey()));
assertNotNull(new JpaToscaPolicyType(new JpaToscaPolicyType()));
- try {
- new JpaToscaPolicyType((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaPolicyType((JpaToscaPolicyType) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- PfConceptKey ptKey = new PfConceptKey("tdt", "0.0.1");
+ assertThatThrownBy(() -> new JpaToscaPolicyType((PfConceptKey) null))
+ .hasMessage("key is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaPolicyType((JpaToscaPolicyType) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ PfConceptKey ptKey = new PfConceptKey("tdt", VERSION_001);
JpaToscaPolicyType tpt = new JpaToscaPolicyType(ptKey);
- PfConceptKey derivedFromKey = new PfConceptKey("deriveFrom", "0.0.1");
+ PfConceptKey derivedFromKey = new PfConceptKey("deriveFrom", VERSION_001);
tpt.setDerivedFrom(derivedFromKey);
Map<String, String> metadata = new HashMap<>();
@@ -80,9 +71,9 @@ public class JpaToscaPolicyTypeTest {
tpt.setMetadata(metadata);
assertEquals(metadata, tpt.getMetadata());
- tpt.setDescription("A Description");
+ tpt.setDescription(A_DESCRIPTION);
- PfConceptKey propTypeKey = new PfConceptKey("propType", "0.0.1");
+ PfConceptKey propTypeKey = new PfConceptKey("propType", VERSION_001);
Map<String, JpaToscaProperty> properties = new LinkedHashMap<>();
JpaToscaProperty tp = new JpaToscaProperty(new PfReferenceKey(ptKey, "aProp"), propTypeKey);
properties.put(tp.getKey().getLocalName(), tp);
@@ -90,7 +81,7 @@ public class JpaToscaPolicyTypeTest {
assertEquals(properties, tpt.getProperties());
List<PfConceptKey> targets = new ArrayList<>();
- PfConceptKey target = new PfConceptKey("target", "0.0.1");
+ PfConceptKey target = new PfConceptKey("target", VERSION_001);
targets.add(target);
tpt.setTargets(targets);
assertEquals(targets, tpt.getTargets());
@@ -114,7 +105,7 @@ public class JpaToscaPolicyTypeTest {
assertEquals(0, tpt.compareTo(tpt));
assertFalse(tpt.compareTo(tpt.getKey()) == 0);
- PfConceptKey otherDtKey = new PfConceptKey("otherDt", "0.0.1");
+ PfConceptKey otherDtKey = new PfConceptKey("otherDt", VERSION_001);
JpaToscaPolicyType otherDt = new JpaToscaPolicyType(otherDtKey);
assertFalse(tpt.compareTo(otherDt) == 0);
@@ -124,7 +115,7 @@ public class JpaToscaPolicyTypeTest {
assertFalse(tpt.compareTo(otherDt) == 0);
otherDt.setMetadata(metadata);
assertFalse(tpt.compareTo(otherDt) == 0);
- otherDt.setDescription("A Description");
+ otherDt.setDescription(A_DESCRIPTION);
assertFalse(tpt.compareTo(otherDt) == 0);
otherDt.setProperties(properties);
assertFalse(tpt.compareTo(otherDt) == 0);
@@ -133,12 +124,7 @@ public class JpaToscaPolicyTypeTest {
otherDt.setTriggers(triggers);
assertEquals(0, tpt.compareTo(otherDt));
- try {
- tpt.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tpt.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(6, tpt.getKeys().size());
assertEquals(1, new JpaToscaPolicyType().getKeys().size());
@@ -177,7 +163,7 @@ public class JpaToscaPolicyTypeTest {
tpt.setDescription("");;
assertFalse(tpt.validate(new PfValidationResult()).isValid());
- tpt.setDescription("A Description");
+ tpt.setDescription(A_DESCRIPTION);
assertTrue(tpt.validate(new PfValidationResult()).isValid());
tpt.setDerivedFrom(PfConceptKey.getNullKey());
@@ -185,28 +171,15 @@ public class JpaToscaPolicyTypeTest {
tpt.setDerivedFrom(derivedFromKey);
assertTrue(tpt.validate(new PfValidationResult()).isValid());
- try {
- tpt.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaEntityType<ToscaPolicy>((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaEntityType<ToscaPolicy>((JpaToscaEntityType<ToscaPolicy>) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- JpaToscaEntityType<ToscaPolicy> tet = new JpaToscaEntityType<ToscaPolicy>(tpt.getKey());
+ assertThatThrownBy(() -> tpt.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaEntityType<ToscaPolicy>((PfConceptKey) null))
+ .hasMessage("key is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaEntityType<ToscaPolicy>((JpaToscaEntityType<ToscaPolicy>) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ JpaToscaEntityType<ToscaPolicy> tet = new JpaToscaEntityType<>(tpt.getKey());
assertEquals(-1, tet.compareTo(null));
assertEquals(0, tet.compareTo(tet));
assertFalse(tet.compareTo(tet.getKey()) == 0);
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java
index e02df235f..8288fd80b 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,24 +21,22 @@
package org.onap.policy.models.tosca.simple.concepts;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes;
public class JpaToscaPolicyTypesTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+
@Test
public void testPolicyTypes() {
assertNotNull(new JpaToscaPolicyTypes());
@@ -45,40 +44,18 @@ public class JpaToscaPolicyTypesTest {
assertNotNull(new JpaToscaPolicyTypes(new PfConceptKey(), new TreeMap<PfConceptKey, JpaToscaPolicyType>()));
assertNotNull(new JpaToscaPolicyTypes(new JpaToscaPolicyTypes()));
- try {
- new JpaToscaPolicyTypes((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicyTypes((PfConceptKey) null)).hasMessage(KEY_IS_NULL);
- try {
- new JpaToscaPolicyTypes((JpaToscaPolicyTypes) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicyTypes((JpaToscaPolicyTypes) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
- try {
- new JpaToscaPolicyTypes(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicyTypes(null, null)).hasMessage(KEY_IS_NULL);
- try {
- new JpaToscaPolicyTypes(new PfConceptKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("conceptMap is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicyTypes(new PfConceptKey(), null))
+ .hasMessage("conceptMap is marked @NonNull but is null");
- try {
- new JpaToscaPolicyTypes(null, new TreeMap<PfConceptKey, JpaToscaPolicyType>());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaPolicyTypes(null, new TreeMap<PfConceptKey, JpaToscaPolicyType>()))
+ .hasMessage(KEY_IS_NULL);
List<Map<String, ToscaPolicyType>> ptMapList = new ArrayList<>();
ptMapList.add(new LinkedHashMap<>());
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java
index 706011bcf..70018b62a 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,21 +21,19 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfReferenceKey;
import org.onap.policy.models.base.PfValidationResult;
import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraint;
/**
* DAO test for ToscaProperty.
@@ -43,6 +42,11 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraint;
*/
public class JpaToscaPropertyTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+ private static final String DEFAULT_KEY = "defaultKey";
+ private static final String A_DESCRIPTION = "A Description";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testPropertyPojo() {
assertNotNull(new JpaToscaProperty());
@@ -50,53 +54,30 @@ public class JpaToscaPropertyTest {
assertNotNull(new JpaToscaProperty(new PfReferenceKey(), new PfConceptKey()));
assertNotNull(new JpaToscaProperty(new JpaToscaProperty()));
- try {
- new JpaToscaProperty((PfReferenceKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaProperty(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaProperty(null, new PfConceptKey());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaProperty(new PfReferenceKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("type is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaProperty((JpaToscaProperty) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- PfConceptKey pparentKey = new PfConceptKey("tParentKey", "0.0.1");
+ assertThatThrownBy(() -> new JpaToscaProperty((PfReferenceKey) null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaProperty(null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaProperty(null, new PfConceptKey())).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaProperty(new PfReferenceKey(), null))
+ .hasMessage("type is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaProperty((JpaToscaProperty) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ PfConceptKey pparentKey = new PfConceptKey("tParentKey", VERSION_001);
PfReferenceKey pkey = new PfReferenceKey(pparentKey, "trigger0");
- PfConceptKey ptypeKey = new PfConceptKey("TTypeKey", "0.0.1");
+ PfConceptKey ptypeKey = new PfConceptKey("TTypeKey", VERSION_001);
JpaToscaProperty tp = new JpaToscaProperty(pkey, ptypeKey);
- tp.setDescription("A Description");
- assertEquals("A Description", tp.getDescription());
+ tp.setDescription(A_DESCRIPTION);
+ assertEquals(A_DESCRIPTION, tp.getDescription());
tp.setRequired(false);
assertFalse(tp.isRequired());
- tp.setDefaultValue("defaultKey");
+ tp.setDefaultValue(DEFAULT_KEY);
tp.setStatus(ToscaProperty.Status.SUPPORTED);
@@ -106,7 +87,7 @@ public class JpaToscaPropertyTest {
tp.setConstraints(constraints);
assertEquals(constraints, tp.getConstraints());
- PfConceptKey typeKey = new PfConceptKey("type", "0.0.1");
+ PfConceptKey typeKey = new PfConceptKey("type", VERSION_001);
JpaToscaEntrySchema tes = new JpaToscaEntrySchema(typeKey);
tp.setEntrySchema(tes);
@@ -123,7 +104,7 @@ public class JpaToscaPropertyTest {
assertEquals(0, tp.compareTo(tp));
assertFalse(tp.compareTo(tp.getKey()) == 0);
- PfReferenceKey otherDtKey = new PfReferenceKey("otherDt", "0.0.1", "OtherProperty");
+ PfReferenceKey otherDtKey = new PfReferenceKey("otherDt", VERSION_001, "OtherProperty");
JpaToscaProperty otherDt = new JpaToscaProperty(otherDtKey);
assertFalse(tp.compareTo(otherDt) == 0);
@@ -131,11 +112,11 @@ public class JpaToscaPropertyTest {
assertFalse(tp.compareTo(otherDt) == 0);
otherDt.setType(ptypeKey);
assertFalse(tp.compareTo(otherDt) == 0);
- otherDt.setDescription("A Description");
+ otherDt.setDescription(A_DESCRIPTION);
assertFalse(tp.compareTo(otherDt) == 0);
otherDt.setRequired(false);
assertFalse(tp.compareTo(otherDt) == 0);
- otherDt.setDefaultValue("defaultKey");
+ otherDt.setDefaultValue(DEFAULT_KEY);
assertFalse(tp.compareTo(otherDt) == 0);
otherDt.setStatus(ToscaProperty.Status.SUPPORTED);
assertFalse(tp.compareTo(otherDt) == 0);
@@ -155,12 +136,7 @@ public class JpaToscaPropertyTest {
otherDt.setStatus(ToscaProperty.Status.SUPPORTED);
assertEquals(0, tp.compareTo(otherDt));
- try {
- tp.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tp.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(3, tp.getKeys().size());
assertEquals(2, new JpaToscaProperty().getKeys().size());
@@ -176,7 +152,7 @@ public class JpaToscaPropertyTest {
assertTrue(tp.validate(new PfValidationResult()).isValid());
tp.setDescription("");
assertFalse(tp.validate(new PfValidationResult()).isValid());
- tp.setDescription("A Description");
+ tp.setDescription(A_DESCRIPTION);
assertTrue(tp.validate(new PfValidationResult()).isValid());
tp.setType(null);
@@ -193,7 +169,7 @@ public class JpaToscaPropertyTest {
assertTrue(tp.validate(new PfValidationResult()).isValid());
tp.setDefaultValue("");
assertFalse(tp.validate(new PfValidationResult()).isValid());
- tp.setDefaultValue("defaultKey");
+ tp.setDefaultValue(DEFAULT_KEY);
assertTrue(tp.validate(new PfValidationResult()).isValid());
tp.getConstraints().add(null);
@@ -201,11 +177,6 @@ public class JpaToscaPropertyTest {
tp.getConstraints().remove(null);
assertTrue(tp.validate(new PfValidationResult()).isValid());
- try {
- tp.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tp.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java
index a2a418ef9..df72ce57b 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,25 +21,18 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.Map;
import java.util.TreeMap;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfReferenceKey;
import org.onap.policy.models.base.PfValidationResult;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataTypes;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate;
/**
* DAO test for ToscaDatatype.
@@ -47,6 +41,9 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate;
*/
public class JpaToscaServiceTemplateTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testServiceTemplatePojo() {
assertNotNull(new JpaToscaServiceTemplate());
@@ -54,56 +51,33 @@ public class JpaToscaServiceTemplateTest {
assertNotNull(new JpaToscaServiceTemplate(new PfConceptKey(), ""));
assertNotNull(new JpaToscaServiceTemplate(new JpaToscaServiceTemplate()));
- try {
- new JpaToscaServiceTemplate((PfConceptKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaServiceTemplate(null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaServiceTemplate(null, "");
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaServiceTemplate(new PfConceptKey(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("toscaDefinitionsVersion is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaServiceTemplate((JpaToscaServiceTemplate) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- PfConceptKey tstKey = new PfConceptKey("tst", "0.0.1");
+ assertThatThrownBy(() -> new JpaToscaServiceTemplate((PfConceptKey) null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaServiceTemplate(null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaServiceTemplate(null, "")).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaServiceTemplate(new PfConceptKey(), null))
+ .hasMessage("toscaDefinitionsVersion is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaServiceTemplate((JpaToscaServiceTemplate) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ PfConceptKey tstKey = new PfConceptKey("tst", VERSION_001);
JpaToscaServiceTemplate tst = new JpaToscaServiceTemplate(tstKey, "Tosca Version");
- PfConceptKey dataTypeKey = new PfConceptKey("DataType", "0.0.1");
+ PfConceptKey dataTypeKey = new PfConceptKey("DataType", VERSION_001);
JpaToscaDataType dataType0 = new JpaToscaDataType(dataTypeKey);
- PfConceptKey dtsKey = new PfConceptKey("dts", "0.0.1");
+ PfConceptKey dtsKey = new PfConceptKey("dts", VERSION_001);
Map<PfConceptKey, JpaToscaDataType> dataTypeMap = new TreeMap<>();
dataTypeMap.put(dataTypeKey, dataType0);
JpaToscaDataTypes dataTypes = new JpaToscaDataTypes(dtsKey, dataTypeMap);
tst.setDataTypes(dataTypes);
assertEquals(dataTypes, tst.getDataTypes());
- PfConceptKey policyTypeKey = new PfConceptKey("DataType", "0.0.1");
+ PfConceptKey policyTypeKey = new PfConceptKey("DataType", VERSION_001);
JpaToscaPolicyType policyType0 = new JpaToscaPolicyType(policyTypeKey);
- PfConceptKey ptsKey = new PfConceptKey("dts", "0.0.1");
+ PfConceptKey ptsKey = new PfConceptKey("dts", VERSION_001);
Map<PfConceptKey, JpaToscaPolicyType> policyTypeMap = new TreeMap<>();
policyTypeMap.put(policyTypeKey, policyType0);
JpaToscaPolicyTypes policyTypes = new JpaToscaPolicyTypes(ptsKey, policyTypeMap);
@@ -128,7 +102,7 @@ public class JpaToscaServiceTemplateTest {
assertEquals(0, tst.compareTo(tst));
assertFalse(tst.compareTo(tst.getKey()) == 0);
- PfConceptKey otherDtKey = new PfConceptKey("otherDt", "0.0.1");
+ PfConceptKey otherDtKey = new PfConceptKey("otherDt", VERSION_001);
JpaToscaServiceTemplate otherDt = new JpaToscaServiceTemplate(otherDtKey);
assertFalse(tst.compareTo(otherDt) == 0);
@@ -143,12 +117,7 @@ public class JpaToscaServiceTemplateTest {
otherDt.setTopologyTemplate(ttt);
assertEquals(0, tst.compareTo(otherDt));
- try {
- tst.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tst.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(6, tst.getKeys().size());
assertEquals(1, new JpaToscaServiceTemplate().getKeys().size());
@@ -167,11 +136,6 @@ public class JpaToscaServiceTemplateTest {
tst.setDescription("A Description");
assertTrue(tst.validate(new PfValidationResult()).isValid());
- try {
- tst.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tst.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java
index 354fe8b78..075087774 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -37,6 +38,8 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplates;
public class JpaToscaServiceTemplatesTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+
@Test
public void testServiceTemplates() {
assertNotNull(new JpaToscaServiceTemplates());
@@ -47,7 +50,7 @@ public class JpaToscaServiceTemplatesTest {
assertThatThrownBy(() -> {
new JpaToscaServiceTemplates((PfConceptKey) null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(KEY_IS_NULL);
assertThatThrownBy(() -> {
new JpaToscaServiceTemplates((JpaToscaServiceTemplates) null);
@@ -55,7 +58,7 @@ public class JpaToscaServiceTemplatesTest {
assertThatThrownBy(() -> {
new JpaToscaServiceTemplates(null, null);
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(KEY_IS_NULL);
assertThatThrownBy(() -> {
new JpaToscaServiceTemplates(new PfConceptKey(), null);
@@ -63,7 +66,7 @@ public class JpaToscaServiceTemplatesTest {
assertThatThrownBy(() -> {
new JpaToscaServiceTemplates(null, new TreeMap<PfConceptKey, JpaToscaServiceTemplate>());
- }).hasMessage("key is marked @NonNull but is null");
+ }).hasMessage(KEY_IS_NULL);
List<Map<String, ToscaServiceTemplate>> tsMapList = new ArrayList<>();
tsMapList.add(new LinkedHashMap<>());
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTimeIntervalTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTimeIntervalTest.java
index 707e66dfd..e77f12062 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTimeIntervalTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTimeIntervalTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,19 +21,17 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.Date;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfReferenceKey;
import org.onap.policy.models.base.PfValidationResult;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaTimeInterval;
/**
* DAO test for ToscaTimeInterval.
@@ -41,6 +40,8 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaTimeInterval;
*/
public class JpaToscaTimeIntervalTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+
@Test
public void testTimeIntervalPojo() {
assertNotNull(new JpaToscaTimeInterval());
@@ -48,68 +49,27 @@ public class JpaToscaTimeIntervalTest {
assertNotNull(new JpaToscaTimeInterval(new PfReferenceKey(), new Date(), new Date()));
assertNotNull(new JpaToscaTimeInterval(new JpaToscaTimeInterval()));
- try {
- new JpaToscaTimeInterval((PfReferenceKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval(null, null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval(null, null, new Date());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval(null, new Date(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval(null, new Date(), new Date());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval(new PfReferenceKey(), null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("startTime is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval(new PfReferenceKey(), null, new Date());
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("startTime is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval(new PfReferenceKey(), new Date(), null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("endTime is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTimeInterval((JpaToscaTimeInterval) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> new JpaToscaTimeInterval((PfReferenceKey) null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval(null, null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval(null, null, new Date())).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval(null, new Date(), null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval(null, new Date(), new Date())).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval(new PfReferenceKey(), null, null))
+ .hasMessage("startTime is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval(new PfReferenceKey(), null, new Date()))
+ .hasMessage("startTime is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval(new PfReferenceKey(), new Date(), null))
+ .hasMessage("endTime is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaTimeInterval((JpaToscaTimeInterval) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
PfConceptKey ttiParentKey = new PfConceptKey("tParentKey", "0.0.1");
PfReferenceKey ttiKey = new PfReferenceKey(ttiParentKey, "trigger0");
@@ -141,12 +101,7 @@ public class JpaToscaTimeIntervalTest {
otherDt.setEndTime(endTime);
assertEquals(0, tti.compareTo(otherDt));
- try {
- tti.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tti.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(1, tti.getKeys().size());
assertEquals(1, new JpaToscaTimeInterval().getKeys().size());
@@ -172,11 +127,6 @@ public class JpaToscaTimeIntervalTest {
tti.setEndTime(endTime);
assertTrue(tti.validate(new PfValidationResult()).isValid());
- try {
- tti.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tti.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java
index 61ce3d077..7712a64c0 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,23 +21,19 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.Map;
import java.util.TreeMap;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfReferenceKey;
import org.onap.policy.models.base.PfValidationResult;
import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate;
/**
* DAO test for ToscaDatatype.
@@ -45,6 +42,9 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate;
*/
public class JpaToscaTopologyTemplateTest {
+ private static final String A_DESCRIPTION = "A Description";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testTopologyTemplatePojo() {
assertNotNull(new JpaToscaTopologyTemplate());
@@ -52,31 +52,23 @@ public class JpaToscaTopologyTemplateTest {
assertNotNull(new JpaToscaTopologyTemplate(new JpaToscaTopologyTemplate()));
assertNotNull(new JpaToscaTopologyTemplate(new ToscaTopologyTemplate()));
- try {
- new JpaToscaTopologyTemplate((PfReferenceKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTopologyTemplate((JpaToscaTopologyTemplate) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- PfReferenceKey tttKey = new PfReferenceKey("tst", "0.0.1", "ttt");
+ assertThatThrownBy(() -> new JpaToscaTopologyTemplate((PfReferenceKey) null))
+ .hasMessage("key is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaTopologyTemplate((JpaToscaTopologyTemplate) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ PfReferenceKey tttKey = new PfReferenceKey("tst", VERSION_001, "ttt");
JpaToscaTopologyTemplate ttt = new JpaToscaTopologyTemplate(tttKey);
- ttt.setDescription("A Description");
- assertEquals("A Description", ttt.getDescription());
+ ttt.setDescription(A_DESCRIPTION);
+ assertEquals(A_DESCRIPTION, ttt.getDescription());
- PfConceptKey policy0TypeKey = new PfConceptKey("Policy0Type", "0.0.1");
- PfConceptKey policy0Key = new PfConceptKey("Policy0", "0.0.1");
+ PfConceptKey policy0TypeKey = new PfConceptKey("Policy0Type", VERSION_001);
+ PfConceptKey policy0Key = new PfConceptKey("Policy0", VERSION_001);
JpaToscaPolicy policy0 = new JpaToscaPolicy(policy0Key, policy0TypeKey);
- PfConceptKey polsKey = new PfConceptKey("pols", "0.0.1");
+ PfConceptKey polsKey = new PfConceptKey("pols", VERSION_001);
Map<PfConceptKey, JpaToscaPolicy> policyMap = new TreeMap<>();
policyMap.put(policy0Key, policy0);
JpaToscaPolicies policies = new JpaToscaPolicies(polsKey, policyMap);
@@ -95,23 +87,18 @@ public class JpaToscaTopologyTemplateTest {
assertEquals(0, ttt.compareTo(ttt));
assertFalse(ttt.compareTo(ttt.getKey()) == 0);
- PfReferenceKey otherDtKey = new PfReferenceKey("otherSt", "0.0.1", "otherDt");
+ PfReferenceKey otherDtKey = new PfReferenceKey("otherSt", VERSION_001, "otherDt");
JpaToscaTopologyTemplate otherDt = new JpaToscaTopologyTemplate(otherDtKey);
assertFalse(ttt.compareTo(otherDt) == 0);
otherDt.setKey(tttKey);
assertFalse(ttt.compareTo(otherDt) == 0);
- otherDt.setDescription("A Description");
+ otherDt.setDescription(A_DESCRIPTION);
assertFalse(ttt.compareTo(otherDt) == 0);
otherDt.setPolicies(policies);
assertEquals(0, ttt.compareTo(otherDt));
- try {
- ttt.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> ttt.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(4, ttt.getKeys().size());
assertEquals(1, new JpaToscaTopologyTemplate().getKeys().size());
@@ -132,14 +119,9 @@ public class JpaToscaTopologyTemplateTest {
assertTrue(ttt.validate(new PfValidationResult()).isValid());
ttt.setDescription("");
assertFalse(ttt.validate(new PfValidationResult()).isValid());
- ttt.setDescription("A Description");
+ ttt.setDescription(A_DESCRIPTION);
assertTrue(ttt.validate(new PfValidationResult()).isValid());
- try {
- ttt.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> ttt.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTriggerTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTriggerTest.java
index 0f69cb3c9..97c1b6fb7 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTriggerTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTriggerTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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,22 +21,18 @@
package org.onap.policy.models.tosca.simple.concepts;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.time.Duration;
import java.util.Date;
-
import org.junit.Test;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfReferenceKey;
import org.onap.policy.models.base.PfValidationResult;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaEventFilter;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaTimeInterval;
-import org.onap.policy.models.tosca.simple.concepts.JpaToscaTrigger;
/**
* DAO test for ToscaTrigger.
@@ -44,86 +41,52 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaTrigger;
*/
public class JpaToscaTriggerTest {
+ private static final String KEY_IS_NULL = "key is marked @NonNull but is null";
+ private static final String EVENT_TYPE = "EventType";
+ private static final String ACTION = "Action";
+ private static final String A_METHOD = "A Method";
+ private static final String A_DESCRIPTION = "A Description";
+ private static final String VERSION_001 = "0.0.1";
+
@Test
public void testTriggerPojo() {
assertNotNull(new JpaToscaTrigger());
assertNotNull(new JpaToscaTrigger(new PfReferenceKey()));
- assertNotNull(new JpaToscaTrigger(new PfReferenceKey(), "EventType", "Action"));
+ assertNotNull(new JpaToscaTrigger(new PfReferenceKey(), EVENT_TYPE, ACTION));
assertNotNull(new JpaToscaTrigger(new JpaToscaTrigger()));
- try {
- new JpaToscaTrigger((PfReferenceKey) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger(null, null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger(null, "EventType", null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger(null, "EventType", "Action");
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger(null, null, "Action");
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("key is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger(new PfReferenceKey(), null, null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("eventType is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger(new PfReferenceKey(), "EventType", null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("action is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger(new PfReferenceKey(), null, "Action");
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("eventType is marked @NonNull but is null", exc.getMessage());
- }
-
- try {
- new JpaToscaTrigger((JpaToscaTrigger) null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage());
- }
-
- PfConceptKey tparentKey = new PfConceptKey("tParentKey", "0.0.1");
+ assertThatThrownBy(() -> new JpaToscaTrigger((PfReferenceKey) null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTrigger(null, null, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTrigger(null, EVENT_TYPE, null)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTrigger(null, EVENT_TYPE, ACTION)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTrigger(null, null, ACTION)).hasMessage(KEY_IS_NULL);
+
+ assertThatThrownBy(() -> new JpaToscaTrigger(new PfReferenceKey(), null, null))
+ .hasMessage("eventType is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaTrigger(new PfReferenceKey(), EVENT_TYPE, null))
+ .hasMessage("action is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaTrigger(new PfReferenceKey(), null, ACTION))
+ .hasMessage("eventType is marked @NonNull but is null");
+
+ assertThatThrownBy(() -> new JpaToscaTrigger((JpaToscaTrigger) null))
+ .hasMessage("copyConcept is marked @NonNull but is null");
+
+ PfConceptKey tparentKey = new PfConceptKey("tParentKey", VERSION_001);
PfReferenceKey tkey = new PfReferenceKey(tparentKey, "trigger0");
- JpaToscaTrigger tdt = new JpaToscaTrigger(tkey, "EventType", "Action");
+ JpaToscaTrigger tdt = new JpaToscaTrigger(tkey, EVENT_TYPE, ACTION);
JpaToscaTimeInterval schedule =
new JpaToscaTimeInterval(new PfReferenceKey(tkey, "sched"), new Date(), new Date());
tdt.setSchedule(schedule);
JpaToscaEventFilter targetFilter =
- new JpaToscaEventFilter(new PfReferenceKey(tkey, "filter"), new PfConceptKey("NodeName", "0.0.1"));
+ new JpaToscaEventFilter(new PfReferenceKey(tkey, "filter"), new PfConceptKey("NodeName", VERSION_001));
tdt.setTargetFilter(targetFilter);
JpaToscaConstraintLogical lsc = new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "hello");
@@ -135,11 +98,11 @@ public class JpaToscaTriggerTest {
tdt.setPeriod(Duration.ZERO);
assertEquals(Duration.ZERO, tdt.getPeriod());
- tdt.setDescription("A Description");
- assertEquals("A Description", tdt.getDescription());
+ tdt.setDescription(A_DESCRIPTION);
+ assertEquals(A_DESCRIPTION, tdt.getDescription());
- tdt.setMethod("A Method");
- assertEquals("A Method", tdt.getMethod());
+ tdt.setMethod(A_METHOD);
+ assertEquals(A_METHOD, tdt.getMethod());
JpaToscaTrigger tdtClone0 = new JpaToscaTrigger(tdt);
assertEquals(tdt, tdtClone0);
@@ -154,15 +117,15 @@ public class JpaToscaTriggerTest {
assertEquals(0, tdt.compareTo(tdt));
assertFalse(tdt.compareTo(tdt.getKey()) == 0);
- PfReferenceKey otherDtKey = new PfReferenceKey("otherDt", "0.0.1", "OtherTrigger");
+ PfReferenceKey otherDtKey = new PfReferenceKey("otherDt", VERSION_001, "OtherTrigger");
JpaToscaTrigger otherDt = new JpaToscaTrigger(otherDtKey);
assertFalse(tdt.compareTo(otherDt) == 0);
otherDt.setKey(tkey);
assertFalse(tdt.compareTo(otherDt) == 0);
- otherDt.setDescription("A Description");
+ otherDt.setDescription(A_DESCRIPTION);
assertFalse(tdt.compareTo(otherDt) == 0);
- otherDt.setEventType("EventType");
+ otherDt.setEventType(EVENT_TYPE);
assertFalse(tdt.compareTo(otherDt) == 0);
otherDt.setSchedule(schedule);
assertFalse(tdt.compareTo(otherDt) == 0);
@@ -174,9 +137,9 @@ public class JpaToscaTriggerTest {
assertFalse(tdt.compareTo(otherDt) == 0);
otherDt.setPeriod(Duration.ZERO);
assertFalse(tdt.compareTo(otherDt) == 0);
- otherDt.setMethod("A Method");
+ otherDt.setMethod(A_METHOD);
assertFalse(tdt.compareTo(otherDt) == 0);
- otherDt.setAction("Action");
+ otherDt.setAction(ACTION);
assertEquals(0, tdt.compareTo(otherDt));
otherDt.setEvaluations(100);
@@ -184,12 +147,7 @@ public class JpaToscaTriggerTest {
otherDt.setEvaluations(0);
assertEquals(0, tdt.compareTo(otherDt));
- try {
- tdt.copyTo(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("target is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tdt.copyTo(null)).hasMessage("target is marked @NonNull but is null");
assertEquals(4, tdt.getKeys().size());
assertEquals(1, new JpaToscaTrigger().getKeys().size());
@@ -205,7 +163,7 @@ public class JpaToscaTriggerTest {
assertTrue(tdt.validate(new PfValidationResult()).isValid());
tdt.setDescription("");
assertFalse(tdt.validate(new PfValidationResult()).isValid());
- tdt.setDescription("A Description");
+ tdt.setDescription(A_DESCRIPTION);
assertTrue(tdt.validate(new PfValidationResult()).isValid());
tdt.setEvaluations(-1);
@@ -217,14 +175,9 @@ public class JpaToscaTriggerTest {
assertTrue(tdt.validate(new PfValidationResult()).isValid());
tdt.setMethod("");
assertFalse(tdt.validate(new PfValidationResult()).isValid());
- tdt.setMethod("A Method");
+ tdt.setMethod(A_METHOD);
assertTrue(tdt.validate(new PfValidationResult()).isValid());
- try {
- tdt.validate(null);
- fail("test should throw an exception");
- } catch (Exception exc) {
- assertEquals("resultIn is marked @NonNull but is null", exc.getMessage());
- }
+ assertThatThrownBy(() -> tdt.validate(null)).hasMessage("resultIn is marked @NonNull but is null");
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java
index f8e422160..4603a168f 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -35,6 +36,7 @@ public class DummyToscaConstraint extends JpaToscaConstraint {
* The Default Constructor creates a {@link DummyToscaConstraint} object with a null key.
*/
public DummyToscaConstraint() {
+ // do nothing
}
@Override
@@ -44,6 +46,7 @@ public class DummyToscaConstraint extends JpaToscaConstraint {
@Override
public void fromAuthorative(ToscaConstraint authorativeConcept) {
+ // do nothing
}
@Override
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java
index 4d71d0ddd..5e7e8fd5c 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019 AT&T 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.
@@ -24,10 +25,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.util.Properties;
-
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.junit.After;
import org.junit.Before;
@@ -54,6 +53,9 @@ import org.yaml.snakeyaml.Yaml;
* @author Liam Fallon (liam.fallon@est.tech)
*/
public class SimpleToscaProviderTest {
+ private static final String TEMPLATE_IS_NULL = "serviceTemplate is marked @NonNull but is null";
+ private static final String VCPE_INPUT_JSON = "policies/vCPE.policy.monitoring.input.tosca.json";
+ private static final String DAO_IS_NULL = "dao is marked @NonNull but is null";
private PfDao pfDao;
private StandardCoder standardCoder;
@@ -92,14 +94,14 @@ public class SimpleToscaProviderTest {
}
@After
- public void teardown() throws Exception {
+ public void teardown() {
pfDao.close();
}
@Test
public void testPoliciesGet() throws Exception {
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
ToscaServiceTemplate.class);
createPolicyTypes();
@@ -126,7 +128,7 @@ public class SimpleToscaProviderTest {
@Test
public void testPolicyCreate() throws Exception {
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
ToscaServiceTemplate.class);
createPolicyTypes();
@@ -144,7 +146,7 @@ public class SimpleToscaProviderTest {
@Test
public void testPolicyUpdate() throws Exception {
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
ToscaServiceTemplate.class);
createPolicyTypes();
@@ -162,7 +164,7 @@ public class SimpleToscaProviderTest {
@Test
public void testPoliciesDelete() throws Exception {
ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(
- ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ResourceUtils.getResourceAsString(VCPE_INPUT_JSON),
ToscaServiceTemplate.class);
createPolicyTypes();
@@ -189,71 +191,58 @@ public class SimpleToscaProviderTest {
}
@Test
- public void testAssertPoliciesExist() throws PfModelException {
+ public void testAssertPoliciesExist() {
JpaToscaServiceTemplate testServiceTemplate = new JpaToscaServiceTemplate();
- try {
- new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("topology template not specified on service template", exc.getMessage());
- }
+ assertThatThrownBy(() -> new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate))
+ .hasMessage("topology template not specified on service template");
testServiceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate());
- try {
- new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("no policies specified on topology template of service template", exc.getMessage());
- }
+ assertThatThrownBy(() -> new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate))
+ .hasMessage("no policies specified on topology template of service template");
testServiceTemplate.getTopologyTemplate().setPolicies(new JpaToscaPolicies());
- try {
- new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate);
- fail("test should throw an exception here");
- } catch (Exception exc) {
- assertEquals("list of policies specified on topology template of service template is empty",
- exc.getMessage());
- }
+ assertThatThrownBy(() -> new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate))
+ .hasMessage("list of policies specified on topology template of service template is empty");
}
@Test
public void testNonNulls() {
assertThatThrownBy(() -> {
new SimpleToscaProvider().getPolicyTypes(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().createPolicyTypes(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().createPolicyTypes(null, new JpaToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().createPolicyTypes(pfDao, null);
- }).hasMessage("serviceTemplate is marked @NonNull but is null");
+ }).hasMessage(TEMPLATE_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().updatePolicyTypes(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().updatePolicyTypes(null, new JpaToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().updatePolicyTypes(pfDao, null);
- }).hasMessage("serviceTemplate is marked @NonNull but is null");
+ }).hasMessage(TEMPLATE_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().deletePolicyType(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().deletePolicyType(null, new PfConceptKey());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().deletePolicyType(pfDao, null);
@@ -261,39 +250,39 @@ public class SimpleToscaProviderTest {
assertThatThrownBy(() -> {
new SimpleToscaProvider().getPolicies(null, null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().createPolicies(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().createPolicies(null, new JpaToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().createPolicies(pfDao, null);
- }).hasMessage("serviceTemplate is marked @NonNull but is null");
+ }).hasMessage(TEMPLATE_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().updatePolicies(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().updatePolicies(null, new JpaToscaServiceTemplate());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().updatePolicies(pfDao, null);
- }).hasMessage("serviceTemplate is marked @NonNull but is null");
+ }).hasMessage(TEMPLATE_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().deletePolicy(null, null);
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().deletePolicy(null, new PfConceptKey());
- }).hasMessage("dao is marked @NonNull but is null");
+ }).hasMessage(DAO_IS_NULL);
assertThatThrownBy(() -> {
new SimpleToscaProvider().deletePolicy(pfDao, null);
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java
index f05e2e6ef..f5722dded 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java
@@ -53,6 +53,34 @@ import org.yaml.snakeyaml.Yaml;
*/
public class MonitoringPolicySerializationTest {
+ private static final String VERSION = "version";
+
+ private static final String YAML_VERSION = "tosca_simple_yaml_1_0_0";
+
+ private static final String DEFINITION_VERSION = "tosca_definitions_version";
+
+ private static final String TOPOLOGY_TEMPLATE = "topology_template";
+
+ private static final String TCA_POLICY = "tca_policy";
+
+ private static final String PROPERTIES2 = "properties";
+
+ private static final String POLICY_ID = "policy-id";
+
+ private static final String POLICIES = "policies";
+
+ private static final String POLICY3 = "onap.vfirewall.tca";
+
+ private static final String POLICY2 = "onap.scaleout.tca";
+
+ private static final String POLICY1 = "onap.restart.tca";
+
+ private static final String TYPE1 = "onap.policies.monitoring.cdap.tca.hi.lo.app";
+
+ private static final String METADATA = "metadata";
+
+ private static final String VERSION_100 = "1.0.0";
+
private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPolicySerializationTest.class);
private static final String VCPE_MON_INPUT_JSON = "policies/vCPE.policy.monitoring.input.tosca.json";
@@ -70,30 +98,24 @@ public class MonitoringPolicySerializationTest {
}
@Test
- public void testDeserialization() {
- try {
- // vCPE
- JpaToscaServiceTemplate serviceTemplateFromJson = deserializeMonitoringInputJson(VCPE_MON_INPUT_JSON);
- verifyVcpeMonitoringInputDeserialization(serviceTemplateFromJson);
- JpaToscaServiceTemplate serviceTemplateFromYaml = deserializeMonitoringInputYaml(VCPE_MON_INPUT_YAML);
- assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0);
-
- // vDNS
- serviceTemplateFromJson = deserializeMonitoringInputJson(VDNS_MON_INPUT_JSON);
- verifyVdnsMonitoringInputDeserialization(serviceTemplateFromJson);
- serviceTemplateFromYaml = deserializeMonitoringInputYaml(VDNS_MON_INPUT_YAML);
- assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0);
-
- // vFirewall
- serviceTemplateFromJson = deserializeMonitoringInputJson(VFW_MON_INPUT_JSON);
- verifyVfwMonitoringInputDeserialization(serviceTemplateFromJson);
- serviceTemplateFromYaml = deserializeMonitoringInputYaml(VFW_MON_INPUT_YAML);
- assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0);
-
- } catch (Exception e) {
- LOGGER.warn("No exception should be thrown", e);
- fail("No exception should be thrown");
- }
+ public void testDeserialization() throws Exception {
+ // vCPE
+ JpaToscaServiceTemplate serviceTemplateFromJson = deserializeMonitoringInputJson(VCPE_MON_INPUT_JSON);
+ verifyVcpeMonitoringInputDeserialization(serviceTemplateFromJson);
+ JpaToscaServiceTemplate serviceTemplateFromYaml = deserializeMonitoringInputYaml(VCPE_MON_INPUT_YAML);
+ assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0);
+
+ // vDNS
+ serviceTemplateFromJson = deserializeMonitoringInputJson(VDNS_MON_INPUT_JSON);
+ verifyVdnsMonitoringInputDeserialization(serviceTemplateFromJson);
+ serviceTemplateFromYaml = deserializeMonitoringInputYaml(VDNS_MON_INPUT_YAML);
+ assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0);
+
+ // vFirewall
+ serviceTemplateFromJson = deserializeMonitoringInputJson(VFW_MON_INPUT_JSON);
+ verifyVfwMonitoringInputDeserialization(serviceTemplateFromJson);
+ serviceTemplateFromYaml = deserializeMonitoringInputYaml(VFW_MON_INPUT_YAML);
+ assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0);
}
@Test
@@ -156,7 +178,7 @@ public class MonitoringPolicySerializationTest {
assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid());
// Check tosca_definitions_version
- assertEquals("tosca_simple_yaml_1_0_0",
+ assertEquals(YAML_VERSION,
serviceTemplate.getToscaDefinitionsVersion());
Map<PfConceptKey, JpaToscaPolicy> policiesConceptMap = serviceTemplate.getTopologyTemplate()
@@ -164,20 +186,20 @@ public class MonitoringPolicySerializationTest {
// Check policies
assertTrue(policiesConceptMap.size() == 1);
- assertEquals("onap.restart.tca", policiesConceptMap.keySet().iterator().next().getName());
+ assertEquals(POLICY1, policiesConceptMap.keySet().iterator().next().getName());
assertEquals("onap.restart.tca:1.0.0",
- serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca").getId());
+ serviceTemplate.getTopologyTemplate().getPolicies().get(POLICY1).getId());
JpaToscaPolicy policyVal = policiesConceptMap.values().iterator().next();
// Check metadata
assertTrue(policyVal.getMetadata().size() == 2);
- assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey());
- assertEquals("onap.restart.tca", policyVal.getMetadata().entrySet().iterator().next().getValue());
+ assertEquals(POLICY_ID, policyVal.getMetadata().entrySet().iterator().next().getKey());
+ assertEquals(POLICY1, policyVal.getMetadata().entrySet().iterator().next().getValue());
// Check properties
assertTrue(policiesConceptMap.values().iterator().next().getProperties().size() == 1);
- assertEquals("tca_policy", policyVal.getProperties().keySet().iterator().next());
+ assertEquals(TCA_POLICY, policyVal.getProperties().keySet().iterator().next());
assertNotNull(policyVal.getProperties().values().iterator().next());
}
@@ -189,7 +211,7 @@ public class MonitoringPolicySerializationTest {
assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid());
// Check tosca_definitions_version
- assertEquals("tosca_simple_yaml_1_0_0",
+ assertEquals(YAML_VERSION,
serviceTemplate.getToscaDefinitionsVersion());
Map<PfConceptKey, JpaToscaPolicy> policiesConceptMap = serviceTemplate.getTopologyTemplate()
@@ -197,20 +219,20 @@ public class MonitoringPolicySerializationTest {
// Check policies
assertTrue(policiesConceptMap.size() == 1);
- assertEquals("onap.scaleout.tca", policiesConceptMap.keySet().iterator().next().getName());
+ assertEquals(POLICY2, policiesConceptMap.keySet().iterator().next().getName());
assertEquals("onap.scaleout.tca:1.0.0",
- serviceTemplate.getTopologyTemplate().getPolicies().get("onap.scaleout.tca").getId());
+ serviceTemplate.getTopologyTemplate().getPolicies().get(POLICY2).getId());
JpaToscaPolicy policyVal = policiesConceptMap.values().iterator().next();
// Check metadata
assertTrue(policyVal.getMetadata().size() == 2);
- assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey());
- assertEquals("onap.scaleout.tca", policyVal.getMetadata().entrySet().iterator().next().getValue());
+ assertEquals(POLICY_ID, policyVal.getMetadata().entrySet().iterator().next().getKey());
+ assertEquals(POLICY2, policyVal.getMetadata().entrySet().iterator().next().getValue());
// Check properties
assertTrue(policiesConceptMap.values().iterator().next().getProperties().size() == 1);
- assertEquals("tca_policy", policyVal.getProperties().keySet().iterator().next());
+ assertEquals(TCA_POLICY, policyVal.getProperties().keySet().iterator().next());
assertNotNull(policyVal.getProperties().values().iterator().next());
}
@@ -222,7 +244,7 @@ public class MonitoringPolicySerializationTest {
assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid());
// Check tosca_definitions_version
- assertEquals("tosca_simple_yaml_1_0_0",
+ assertEquals(YAML_VERSION,
serviceTemplate.getToscaDefinitionsVersion());
Map<PfConceptKey, JpaToscaPolicy> policiesConceptMap = serviceTemplate.getTopologyTemplate()
@@ -230,78 +252,78 @@ public class MonitoringPolicySerializationTest {
// Check policies
assertTrue(policiesConceptMap.size() == 1);
- assertEquals("onap.vfirewall.tca", policiesConceptMap.keySet().iterator().next().getName());
+ assertEquals(POLICY3, policiesConceptMap.keySet().iterator().next().getName());
assertEquals("onap.vfirewall.tca:1.0.0",
- serviceTemplate.getTopologyTemplate().getPolicies().get("onap.vfirewall.tca").getId());
+ serviceTemplate.getTopologyTemplate().getPolicies().get(POLICY3).getId());
JpaToscaPolicy policyVal = policiesConceptMap.values().iterator().next();
// Check metadata
assertTrue(policyVal.getMetadata().size() == 2);
- assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey());
- assertEquals("onap.vfirewall.tca", policyVal.getMetadata().entrySet().iterator().next().getValue());
+ assertEquals(POLICY_ID, policyVal.getMetadata().entrySet().iterator().next().getKey());
+ assertEquals(POLICY3, policyVal.getMetadata().entrySet().iterator().next().getValue());
// Check properties
assertTrue(policiesConceptMap.values().iterator().next().getProperties().size() == 1);
- assertEquals("tca_policy", policyVal.getProperties().keySet().iterator().next());
+ assertEquals(TCA_POLICY, policyVal.getProperties().keySet().iterator().next());
assertNotNull(policyVal.getProperties().values().iterator().next());
}
private void verifyVcpeMonitoringOutputserialization(String serializedServiceTemplate) {
JsonObject serviceTemplateJsonObject = new JsonParser().parse(serializedServiceTemplate).getAsJsonObject();
- assertEquals("tosca_simple_yaml_1_0_0", serviceTemplateJsonObject.get("tosca_definitions_version")
+ assertEquals(YAML_VERSION, serviceTemplateJsonObject.get(DEFINITION_VERSION)
.getAsString());
- JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get("topology_template")
+ JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get(TOPOLOGY_TEMPLATE)
.getAsJsonObject();
- JsonArray policiesJsonArray = topologyTemplateJsonObject.get("policies").getAsJsonArray();
+ JsonArray policiesJsonArray = topologyTemplateJsonObject.get(POLICIES).getAsJsonArray();
assertTrue(policiesJsonArray.size() == 1);
JsonObject policy = policiesJsonArray.iterator().next().getAsJsonObject();
- assertNotNull(policy.get("onap.restart.tca"));
- JsonObject policyVal = policy.get("onap.restart.tca").getAsJsonObject();
- assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", policyVal.get("type").getAsString());
- assertEquals("1.0.0", policyVal.get("version").getAsString());
- assertEquals("onap.restart.tca", policyVal.get("metadata").getAsJsonObject().get("policy-id")
+ assertNotNull(policy.get(POLICY1));
+ JsonObject policyVal = policy.get(POLICY1).getAsJsonObject();
+ assertEquals(TYPE1, policyVal.get("type").getAsString());
+ assertEquals(VERSION_100, policyVal.get(VERSION).getAsString());
+ assertEquals(POLICY1, policyVal.get(METADATA).getAsJsonObject().get(POLICY_ID)
.getAsString());
- JsonObject properties = policyVal.get("properties").getAsJsonObject();
- assertNotNull(properties.get("tca_policy"));
+ JsonObject properties = policyVal.get(PROPERTIES2).getAsJsonObject();
+ assertNotNull(properties.get(TCA_POLICY));
}
private void verifyVdnsMonitoringOutputserialization(String serializedServiceTemplate) {
JsonObject serviceTemplateJsonObject = new JsonParser().parse(serializedServiceTemplate).getAsJsonObject();
- assertEquals("tosca_simple_yaml_1_0_0", serviceTemplateJsonObject.get("tosca_definitions_version")
+ assertEquals(YAML_VERSION, serviceTemplateJsonObject.get(DEFINITION_VERSION)
.getAsString());
- JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get("topology_template").getAsJsonObject();
- JsonArray policiesJsonArray = topologyTemplateJsonObject.get("policies").getAsJsonArray();
+ JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get(TOPOLOGY_TEMPLATE).getAsJsonObject();
+ JsonArray policiesJsonArray = topologyTemplateJsonObject.get(POLICIES).getAsJsonArray();
assertTrue(policiesJsonArray.size() == 1);
JsonObject policy = policiesJsonArray.iterator().next().getAsJsonObject();
- assertNotNull(policy.get("onap.scaleout.tca"));
- JsonObject policyVal = policy.get("onap.scaleout.tca").getAsJsonObject();
- assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", policyVal.get("type").getAsString());
- assertEquals("1.0.0", policyVal.get("version").getAsString());
- assertEquals("onap.scaleout.tca", policyVal.get("metadata").getAsJsonObject().get("policy-id")
+ assertNotNull(policy.get(POLICY2));
+ JsonObject policyVal = policy.get(POLICY2).getAsJsonObject();
+ assertEquals(TYPE1, policyVal.get("type").getAsString());
+ assertEquals(VERSION_100, policyVal.get(VERSION).getAsString());
+ assertEquals(POLICY2, policyVal.get(METADATA).getAsJsonObject().get(POLICY_ID)
.getAsString());
- JsonObject properties = policyVal.get("properties").getAsJsonObject();
- assertNotNull(properties.get("tca_policy"));
+ JsonObject properties = policyVal.get(PROPERTIES2).getAsJsonObject();
+ assertNotNull(properties.get(TCA_POLICY));
}
private void verifyVfwMonitoringOutputserialization(String serializedServiceTemplate) {
JsonObject serviceTemplateJsonObject = new JsonParser().parse(serializedServiceTemplate).getAsJsonObject();
- assertEquals("tosca_simple_yaml_1_0_0", serviceTemplateJsonObject.get("tosca_definitions_version")
+ assertEquals(YAML_VERSION, serviceTemplateJsonObject.get(DEFINITION_VERSION)
.getAsString());
- JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get("topology_template").getAsJsonObject();
- JsonArray policiesJsonArray = topologyTemplateJsonObject.get("policies").getAsJsonArray();
+ JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get(TOPOLOGY_TEMPLATE).getAsJsonObject();
+ JsonArray policiesJsonArray = topologyTemplateJsonObject.get(POLICIES).getAsJsonArray();
assertTrue(policiesJsonArray.size() == 1);
JsonObject policy = policiesJsonArray.iterator().next().getAsJsonObject();
- assertNotNull(policy.get("onap.vfirewall.tca"));
- JsonObject policyVal = policy.get("onap.vfirewall.tca").getAsJsonObject();
- assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", policyVal.get("type").getAsString());
- assertEquals("1.0.0", policyVal.get("version").getAsString());
- assertEquals("onap.vfirewall.tca", policyVal.get("metadata").getAsJsonObject().get("policy-id")
+ assertNotNull(policy.get(POLICY3));
+ JsonObject policyVal = policy.get(POLICY3).getAsJsonObject();
+ assertEquals(TYPE1, policyVal.get("type").getAsString());
+ assertEquals(VERSION_100, policyVal.get(VERSION).getAsString());
+ assertEquals(POLICY3, policyVal.get(METADATA).getAsJsonObject().get(POLICY_ID)
.getAsString());
- JsonObject properties = policyVal.get("properties").getAsJsonObject();
- assertNotNull(properties.get("tca_policy"));
+ JsonObject properties = policyVal.get(PROPERTIES2).getAsJsonObject();
+ assertNotNull(properties.get(TCA_POLICY));
}
}
diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java
index 0e053f182..aa4fc952c 100644
--- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java
+++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java
@@ -55,6 +55,24 @@ import org.yaml.snakeyaml.Yaml;
*/
public class MonitoringPolicyTypeSerializationTest {
+ private static final String DATATYPE_ROOT = "tosca.datatypes.Root";
+
+ private static final String STRING_TEXT = "string";
+
+ private static final String DCAE = "onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server";
+
+ private static final String MONITORING = "onap.policies.Monitoring";
+
+ private static final String THRESHOLDS = "onap.datatypes.monitoring.thresholds";
+
+ private static final String TCA = "onap.datatypes.monitoring.tca_policy";
+
+ private static final String METRICS = "onap.datatypes.monitoring.metricsPerEventName";
+
+ private static final String VERSION_100 = "1.0.0";
+
+ private static final String VERSION_000 = "0.0.0";
+
private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPolicyTypeSerializationTest.class);
private static final String MONITORING_TCA_YAML = "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml";
@@ -69,20 +87,14 @@ public class MonitoringPolicyTypeSerializationTest {
}
@Test
- public void testDeserialization() {
- try {
- // TCA
- JpaToscaServiceTemplate serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_TCA_YAML);
- verifyTcaInputDeserialization(serviceTemplateFromYaml);
-
- // Collector
- serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_COLLECTORS_YAML);
- verifyCollectorInputDeserialization(serviceTemplateFromYaml);
-
- } catch (Exception e) {
- LOGGER.warn("No exception should be thrown", e);
- fail("No exception should be thrown");
- }
+ public void testDeserialization() throws Exception {
+ // TCA
+ JpaToscaServiceTemplate serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_TCA_YAML);
+ verifyTcaInputDeserialization(serviceTemplateFromYaml);
+
+ // Collector
+ serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_COLLECTORS_YAML);
+ verifyCollectorInputDeserialization(serviceTemplateFromYaml);
}
@Test
@@ -148,27 +160,27 @@ public class MonitoringPolicyTypeSerializationTest {
Iterator<Entry<PfConceptKey, JpaToscaPolicyType>> policyTypesIter = policyTypesConceptMap.entrySet().iterator();
Entry<PfConceptKey, JpaToscaPolicyType> firstPolicyType = policyTypesIter.next();
- assertEquals("onap.policies.Monitoring", firstPolicyType.getKey().getName());
- assertEquals("0.0.0", firstPolicyType.getKey().getVersion());
+ assertEquals(MONITORING, firstPolicyType.getKey().getName());
+ assertEquals(VERSION_000, firstPolicyType.getKey().getVersion());
assertEquals("tosca.policies.Root", firstPolicyType.getValue().getDerivedFrom().getName());
assertEquals("a base policy type for all policies that governs monitoring provisioning",
firstPolicyType.getValue().getDescription());
Entry<PfConceptKey, JpaToscaPolicyType> secondPolicyType = policyTypesIter.next();
assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", secondPolicyType.getKey().getName());
- assertEquals("1.0.0", secondPolicyType.getKey().getVersion());
- assertEquals("onap.policies.Monitoring", secondPolicyType.getValue().getDerivedFrom().getName());
+ assertEquals(VERSION_100, secondPolicyType.getKey().getVersion());
+ assertEquals(MONITORING, secondPolicyType.getValue().getDerivedFrom().getName());
assertTrue(secondPolicyType.getValue().getProperties().size() == 1);
JpaToscaProperty property = secondPolicyType.getValue().getProperties().values().iterator().next();
assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", property.getKey().getParentKeyName());
- assertEquals("1.0.0", property.getKey().getParentKeyVersion());
+ assertEquals(VERSION_100, property.getKey().getParentKeyVersion());
assertEquals("tca_policy", property.getKey().getLocalName());
assertEquals("map", property.getType().getName());
assertEquals("TCA Policy JSON", property.getDescription());
JpaToscaEntrySchema entrySchema = property.getEntrySchema();
- assertEquals("onap.datatypes.monitoring.tca_policy", entrySchema.getType().getName());
+ assertEquals(TCA, entrySchema.getType().getName());
// Check data_types
Map<PfConceptKey, JpaToscaDataType> dataTypesConceptMap = serviceTemplate.getDataTypes().getConceptMap();
@@ -176,18 +188,18 @@ public class MonitoringPolicyTypeSerializationTest {
Iterator<Entry<PfConceptKey, JpaToscaDataType>> dataTypesIter = dataTypesConceptMap.entrySet().iterator();
Entry<PfConceptKey, JpaToscaDataType> firstDataType = dataTypesIter.next();
- assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataType.getKey().getName());
+ assertEquals(METRICS, firstDataType.getKey().getName());
JpaToscaDataType firstDataTypeVal = firstDataType.getValue();
- assertEquals("tosca.datatypes.Root", firstDataTypeVal.getDerivedFrom().getName());
- assertEquals("0.0.0", firstDataTypeVal.getDerivedFrom().getVersion());
+ assertEquals(DATATYPE_ROOT, firstDataTypeVal.getDerivedFrom().getName());
+ assertEquals(VERSION_000, firstDataTypeVal.getDerivedFrom().getVersion());
assertTrue(firstDataTypeVal.getProperties().size() == 6);
Iterator<JpaToscaProperty> firstDataTypePropertiesIter = firstDataTypeVal.getProperties().values().iterator();
JpaToscaProperty firstDataTypeFirstProperty = firstDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.metricsPerEventName",
+ assertEquals(METRICS,
firstDataTypeFirstProperty.getKey().getParentKeyName());
assertEquals("controlLoopSchemaType", firstDataTypeFirstProperty.getKey().getLocalName());
- assertEquals("string", firstDataTypeFirstProperty.getType().getName());
+ assertEquals(STRING_TEXT, firstDataTypeFirstProperty.getType().getName());
assertTrue(firstDataTypeFirstProperty.isRequired());
assertEquals("Specifies Control Loop Schema Type for the event Name e.g. VNF, VM",
firstDataTypeFirstProperty.getDescription());
@@ -198,60 +210,60 @@ public class MonitoringPolicyTypeSerializationTest {
.getValidValues().size() == 2);
JpaToscaProperty firstDataTypeSecondProperty = firstDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.metricsPerEventName",
+ assertEquals(METRICS,
firstDataTypeSecondProperty.getKey().getParentKeyName());
assertEquals("eventName", firstDataTypeSecondProperty.getKey().getLocalName());
- assertEquals("string", firstDataTypeSecondProperty.getType().getName());
+ assertEquals(STRING_TEXT, firstDataTypeSecondProperty.getType().getName());
assertTrue(firstDataTypeSecondProperty.isRequired());
assertEquals("Event name to which thresholds need to be applied", firstDataTypeSecondProperty.getDescription());
JpaToscaProperty firstDataTypeThirdProperty = firstDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.metricsPerEventName",
+ assertEquals(METRICS,
firstDataTypeThirdProperty.getKey().getParentKeyName());
assertEquals("policyName", firstDataTypeThirdProperty.getKey().getLocalName());
- assertEquals("string", firstDataTypeThirdProperty.getType().getName());
+ assertEquals(STRING_TEXT, firstDataTypeThirdProperty.getType().getName());
assertTrue(firstDataTypeThirdProperty.isRequired());
assertEquals("TCA Policy Scope Name", firstDataTypeThirdProperty.getDescription());
JpaToscaProperty firstDataTypeFourthProperty = firstDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.metricsPerEventName",
+ assertEquals(METRICS,
firstDataTypeFourthProperty.getKey().getParentKeyName());
assertEquals("policyScope", firstDataTypeFourthProperty.getKey().getLocalName());
- assertEquals("string", firstDataTypeFourthProperty.getType().getName());
+ assertEquals(STRING_TEXT, firstDataTypeFourthProperty.getType().getName());
assertTrue(firstDataTypeFourthProperty.isRequired());
assertEquals("TCA Policy Scope", firstDataTypeFourthProperty.getDescription());
JpaToscaProperty firstDataTypeFifthProperty = firstDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.metricsPerEventName",
+ assertEquals(METRICS,
firstDataTypeFifthProperty.getKey().getParentKeyName());
assertEquals("policyVersion", firstDataTypeFifthProperty.getKey().getLocalName());
- assertEquals("string", firstDataTypeFifthProperty.getType().getName());
+ assertEquals(STRING_TEXT, firstDataTypeFifthProperty.getType().getName());
assertTrue(firstDataTypeFifthProperty.isRequired());
assertEquals("TCA Policy Scope Version", firstDataTypeFifthProperty.getDescription());
JpaToscaProperty firstDataTypeSixthProperty = firstDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.metricsPerEventName",
+ assertEquals(METRICS,
firstDataTypeSixthProperty.getKey().getParentKeyName());
assertEquals("thresholds", firstDataTypeSixthProperty.getKey().getLocalName());
assertEquals("list", firstDataTypeSixthProperty.getType().getName());
assertTrue(firstDataTypeSixthProperty.isRequired());
assertEquals("Thresholds associated with eventName", firstDataTypeSixthProperty.getDescription());
assertNotNull(firstDataTypeSixthProperty.getEntrySchema());
- assertEquals("onap.datatypes.monitoring.thresholds",
+ assertEquals(THRESHOLDS,
firstDataTypeSixthProperty.getEntrySchema().getType().getName());
Entry<PfConceptKey, JpaToscaDataType> secondDataType = dataTypesIter.next();
- assertEquals("onap.datatypes.monitoring.tca_policy", secondDataType.getKey().getName());
+ assertEquals(TCA, secondDataType.getKey().getName());
JpaToscaDataType secondDataTypeVal = secondDataType.getValue();
- assertEquals("tosca.datatypes.Root", secondDataTypeVal.getDerivedFrom().getName());
- assertEquals("0.0.0", secondDataTypeVal.getDerivedFrom().getVersion());
+ assertEquals(DATATYPE_ROOT, secondDataTypeVal.getDerivedFrom().getName());
+ assertEquals(VERSION_000, secondDataTypeVal.getDerivedFrom().getVersion());
assertTrue(secondDataTypeVal.getProperties().size() == 2);
Iterator<JpaToscaProperty> secondDataTypePropertiesIter = secondDataTypeVal.getProperties().values().iterator();
JpaToscaProperty secondDataTypeFirstProperty = secondDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.tca_policy", secondDataTypeFirstProperty.getKey().getParentKeyName());
+ assertEquals(TCA, secondDataTypeFirstProperty.getKey().getParentKeyName());
assertEquals("domain", secondDataTypeFirstProperty.getKey().getLocalName());
- assertEquals("string", secondDataTypeFirstProperty.getType().getName());
+ assertEquals(STRING_TEXT, secondDataTypeFirstProperty.getType().getName());
assertTrue(secondDataTypeFirstProperty.isRequired());
assertEquals("Domain name to which TCA needs to be applied", secondDataTypeFirstProperty.getDescription());
assertEquals("measurementsForVfScaling", secondDataTypeFirstProperty.getDefaultValue());
@@ -262,36 +274,36 @@ public class MonitoringPolicyTypeSerializationTest {
.getCompareTo());
JpaToscaProperty secondDataTypeSecondProperty = secondDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.tca_policy", secondDataTypeSecondProperty.getKey().getParentKeyName());
+ assertEquals(TCA, secondDataTypeSecondProperty.getKey().getParentKeyName());
assertEquals("metricsPerEventName", secondDataTypeSecondProperty.getKey().getLocalName());
assertEquals("list", secondDataTypeSecondProperty.getType().getName());
assertTrue(secondDataTypeSecondProperty.isRequired());
assertEquals("Contains eventName and threshold details that need to be applied to given eventName",
secondDataTypeSecondProperty.getDescription());
assertNotNull(secondDataTypeSecondProperty.getEntrySchema());
- assertEquals("onap.datatypes.monitoring.metricsPerEventName",
+ assertEquals(METRICS,
secondDataTypeSecondProperty.getEntrySchema().getType().getName());
Entry<PfConceptKey, JpaToscaDataType> thirdDataType = dataTypesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataType.getKey().getName());
+ assertEquals(THRESHOLDS, thirdDataType.getKey().getName());
JpaToscaDataType thirdDataTypeVal = thirdDataType.getValue();
- assertEquals("tosca.datatypes.Root", thirdDataTypeVal.getDerivedFrom().getName());
- assertEquals("0.0.0", thirdDataTypeVal.getDerivedFrom().getVersion());
+ assertEquals(DATATYPE_ROOT, thirdDataTypeVal.getDerivedFrom().getName());
+ assertEquals(VERSION_000, thirdDataTypeVal.getDerivedFrom().getVersion());
assertTrue(thirdDataTypeVal.getProperties().size() == 7);
Iterator<JpaToscaProperty> thirdDataTypePropertiesIter = thirdDataTypeVal.getProperties().values().iterator();
JpaToscaProperty thirdDataTypeFirstProperty = thirdDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeFirstProperty.getKey().getParentKeyName());
+ assertEquals(THRESHOLDS, thirdDataTypeFirstProperty.getKey().getParentKeyName());
assertEquals("closedLoopControlName", thirdDataTypeFirstProperty.getKey().getLocalName());
- assertEquals("string", thirdDataTypeFirstProperty.getType().getName());
+ assertEquals(STRING_TEXT, thirdDataTypeFirstProperty.getType().getName());
assertTrue(thirdDataTypeFirstProperty.isRequired());
assertEquals("Closed Loop Control Name associated with the threshold",
thirdDataTypeFirstProperty.getDescription());
JpaToscaProperty thirdDataTypeSecondProperty = thirdDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeSecondProperty.getKey().getParentKeyName());
+ assertEquals(THRESHOLDS, thirdDataTypeSecondProperty.getKey().getParentKeyName());
assertEquals("closedLoopEventStatus", thirdDataTypeSecondProperty.getKey().getLocalName());
- assertEquals("string", thirdDataTypeSecondProperty.getType().getName());
+ assertEquals(STRING_TEXT, thirdDataTypeSecondProperty.getType().getName());
assertTrue(thirdDataTypeSecondProperty.isRequired());
assertEquals("Closed Loop Event Status of the threshold", thirdDataTypeSecondProperty.getDescription());
assertNotNull(thirdDataTypeSecondProperty.getConstraints());
@@ -304,9 +316,9 @@ public class MonitoringPolicyTypeSerializationTest {
.getValidValues().size() == 2);
JpaToscaProperty thirdDataTypeThirdProperty = thirdDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeThirdProperty.getKey().getParentKeyName());
+ assertEquals(THRESHOLDS, thirdDataTypeThirdProperty.getKey().getParentKeyName());
assertEquals("direction", thirdDataTypeThirdProperty.getKey().getLocalName());
- assertEquals("string", thirdDataTypeThirdProperty.getType().getName());
+ assertEquals(STRING_TEXT, thirdDataTypeThirdProperty.getType().getName());
assertTrue(thirdDataTypeThirdProperty.isRequired());
assertEquals("Direction of the threshold", thirdDataTypeThirdProperty.getDescription());
assertNotNull(thirdDataTypeThirdProperty.getConstraints());
@@ -318,9 +330,9 @@ public class MonitoringPolicyTypeSerializationTest {
.getValidValues().size() == 5);
JpaToscaProperty thirdDataTypeFourthProperty = thirdDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeFourthProperty.getKey().getParentKeyName());
+ assertEquals(THRESHOLDS, thirdDataTypeFourthProperty.getKey().getParentKeyName());
assertEquals("fieldPath", thirdDataTypeFourthProperty.getKey().getLocalName());
- assertEquals("string", thirdDataTypeFourthProperty.getType().getName());
+ assertEquals(STRING_TEXT, thirdDataTypeFourthProperty.getType().getName());
assertTrue(thirdDataTypeFourthProperty.isRequired());
assertEquals("Json field Path as per CEF message which needs to be analyzed for TCA",
thirdDataTypeFourthProperty.getDescription());
@@ -330,9 +342,9 @@ public class MonitoringPolicyTypeSerializationTest {
.getValidValues().size() == 43);
JpaToscaProperty thirdDataTypeFifthProperty = thirdDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeFifthProperty.getKey().getParentKeyName());
+ assertEquals(THRESHOLDS, thirdDataTypeFifthProperty.getKey().getParentKeyName());
assertEquals("severity", thirdDataTypeFifthProperty.getKey().getLocalName());
- assertEquals("string", thirdDataTypeFifthProperty.getType().getName());
+ assertEquals(STRING_TEXT, thirdDataTypeFifthProperty.getType().getName());
assertTrue(thirdDataTypeFifthProperty.isRequired());
assertEquals("Threshold Event Severity", thirdDataTypeFifthProperty.getDescription());
assertNotNull(thirdDataTypeFifthProperty.getConstraints());
@@ -343,7 +355,7 @@ public class MonitoringPolicyTypeSerializationTest {
.getValidValues().size() == 5);;
JpaToscaProperty thirdDataTypeSixthProperty = thirdDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeSixthProperty.getKey().getParentKeyName());
+ assertEquals(THRESHOLDS, thirdDataTypeSixthProperty.getKey().getParentKeyName());
assertEquals("thresholdValue", thirdDataTypeSixthProperty.getKey().getLocalName());
assertEquals("integer", thirdDataTypeSixthProperty.getType().getName());
assertTrue(thirdDataTypeSixthProperty.isRequired());
@@ -351,9 +363,9 @@ public class MonitoringPolicyTypeSerializationTest {
thirdDataTypeSixthProperty.getDescription());
JpaToscaProperty thirdDataTypeSeventhProperty = thirdDataTypePropertiesIter.next();
- assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeSeventhProperty.getKey().getParentKeyName());
+ assertEquals(THRESHOLDS, thirdDataTypeSeventhProperty.getKey().getParentKeyName());
assertEquals("version", thirdDataTypeSeventhProperty.getKey().getLocalName());
- assertEquals("string", thirdDataTypeSeventhProperty.getType().getName());
+ assertEquals(STRING_TEXT, thirdDataTypeSeventhProperty.getType().getName());
assertTrue(thirdDataTypeSeventhProperty.isRequired());
assertEquals("Version number associated with the threshold", thirdDataTypeSeventhProperty.getDescription());
}
@@ -374,35 +386,35 @@ public class MonitoringPolicyTypeSerializationTest {
Iterator<Entry<PfConceptKey, JpaToscaPolicyType>> policyTypesIter = policyTypesConceptMap.entrySet().iterator();
Entry<PfConceptKey, JpaToscaPolicyType> firstPolicyType = policyTypesIter.next();
- assertEquals("onap.policies.Monitoring", firstPolicyType.getKey().getName());
- assertEquals("1.0.0", firstPolicyType.getKey().getVersion());
+ assertEquals(MONITORING, firstPolicyType.getKey().getName());
+ assertEquals(VERSION_100, firstPolicyType.getKey().getVersion());
assertEquals("tosca.policies.Root", firstPolicyType.getValue().getDerivedFrom().getName());
assertEquals("a base policy type for all policies that govern monitoring provision",
firstPolicyType.getValue().getDescription());
Entry<PfConceptKey, JpaToscaPolicyType> secondPolicyType = policyTypesIter.next();
- assertEquals("onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server",
+ assertEquals(DCAE,
secondPolicyType.getKey().getName());
- assertEquals("1.0.0", secondPolicyType.getKey().getVersion());
+ assertEquals(VERSION_100, secondPolicyType.getKey().getVersion());
assertEquals("policy.nodes.Root", secondPolicyType.getValue().getDerivedFrom().getName());
assertTrue(secondPolicyType.getValue().getProperties().size() == 2);
Iterator<JpaToscaProperty> propertiesIter = secondPolicyType.getValue().getProperties().values().iterator();
JpaToscaProperty firstProperty = propertiesIter.next();
- assertEquals("onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server",
+ assertEquals(DCAE,
firstProperty.getKey().getParentKeyName());
- assertEquals("1.0.0", firstProperty.getKey().getParentKeyVersion());
+ assertEquals(VERSION_100, firstProperty.getKey().getParentKeyVersion());
assertEquals("buscontroller_feed_publishing_endpoint", firstProperty.getKey().getLocalName());
- assertEquals("string", firstProperty.getType().getName());
+ assertEquals(STRING_TEXT, firstProperty.getType().getName());
assertEquals("DMAAP Bus Controller feed endpoint", firstProperty.getDescription());
JpaToscaProperty secondProperty = propertiesIter.next();
- assertEquals("onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server",
+ assertEquals(DCAE,
secondProperty.getKey().getParentKeyName());
- assertEquals("1.0.0", secondProperty.getKey().getParentKeyVersion());
+ assertEquals(VERSION_100, secondProperty.getKey().getParentKeyVersion());
assertEquals("datafile.policy", secondProperty.getKey().getLocalName());
- assertEquals("string", secondProperty.getType().getName());
+ assertEquals(STRING_TEXT, secondProperty.getType().getName());
assertEquals("datafile Policy JSON as string", secondProperty.getDescription());
}