From 6347aed1148a9fab8f7f45e46be71b8bdfc52924 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Thu, 13 Jun 2019 18:18:39 -0400 Subject: [PATCH] Fix more sonar issues in models: yaml to dao Extracted common Strings into constants. Reduced "cyclomatic complexity" in some return statements. Used assertj to eliminate "log or rethrow" messages in junit tests. models-yaml models-base models-dao Change-Id: I20548d4cf5e67d085245e0d54df8ba0116ec86ec Issue-ID: POLICY-1791 Signed-off-by: Jim Hahn --- .../onap/policy/models/base/ExceptionsTest.java | 22 +- .../onap/policy/models/base/ModelServiceTest.java | 95 +- .../policy/models/base/PfConceptContainerTest.java | 107 +-- .../models/base/PfConceptGetterImplTest.java | 37 +- .../org/onap/policy/models/base/PfKeyTest.java | 225 ++--- .../org/onap/policy/models/base/PfKeyUseTest.java | 78 +- .../org/onap/policy/models/base/PfModelTest.java | 51 +- .../policy/models/base/PfObjectFilterTest.java | 57 +- .../policy/models/base/PfReferenceKeyTest.java | 201 ++-- .../org/onap/policy/models/base/PfUtilsTest.java | 10 +- .../org/onap/policy/models/base/ValidatedTest.java | 8 +- .../onap/policy/models/base/ValidationTest.java | 22 +- .../models/base/testconcepts/DummyPfConcept.java | 38 +- .../models/base/testconcepts/DummyPfKey.java | 5 +- .../models/base/testconcepts/DummyPfModel.java | 6 +- .../base/testconcepts/DummyPfNameVersion.java | 5 +- .../org/onap/policy/models/dao/DaoMiscTest.java | 32 +- .../policy/models/dao/DummyReferenceEntity.java | 3 +- .../org/onap/policy/models/dao/EntityTest.java | 171 ++-- .../controlloop/compiler/ControlLoopCompiler.java | 201 ++-- .../policy/controlloop/policy/ControlLoop.java | 18 +- .../org/onap/policy/controlloop/policy/Policy.java | 55 +- .../org/onap/policy/controlloop/policy/Target.java | 44 +- .../controlloop/policy/guard/ControlLoopGuard.java | 25 +- .../controlloop/policy/guard/GuardPolicy.java | 66 +- .../builder/impl/ControlLoopGuardBuilderImpl.java | 82 +- .../compiler/CompilerExceptionTest.java | 7 +- .../compiler/ControlLoopCompilerTest.java | 65 +- .../compiler/ControlLoopGuardCompilerTest.java | 78 +- .../policy/ControlLoopPolicyBuilderTest.java | 1006 ++++++++++---------- .../controlloop/policy/ControlLoopPolicyTest.java | 61 +- .../policy/controlloop/policy/ControlLoopTest.java | 37 +- .../controlloop/policy/guard/ConstraintTest.java | 32 +- .../policy/guard/ControlLoopGuardBuilderTest.java | 239 +++-- .../policy/guard/ControlLoopGuardTest.java | 36 +- .../controlloop/policy/guard/GuardPolicyTest.java | 52 +- .../src/test/resources/v1.0.0/test_evil.yaml | 4 +- 37 files changed, 1490 insertions(+), 1791 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()); 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()); - 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())) + .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 keyList = container.getKeys(); assertEquals(1, keyList.size()); - PfConceptKey conceptKey = new PfConceptKey("Key", "0.0.1"); + PfConceptKey conceptKey = new PfConceptKey("Key", VERSION0); Map 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 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> authorativeList = new ArrayList<>(); authorativeList.add(dacMap); @@ -213,19 +188,17 @@ public class PfConceptContainerTest { List> 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 keyMap = new TreeMap<>(); @@ -43,54 +46,42 @@ public class PfConceptGetterImplTest { PfConceptGetterImpl 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(keyMap.values()), getter.getAll(null)); assertEquals(new TreeSet(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 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 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 getKeys() { - final List 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(); + this.keyList = new ArrayList<>(); } /** @@ -61,7 +62,7 @@ public class DummyPfModel extends PfModel { */ public DummyPfModel(final PfConceptKey key) { super(key); - this.keyList = new ArrayList(); + 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 keyInfoSetIn = new TreeSet(); + final Set keyInfoSetIn = new TreeSet<>(); keyInfoSetIn.add(keyInfo1); keyInfoSetIn.add(keyInfo2); pfDao.createCollection(keyInfoSetIn); - Set keyInfoSetOut = new TreeSet(pfDao.getAll(DummyConceptEntity.class)); + Set keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class)); keyInfoSetIn.add(keyInfo0); assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); pfDao.delete(keyInfo1); keyInfoSetIn.remove(keyInfo1); - keyInfoSetOut = new TreeSet(pfDao.getAll(DummyConceptEntity.class)); + keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class)); assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); pfDao.deleteCollection(keyInfoSetIn); - keyInfoSetOut = new TreeSet(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(pfDao.getAll(DummyConceptEntity.class)); + keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class)); assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); pfDao.delete(DummyConceptEntity.class, aKey0); - keyInfoSetOut = new TreeSet(pfDao.getAll(DummyConceptEntity.class)); + keyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyConceptEntity.class)); assertEquals(2, keyInfoSetOut.size()); assertEquals(2, pfDao.size(DummyConceptEntity.class)); - final Set keySetIn = new TreeSet(); + final Set keySetIn = new TreeSet<>(); keySetIn.add(aKey1); keySetIn.add(aKey2); final int deletedCount = pfDao.deleteByConceptKey(DummyConceptEntity.class, keySetIn); assertEquals(2, deletedCount); - keyInfoSetOut = new TreeSet(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(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 testEntitySetOut = - new TreeSet(pfDao.getAll(DummyReferenceEntity.class)); + new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class)); assertEquals(16, testEntitySetOut.size()); - testEntitySetOut = new TreeSet(pfDao.getAll(DummyReferenceEntity.class, owner0Key)); + testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner0Key)); assertEquals(5, testEntitySetOut.size()); - testEntitySetOut = new TreeSet(pfDao.getAll(DummyReferenceEntity.class, owner1Key)); + testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner1Key)); assertEquals(3, testEntitySetOut.size()); - testEntitySetOut = new TreeSet(pfDao.getAll(DummyReferenceEntity.class, owner2Key)); + testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner2Key)); assertEquals(2, testEntitySetOut.size()); - testEntitySetOut = new TreeSet(pfDao.getAll(DummyReferenceEntity.class, owner3Key)); + testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner3Key)); assertEquals(1, testEntitySetOut.size()); - testEntitySetOut = new TreeSet(pfDao.getAll(DummyReferenceEntity.class, owner4Key)); + testEntitySetOut = new TreeSet<>(pfDao.getAll(DummyReferenceEntity.class, owner4Key)); assertEquals(1, testEntitySetOut.size()); - testEntitySetOut = new TreeSet(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 rKeySetIn = new TreeSet(); + final Set 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-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 graph = - new DirectedMultigraph<>(new ClassBasedEdgeFactory graph = + new DirectedMultigraph<>(new ClassBasedEdgeFactory(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 addPoliciesAsNodes(ControlLoopPolicy policy, - DirectedGraph graph, TriggerNodeWrapper triggerNode, + + private static Map addPoliciesAsNodes(ControlLoopPolicy policy, + DirectedGraph graph, TriggerNodeWrapper triggerNode, ControlLoopCompilerCallback callback) { Map mapNodes = new HashMap<>(); for (Policy operPolicy : policy.getPolicies()) { @@ -264,27 +263,27 @@ public class ControlLoopCompiler implements Serializable { } return mapNodes; } - + private static void addEdge(DirectedGraph graph, Map 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 graph, + + private static void validateNodesAndEdges(DirectedGraph 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 graph, + + private static void validateTriggerNodeWrapper(DirectedGraph 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 graph, + + private static void validateFinalResultNodeWrapper(DirectedGraph 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 graph, + + private static void validatePolicyNodeWrapper(DirectedGraph 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> recipes = new ImmutableMap.Builder>() .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 guards; - + + private List 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 getGuards() { + public List getGuards() { return guards; } - public void setGuards(LinkedList guards) { + public void setGuards(List 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 limitConstraints; - + private List 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 limitConstraints) { this(name, matchParameters); - if (limitConstraints != null) { - this.limitConstraints = (LinkedList) limitConstraints; - } + this.limitConstraints = limitConstraints; } - - public GuardPolicy(String name, String description, MatchParameters matchParameters, + + public GuardPolicy(String name, String description, MatchParameters matchParameters, List 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 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 getLimit_constraints() { + public List getLimit_constraints() { return limitConstraints; } - public void setLimit_constraints(LinkedList limitConstraints) { + public void setLimit_constraints(List 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 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 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 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 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 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 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 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 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 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 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 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 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 timeWindow = new HashMap<>(); List 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 timeWindow = new HashMap<>(); Map 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 timeWindow = new HashMap<>(); Map activeTimeRange = new HashMap<>(); - activeTimeRange.put("timeWindowKey", "timeWindowValue"); + activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE); List 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 timeWindow = new HashMap<>(); Map activeTimeRange = new HashMap<>(); - activeTimeRange.put("timeWindowKey", "timeWindowValue"); + activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE); List 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 timeWindow = new HashMap<>(); Map activeTimeRange = new HashMap<>(); - activeTimeRange.put("timeWindowKey", "timeWindowValue"); + activeTimeRange.put(TIME_WINDOW_KEY, TIME_WINDOW_VALUE); List 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 timeWindow = new HashMap<>(); final Map activeTimeRange = new HashMap<>(); List 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 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 (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 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 activeTimeRange = new HashMap(); - activeTimeRange.put("start", "00:00:00-05:00"); - activeTimeRange.put("end", "23:59:59-05:00"); - List blacklist = new LinkedList(); - blacklist.add("eNodeB_common_id1"); - blacklist.add("eNodeB_common_id2"); - Map 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 (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 activeTimeRange = new HashMap<>(); + activeTimeRange.put("start", "00:00:00-05:00"); + activeTimeRange.put("end", "23:59:59-05:00"); + List blacklist = new LinkedList<>(); + blacklist.add("eNodeB_common_id1"); + blacklist.add("eNodeB_common_id2"); + Map 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 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 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 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 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 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 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 -- 2.16.6