diff options
Diffstat (limited to 'common-parameters/src/test/java/org/onap')
28 files changed, 1458 insertions, 1668 deletions
diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java index b874db69..48d2f4b5 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ExceptionTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ package org.onap.policy.common.parameters; import static org.junit.Assert.assertEquals; import java.io.IOException; - import org.junit.Test; public class ExceptionTest { diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java deleted file mode 100644 index b568d7fb..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestAbstractParameters.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.EmptyParameterGroup; - -public class TestAbstractParameters { - - @Test - public void testAbstractParameters() { - final EmptyParameterGroup parameters = new EmptyParameterGroup("Empty Group"); - assertTrue(parameters.isValid()); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java index 12cd80cb..b7bea204 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidationResult.java @@ -1,8 +1,8 @@ -/* +/*- * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 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,6 +20,7 @@ package org.onap.policy.common.parameters; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -27,17 +28,25 @@ import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; +import java.util.function.BiConsumer; import org.junit.Before; import org.junit.Test; public class TestBeanValidationResult { + private static final String TEXT1 = "abc"; + private static final String TEXT2 = "def"; private static final String MY_LIST = "my-list"; + private static final String MY_MAP = "my-map"; private static final String OBJECT = "an object"; private static final String INITIAL_INDENT = "xx "; private static final String NEXT_INDENT = "yy "; private static final String MID_INDENT = "xx yy "; private static final String NAME = "my-name"; private static final String MY_LIST_INVALID = " 'my-list' INVALID, item has status INVALID\n "; + private static final String MY_MAP_INVALID = " 'my-map' INVALID, item has status INVALID\n "; private static final String BEAN_INVALID_MSG = requote("'my-name' INVALID, item has status INVALID\n"); private String cleanMsg; @@ -52,10 +61,10 @@ public class TestBeanValidationResult { */ @Before public void setUp() { - clean = new ObjectValidationResult("abc", 10); + clean = new ObjectValidationResult(TEXT1, 10); cleanMsg = clean.getResult("", "", true); - invalid = new ObjectValidationResult("def", 20); + invalid = new ObjectValidationResult(TEXT2, 20); invalid.setResult(ValidationStatus.INVALID, "invalid"); invalidMsg = invalid.getResult(); @@ -83,6 +92,10 @@ public class TestBeanValidationResult { assertEquals(INITIAL_INDENT + BEAN_INVALID_MSG + MID_INDENT + cleanMsg + MID_INDENT + invalidMsg, bean.getResult(INITIAL_INDENT, NEXT_INDENT, true)); + + bean = new BeanValidationResult(NAME, OBJECT); + assertFalse(bean.addResult(MY_LIST, "hello", ValidationStatus.INVALID, TEXT1)); + assertThat(bean.getResult()).contains("\"" + MY_LIST + "\" value \"hello\" INVALID, " + TEXT1); } @Test @@ -150,6 +163,50 @@ public class TestBeanValidationResult { } + @Test + public void testValidateMap() { + Map<String, ValidationResult> map = null; + bean = new BeanValidationResult(NAME, OBJECT); + assertTrue(bean.validateMap(MY_MAP, map, validMapEntry())); + assertTrue(bean.isValid()); + assertNull(bean.getResult()); + + map = Map.of(TEXT1, clean, TEXT2, clean); + bean = new BeanValidationResult(NAME, OBJECT); + assertTrue(bean.validateMap(MY_MAP, map, validMapEntry())); + assertTrue(bean.isValid()); + assertNull(bean.getResult()); + + // null value in the map + map = new TreeMap<>(); + map.put(TEXT1, clean); + map.put(TEXT2, null); + bean = new BeanValidationResult(NAME, OBJECT); + assertFalse(bean.validateMap(MY_MAP, map, validMapEntry())); + assertFalse(bean.isValid()); + assertEquals(requote(BEAN_INVALID_MSG + MY_MAP_INVALID + + "item 'def' value 'null' INVALID, is null\n"), bean.getResult()); + + map = Map.of(TEXT1, invalid, TEXT2, invalid); + bean = new BeanValidationResult(NAME, OBJECT); + assertFalse(bean.validateMap(MY_MAP, map, validMapEntry())); + assertFalse(bean.isValid()); + assertEquals(requote(BEAN_INVALID_MSG + MY_MAP_INVALID + invalidMsg + + " " + invalidMsg), bean.getResult()); + + } + + private BiConsumer<BeanValidationResult, Entry<String, ValidationResult>> validMapEntry() { + return (result, entry) -> { + var value = entry.getValue(); + if (value == null) { + result.validateNotNull(entry.getKey(), value); + } else { + result.addResult(value); + } + }; + } + private static String requote(String text) { return text.replace('\'', '"'); } diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java new file mode 100644 index 00000000..83d0a7f9 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestBeanValidator.java @@ -0,0 +1,664 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import lombok.Getter; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.ClassName; +import org.onap.policy.common.parameters.annotations.Max; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.common.parameters.annotations.Pattern; +import org.onap.policy.common.parameters.annotations.Size; +import org.onap.policy.common.parameters.annotations.Valid; + +public class TestBeanValidator { + private static final String TOP = "top"; + private static final String STR_FIELD = "strValue"; + private static final String INT_FIELD = "intValue"; + private static final String NUM_FIELD = "numValue"; + private static final String ITEMS_FIELD = "items"; + private static final String STRING_VALUE = "string value"; + private static final int INT_VALUE = 20; + + private BeanValidator validator; + + @Before + public void setUp() { + validator = new BeanValidator(); + } + + @Test + public void testValidateTop_testValidateFields() { + // validate null + assertTrue(validator.validateTop(TOP, null).isValid()); + + // validate something that has no annotations + assertTrue(validator.validateTop(TOP, validator).isValid()); + + @NotNull + @Getter + class Data { + String strValue; + } + + // one failure case + Data data = new Data(); + BeanValidationResult result = validator.validateTop(TOP, data); + assertInvalid("testValidateFields", result, STR_FIELD, "null"); + assertTrue(result.getResult().contains(TOP)); + + // one success case + data.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, data).isValid()); + + /** + * Repeat with a subclass. + */ + @Getter + class Derived extends Data { + @Min(10) + int intValue; + } + + Derived derived = new Derived(); + derived.strValue = STRING_VALUE; + derived.intValue = INT_VALUE; + + // success case + assertTrue(validator.validateTop(TOP, derived).isValid()); + + // failure cases + derived.strValue = null; + assertInvalid("testValidateFields", validator.validateTop(TOP, derived), STR_FIELD, "null"); + derived.strValue = STRING_VALUE; + + derived.intValue = 1; + assertInvalid("testValidateFields", validator.validateTop(TOP, derived), INT_FIELD, "minimum"); + derived.intValue = INT_VALUE; + + // both invalid + derived.strValue = null; + derived.intValue = 1; + result = validator.validateTop(TOP, derived); + assertInvalid("testValidateFields", result, STR_FIELD, "null"); + assertInvalid("testValidateFields", result, INT_FIELD, "minimum"); + derived.strValue = STRING_VALUE; + derived.intValue = INT_VALUE; + } + + @Test + public void testVerNotNull() { + class NotNullCheck { + @Getter + @Min(1) + @NotNull + Integer intValue; + } + + NotNullCheck notNullCheck = new NotNullCheck(); + assertInvalid("testVerNotNull", validator.validateTop(TOP, notNullCheck), INT_FIELD, "null"); + + notNullCheck.intValue = INT_VALUE; + assertTrue(validator.validateTop(TOP, notNullCheck).isValid()); + + notNullCheck.intValue = 0; + assertInvalid("testVerNotNull", validator.validateTop(TOP, notNullCheck), INT_FIELD, "minimum"); + } + + @Test + public void testVerNotBlank() { + class NotBlankCheck { + @Getter + @NotBlank + String strValue; + } + + NotBlankCheck notBlankCheck = new NotBlankCheck(); + + // null + assertTrue(validator.validateTop(TOP, notBlankCheck).isValid()); + + // empty + notBlankCheck.strValue = ""; + assertInvalid("testVerNotNull", validator.validateTop(TOP, notBlankCheck), STR_FIELD, "blank"); + + // spaces + notBlankCheck.strValue = " "; + assertInvalid("testVerNotNull", validator.validateTop(TOP, notBlankCheck), STR_FIELD, "blank"); + + // not blank + notBlankCheck.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, notBlankCheck).isValid()); + + /* + * Class with "blank" annotation on an integer. + */ + class NotBlankInt { + @Getter + @NotBlank + int intValue; + } + + NotBlankInt notBlankInt = new NotBlankInt(); + notBlankInt.intValue = 0; + assertTrue(validator.validateTop(TOP, notBlankInt).isValid()); + } + + /** + * Tests verSize with a collection. + */ + @Test + public void testVerSizeCollection() { + class CollectionSizeCheck { + @Getter + @Size(min = 3) + Collection<Integer> items; + } + + CollectionSizeCheck collCheck = new CollectionSizeCheck(); + + // valid length - exact + collCheck.items = List.of(1, 2, 3); + assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue(); + + // valid length - extra + collCheck.items = List.of(1, 2, 3, 4); + assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue(); + + // too few + collCheck.items = List.of(1, 2); + assertInvalid("testVerSize", validator.validateTop(TOP, collCheck), ITEMS_FIELD, "minimum", "3"); + + // null + collCheck.items = null; + assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue(); + } + + /** + * Tests verSize with a map. + */ + @Test + public void testVerSizeMap() { + class MapSizeCheck { + @Getter + @Size(min = 3) + Map<Integer, Integer> items; + } + + MapSizeCheck mapCheck = new MapSizeCheck(); + + // valid length - exact + mapCheck.items = Map.of(1, 10, 2, 20, 3, 30); + assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue(); + + // valid length - extra + mapCheck.items = Map.of(1, 10, 2, 20, 3, 30, 4, 40); + assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue(); + + // too few + mapCheck.items = Map.of(1, 10, 2, 20); + assertInvalid("testVerSize", validator.validateTop(TOP, mapCheck), ITEMS_FIELD, "minimum", "3"); + + // null + mapCheck.items = null; + assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue(); + } + + /** + * Tests verSize with an object for which it doesn't apply. + */ + @Test + public void testVerSizeOther() { + class OtherSizeCheck { + @Getter + @Size(min = 3) + Integer items; + } + + OtherSizeCheck otherCheck = new OtherSizeCheck(); + + otherCheck.items = 10; + assertThat(validator.validateTop(TOP, otherCheck).isValid()).isTrue(); + } + + @Test + public void testVerRegex() { + class RegexCheck { + @Getter + @Pattern(regexp = "[a-f]*") + String strValue; + } + + RegexCheck regexCheck = new RegexCheck(); + + // does not match + regexCheck.strValue = "xyz"; + assertInvalid("testVerRegex", validator.validateTop(TOP, regexCheck), STR_FIELD, + "does not match regular expression [a-f]"); + + // matches + regexCheck.strValue = "abcabc"; + assertTrue(validator.validateTop(TOP, regexCheck).isValid()); + + // invalid regex + class InvalidRegexCheck { + @Getter + @Pattern(regexp = "[a-f") + String strValue; + } + + InvalidRegexCheck invalidRegexCheck = new InvalidRegexCheck(); + + // does not match + invalidRegexCheck.strValue = "abc"; + assertInvalid("testVerRegex", validator.validateTop(TOP, invalidRegexCheck), STR_FIELD, + "does not match regular expression [a-f"); + + // matches + regexCheck.strValue = "abcabc"; + assertTrue(validator.validateTop(TOP, regexCheck).isValid()); + + /* + * Class with "regex" annotation on an integer. + */ + class RegexInt { + @Getter + @Pattern(regexp = "[a-f]*") + int intValue; + } + + RegexInt regexInt = new RegexInt(); + regexInt.intValue = 0; + assertInvalid("testVerRegex", validator.validateTop(TOP, regexInt), INT_FIELD, + "does not match regular expression [a-f]"); + } + + @Test + public void testVerMax() { + /* + * Field is not a number. + */ + class NonNumeric { + @Getter + @Max(100) + String strValue; + } + + NonNumeric nonNumeric = new NonNumeric(); + nonNumeric.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, nonNumeric).isValid()); + + /* + * Integer field. + */ + class IntField { + @Getter + @Max(100) + Integer intValue; + } + + // ok value + IntField intField = new IntField(); + assertNumeric("testVerMax-integer", intField, value -> { + intField.intValue = value; + }, INT_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Long field. + */ + class LongField { + @Getter + @Max(100) + Long numValue; + } + + // ok value + LongField longField = new LongField(); + assertNumeric("testVerMax-long", longField, value -> { + longField.numValue = (long) value; + }, NUM_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Float field. + */ + class FloatField { + @Getter + @Max(100) + Float numValue; + } + + // ok value + FloatField floatField = new FloatField(); + assertNumeric("testVerMax-float", floatField, value -> { + floatField.numValue = (float) value; + }, NUM_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Double field. + */ + class DoubleField { + @Getter + @Max(100) + Double numValue; + } + + // ok value + DoubleField doubleField = new DoubleField(); + assertNumeric("testVerMax-double", doubleField, value -> { + doubleField.numValue = (double) value; + }, NUM_FIELD, "maximum", INT_VALUE, 100, 101); + + /* + * Atomic Integer field (which is a subclass of Number). + */ + class AtomIntValue { + @Getter + @Max(100) + AtomicInteger numValue; + } + + // ok value + AtomIntValue atomIntField = new AtomIntValue(); + atomIntField.numValue = new AtomicInteger(INT_VALUE); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + + // invalid value - should be OK, because it isn't an Integer + atomIntField.numValue.set(101); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + } + + @Test + public void testVerMin() { + /* + * Field is not a number. + */ + class NonNumeric { + @Getter + @Min(10) + String strValue; + } + + NonNumeric nonNumeric = new NonNumeric(); + nonNumeric.strValue = STRING_VALUE; + assertTrue(validator.validateTop(TOP, nonNumeric).isValid()); + + /* + * Integer field. + */ + class IntField { + @Getter + @Min(10) + Integer intValue; + } + + // ok value + IntField intField = new IntField(); + assertNumeric("testVerMin-integer", intField, value -> { + intField.intValue = value; + }, INT_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Long field. + */ + class LongField { + @Getter + @Min(10) + Long numValue; + } + + // ok value + LongField longField = new LongField(); + assertNumeric("testVerMin-long", longField, value -> { + longField.numValue = (long) value; + }, NUM_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Float field. + */ + class FloatField { + @Getter + @Min(10) + Float numValue; + } + + // ok value + FloatField floatField = new FloatField(); + assertNumeric("testVerMin-float", floatField, value -> { + floatField.numValue = (float) value; + }, NUM_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Double field. + */ + class DoubleField { + @Getter + @Min(10) + Double numValue; + } + + // ok value + DoubleField doubleField = new DoubleField(); + assertNumeric("testVerMin-double", doubleField, value -> { + doubleField.numValue = (double) value; + }, NUM_FIELD, "minimum", INT_VALUE, 10, 1); + + /* + * Atomic Integer field (which is a subclass of Number). + */ + class AtomIntValue { + @Getter + @Min(10) + AtomicInteger numValue; + } + + // ok value + AtomIntValue atomIntField = new AtomIntValue(); + atomIntField.numValue = new AtomicInteger(INT_VALUE); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + + // invalid value - should be OK, because it isn't an Integer + atomIntField.numValue.set(101); + assertTrue(validator.validateTop(TOP, atomIntField).isValid()); + } + + @Test + public void testVerClassName() { + class ClassNameCheck { + @Getter + @ClassName + String strValue; + } + + ClassNameCheck classCheck = new ClassNameCheck(); + + // null should be OK + classCheck.strValue = null; + assertTrue(validator.validateTop(TOP, classCheck).isValid()); + + // valid class name + classCheck.strValue = getClass().getName(); + assertTrue(validator.validateTop(TOP, classCheck).isValid()); + + // invalid class name + classCheck.strValue = "<unknown class>"; + assertInvalid("testVerClassName", validator.validateTop(TOP, classCheck), + STR_FIELD, "class is not in the classpath"); + } + + @Test + public void testVerCascade() { + class Item { + @Getter + @NotNull + Integer intValue; + } + + @Getter + class Container { + @Valid + Item checked; + + Item unchecked; + + @Valid + List<Item> items; + + @Valid + Map<String, Item> itemMap; + } + + Container cont = new Container(); + cont.unchecked = new Item(); + cont.items = List.of(new Item()); + cont.itemMap = Map.of(STRING_VALUE, new Item()); + + cont.checked = null; + assertTrue(validator.validateTop(TOP, cont).isValid()); + + cont.checked = new Item(); + + assertInvalid("testVerCascade", validator.validateTop(TOP, cont), INT_FIELD, "null"); + + cont.checked.intValue = INT_VALUE; + assertTrue(validator.validateTop(TOP, cont).isValid()); + } + + @Test + public void testVerCollection() { + @Getter + class Container { + List<@Min(5) Integer> items; + + // not a collection - should not be checked + @Valid + String strValue; + + String noAnnotations; + } + + Container cont = new Container(); + cont.strValue = STRING_VALUE; + cont.noAnnotations = STRING_VALUE; + + // null collection - always valid + assertTrue(validator.validateTop(TOP, cont).isValid()); + + // empty collection - always valid + cont.items = List.of(); + assertTrue(validator.validateTop(TOP, cont).isValid()); + + cont.items = List.of(-10, -20); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("\"0\"", "-10", "\"1\"", "-20", "minimum"); + + cont.items = List.of(10, -30); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("\"1\"", "-30", "minimum") + .doesNotContain("\"0\""); + + cont.items = List.of(10, 20); + assertTrue(validator.validateTop(TOP, cont).isValid()); + } + + @Test + public void testVerMap() { + @Getter + class Container { + Map<String, @Min(5) Integer> items; + + // not a map + @NotBlank + String strValue; + + String noAnnotations; + } + + Container cont = new Container(); + cont.strValue = STRING_VALUE; + cont.noAnnotations = STRING_VALUE; + + // null map - always valid + assertTrue(validator.validateTop(TOP, cont).isValid()); + + // empty map - always valid + cont.items = Map.of(); + assertTrue(validator.validateTop(TOP, cont).isValid()); + + cont.items = Map.of("abc", -10, "def", -20); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("abc", "-10", "def", "-20", "minimum"); + + cont.items = Map.of("abc", 10, "def", -30); + assertThat(validator.validateTop(TOP, cont).getResult()).contains("def", "-30", "minimum") + .doesNotContain("abc"); + + cont.items = Map.of("abc", 10, "def", 20); + assertTrue(validator.validateTop(TOP, cont).isValid()); + } + + @Test + public void testGetEntryName() { + assertThat(validator.getEntryName(makeEntry(null, 0))).isEmpty(); + assertThat(validator.getEntryName(makeEntry("", 0))).isEmpty(); + assertThat(validator.getEntryName(makeEntry(STRING_VALUE, 0))).isEqualTo(STRING_VALUE); + } + + /** + * Makes a Map entry with the given key and value. + * + * @param key desired key + * @param value desired value + * @return a new Map entry + */ + private Map.Entry<String, Integer> makeEntry(String key, int value) { + HashMap<String, Integer> map = new HashMap<>(); + map.put(key, value); + return map.entrySet().iterator().next(); + } + + private <T> void assertNumeric(String testName, T object, Consumer<Integer> setter, String fieldName, + String expectedText, int inside, int edge, int outside) { + setter.accept(inside); + assertTrue(validator.validateTop(TOP, object).isValid()); + + // on the edge + setter.accept(edge); + assertTrue(validator.validateTop(TOP, object).isValid()); + + // invalid + setter.accept(outside); + assertInvalid("testVerNotNull", validator.validateTop(TOP, object), fieldName, expectedText); + } + + + private void assertInvalid(String testName, BeanValidationResult result, String... text) { + assertThat(result.getResult()).describedAs(testName).contains(text); + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java new file mode 100644 index 00000000..81a7b8ff --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestFieldValidator.java @@ -0,0 +1,379 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.gson.annotations.SerializedName; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Map; +import lombok.Getter; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +public class TestFieldValidator extends ValidatorUtil { + private static final String INT_LIST_FIELD = "intList"; + private static final String INT_MAP_FIELD = "intMap"; + private static final String UNANNOTATED_FIELD = "unannotated"; + private static final String INT_FIELD = "intValue"; + private static final int VALID_INT = 10; + private static final int INVALID_INT = -10; + + @Getter + private int unannotated; + + @Min(0) + @Getter + private int intValue; + + @Getter + private List<@Min(1) Integer> intList; + + @Getter + private Map<@NotBlank String, @Min(1) Integer> intMap; + + @SerializedName("annotated_key_map") + @Getter + private Map<@NotBlank String, Integer> annotatedKeyMap; + + @Getter + private Map<String, @Min(1) Integer> annotatedValueMap; + + @Getter + private List<Integer> unannotatedList; + + @Getter + private Map<String, Integer> unannotatedMap; + + @NotNull + @Getter + private boolean boolValue; + + @NotNull + @Getter + private String notNullValue; + + @Min(0) + @Getter + private static int staticField; + + /** + * Has no accessor. + */ + @Min(0) + private int noMethod; + + /** + * Accessor is {@link #getStaticMethod()}, which is static. + */ + @Min(0) + private int staticMethod; + + /** + * Accessor is {@link #getVoidMethod()}, which returns a void. + */ + @Min(0) + private int voidMethod; + + /** + * Accessor is {@link #getParameterizedMethod()}, which requires a parameter. + */ + @Min(0) + private int parameterizedMethod; + + /** + * Accessor is {@link #getExMethod()}, which throws an exception. + */ + @Min(0) + private int exMethod; + + + @Before + public void setUp() { + bean = new BeanValidator(); + } + + @Test + public void testGetAnnotation() { + // field-level annotation + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // class-level annotation + assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "text")).isEmpty()).isFalse(); + } + + @Test + public void testFieldValidator() throws NoSuchFieldException, SecurityException { + /* + * Note: nested classes contain fields like "$this", thus the check for "$" in the + * variable name is already covered by the other tests. + */ + + /* + * Class with no annotations. + */ + @NotNull + class NoAnnotations { + @SuppressWarnings("unused") + String strValue; + } + + Field field = NoAnnotations.class.getDeclaredField("this$0"); + + assertThat(new FieldValidator(bean, NoAnnotations.class, field).isEmpty()).isTrue(); + + // unannotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotated")).isEmpty()).isTrue(); + + // these are invalid for various reasons + + Field staticField2 = getField("staticField"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticField2)) + .isInstanceOf(IllegalArgumentException.class); + + Field noMethodField = getField("noMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, noMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + // annotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + } + + @Test + public void testFieldValidator_SetNullAllowed() { + // default - null is allowed + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isNullAllowed()).isTrue(); + + // field-level NotNull + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("notNullValue")).isNullAllowed()) + .isFalse(); + + // class-level NotNull + assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "noMethod")).isNullAllowed()) + .isFalse(); + } + + @Test + public void testAddListValidator() { + + // unannotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotatedList")).isEmpty()).isTrue(); + + // annotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_LIST_FIELD)).isEmpty()).isFalse(); + } + + @Test + public void testAddMapValidator() { + + // unannotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("unannotatedMap")).isEmpty()).isTrue(); + + // annotated + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_MAP_FIELD)).isEmpty()).isFalse(); + + // only the key is annotated + FieldValidator validator = new FieldValidator(bean, TestFieldValidator.class, getField("annotatedKeyMap")); + assertThat(validator.isEmpty()).isFalse(); + + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + annotatedKeyMap = Map.of("abc", -10); + validator.validateField(result, this); + assertThat(result.getResult()).isNull(); + + annotatedKeyMap = Map.of(" ", -10); + validator.validateField(result, this); + assertThat(result.getResult()).contains("annotated_key_map", "blank").doesNotContain("-10"); + + // only the value is annotated + validator = new FieldValidator(bean, TestFieldValidator.class, getField("annotatedValueMap")); + assertThat(validator.isEmpty()).isFalse(); + + result = new BeanValidationResult(MY_NAME, this); + annotatedValueMap = Map.of(" ", 10); + validator.validateField(result, this); + assertThat(result.getResult()).isNull(); + + annotatedValueMap = Map.of(" ", -10); + validator.validateField(result, this); + assertThat(result.getResult()).doesNotContain("blank").contains("annotatedValueMap", "\" \"", "-10"); + } + + @SuppressWarnings("deprecation") + @Test + public void testValidateField_testGetValue() { + // unannotated + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + new FieldValidator(bean, getClass(), getField(UNANNOTATED_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // valid + intValue = VALID_INT; + result = new BeanValidationResult(MY_NAME, this); + new FieldValidator(bean, getClass(), getField(INT_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // invalid + intValue = INVALID_INT; + result = new BeanValidationResult(MY_NAME, this); + new FieldValidator(bean, getClass(), getField(INT_FIELD)).validateField(result, this); + assertThat(result.getResult()).contains(INT_FIELD); + + // throws an exception + FieldValidator validator = new FieldValidator(bean, TestFieldValidator.class, getField("exMethod")); + BeanValidationResult result2 = new BeanValidationResult(MY_NAME, this); + assertThatThrownBy(() -> validator.validateField(result2, this)).isInstanceOf(IllegalArgumentException.class) + .getCause().isInstanceOf(InvocationTargetException.class).getCause() + .hasMessage("expected exception"); + } + + @Test + public void testValidateField_testGetValue_ListField() { + // valid + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + intList = List.of(10, 20, 30, 40); + new FieldValidator(bean, getClass(), getField(INT_LIST_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // invalid + result = new BeanValidationResult(MY_NAME, this); + intList = List.of(9, -8, 7, -6); + new FieldValidator(bean, getClass(), getField(INT_LIST_FIELD)).validateField(result, this); + assertThat(result.getResult()).doesNotContain("0", "9").contains("1", "-8").doesNotContain("2", "7") + .contains("3", "-6"); + } + + @Test + public void testValidateField_testGetValue_MapField() { + // valid + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + intMap = Map.of("ten", 10, "twenty", 20, "thirty", 30, "forty", 40); + new FieldValidator(bean, getClass(), getField(INT_MAP_FIELD)).validateField(result, this); + assertThat(result.getResult()).isNull(); + + // invalid + result = new BeanValidationResult(MY_NAME, this); + intMap = Map.of("ten", 9, "twenty", -8, "thirty", 7, "forty", -6); + new FieldValidator(bean, getClass(), getField(INT_MAP_FIELD)).validateField(result, this); + assertThat(result.getResult()).doesNotContain("ten", "9").contains("twenty", "-8").doesNotContain("thirty", "7") + .contains("forty", "-6"); + } + + @Test + public void testClassOnly() { + // class-level annotation has no bearing on a static field + assertThat(new FieldValidator(bean, ClassAnnot.class, getField(ClassAnnot.class, "staticValue")).isEmpty()) + .isTrue(); + + // field-level annotation on a static field + Field staticField2 = getField("staticField"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticField2)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testGetAccessor() { + // uses "getXxx" + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // uses "isXxx" + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField("boolValue")).isEmpty()).isFalse(); + } + + @Test + public void testGetMethod() { + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // these are invalid for various reasons + + Field noMethodField = getField("noMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, noMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + Field staticMethodField = getField("staticMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticMethodField)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testValidMethod() { + assertThat(new FieldValidator(bean, TestFieldValidator.class, getField(INT_FIELD)).isEmpty()).isFalse(); + + // these are invalid for various reasons + + Field staticMethodField = getField("staticMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, staticMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + Field voidMethodField = getField("voidMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, voidMethodField)) + .isInstanceOf(IllegalArgumentException.class); + + Field paramMethodField = getField("parameterizedMethod"); + assertThatThrownBy(() -> new FieldValidator(bean, TestFieldValidator.class, paramMethodField)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void testIsFieldAnnotated_testSetFieldAnnotated() { + // annotated at the field level + assertThat(new FieldValidator(bean, getClass(), getField(INT_FIELD)).isFieldAnnotated()).isTrue(); + + // unannotated + assertThat(new FieldValidator(bean, getClass(), getField(UNANNOTATED_FIELD)).isFieldAnnotated()).isFalse(); + } + + public static int getStaticMethod() { + return -1000; + } + + public void getVoidMethod() { + // do nothing + } + + public int getParameterizedMethod(boolean flag) { + return 0; + } + + public int getExMethod() { + throw new RuntimeException("expected exception"); + } + + @NotNull + public static class ClassAnnot { + @Getter + private String text; + + // no "get" method + @SuppressWarnings("unused") + private String noMethod; + + @Getter + private static int staticValue; + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java new file mode 100644 index 00000000..cadcfdee --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestItemValidator.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +public class TestItemValidator extends ValidatorUtil { + + // annotated fields - each field must have exactly one annotation + + /** + * This annotation does not contain a method returning an array. + */ + @Min(value = 0) + private int notArray; + + /** + * This annotation doesn't contain any annotations that the {@link BeanValidator} + * recognizes. + */ + @Simple + private int mismatch; + + /** + * No annotations. + */ + @SuppressWarnings("unused") + private int noAnnotations; + + /** + * One matching annotation. + */ + @NotNull + private int match; + + /** + * Multiple matching annotations. + */ + @NotNull + @NotBlank + private String multiMatch; + + + @Before + public void setUp() { + bean = new BeanValidator(); + } + + @Test + public void testGetAnnotation() { + // no matches + assertThat(new ItemValidator(bean, getAnnotType("noAnnotations"), true).isEmpty()).isTrue(); + + // had a match + assertThat(new ItemValidator(bean, getAnnotType("match"), true).checkers).hasSize(1); + + // multiple matches + ItemValidator validator = new ItemValidator(bean, getAnnotType("multiMatch"), true); + assertThat(validator.checkers).hasSize(2); + + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + + result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, null); + assertThat(result.getResult()).isNotNull(); + + result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, ""); + assertThat(result.getResult()).isNotNull(); + } + + @Test + public void testItemValidatorBeanValidatorAnnotation() { + assertThat(new ItemValidator(bean, getAnnotType("match")).isEmpty()).isFalse(); + } + + @Test + public void testItemValidatorBeanValidatorAnnotationBoolean() { + assertThat(new ItemValidator(bean, getAnnotType("match"), true).isEmpty()).isFalse(); + + assertThat(new ItemValidator(bean, getAnnotType("match"), false).isEmpty()).isTrue(); + } + + // these annotations are not recognized by the BeanValidator + + @Retention(RUNTIME) + @Target(FIELD) + public @interface Simple { + + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java deleted file mode 100644 index abef5528..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestJsonInput.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import java.io.FileReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.TestParametersL00; - - -public class TestJsonInput { - - @Test - public void testJsonInput() throws IOException { - TestParametersL00 testParameterGroup = null; - - // Read the parameters from JSON using Gson - final Gson gson = new GsonBuilder().create(); - testParameterGroup = gson.fromJson(new FileReader("src/test/resources/parameters/TestParameters.json"), - TestParametersL00.class); - - GroupValidationResult validationResult = testParameterGroup.validate(); - assertTrue(validationResult.isValid()); - assertEquals("l00NameFromFile", testParameterGroup.getName()); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt"))) - .replaceAll("\\s+", ""); - assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", "")); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java deleted file mode 100644 index fda37816..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestParameterService.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -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 org.junit.Test; -import org.onap.policy.common.parameters.testclasses.EmptyParameterGroup; - -public class TestParameterService { - private static final String EMPTY_GROUP = "Empty Group"; - - @Test - public void testParameterService() { - ParameterService.clear(); - - assertFalse(ParameterService.contains("EmptyGroup")); - - assertThatThrownBy(() -> ParameterService.get("EmptyGroup")) - .hasMessage("\"EmptyGroup\" not found in parameter service"); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP)); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - assertNotNull(ParameterService.get(EMPTY_GROUP)); - - assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP))) - .hasMessage("\"Empty Group\" already registered in parameter service"); - - assertThatThrownBy(() -> ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), false)) - .hasMessage("\"Empty Group\" already registered in parameter service"); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - - ParameterService.deregister(EMPTY_GROUP); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP), true); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - - ParameterService.deregister(EMPTY_GROUP); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - EmptyParameterGroup epg = new EmptyParameterGroup(EMPTY_GROUP); - ParameterService.register(epg); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - assertNotNull(ParameterService.get(EMPTY_GROUP)); - - ParameterService.deregister(epg); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - assertThatThrownBy(() -> ParameterService.deregister(EMPTY_GROUP)) - .hasMessage("\"Empty Group\" not registered in parameter service"); - - assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP)) - .hasMessage("\"Empty Group\" not found in parameter service"); - - ParameterService.register(new EmptyParameterGroup(EMPTY_GROUP)); - assertTrue(ParameterService.contains(EMPTY_GROUP)); - assertNotNull(ParameterService.get(EMPTY_GROUP)); - - assertEquals(1, ParameterService.getAll().size()); - ParameterService.clear(); - assertEquals(0, ParameterService.getAll().size()); - assertFalse(ParameterService.contains(EMPTY_GROUP)); - - assertThatThrownBy(() -> ParameterService.get(EMPTY_GROUP)) - .hasMessage("\"Empty Group\" not found in parameter service"); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java index 9e7121cd..b19b92da 100644 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidation.java @@ -1,7 +1,7 @@ /* * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,25 +21,17 @@ package org.onap.policy.common.parameters; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; import org.junit.Test; import org.onap.policy.common.parameters.annotations.Max; import org.onap.policy.common.parameters.annotations.Min; import org.onap.policy.common.parameters.annotations.NotBlank; import org.onap.policy.common.parameters.annotations.NotNull; -import org.onap.policy.common.parameters.testclasses.TestParametersL00; -import org.onap.policy.common.parameters.testclasses.TestParametersL10; +import org.onap.policy.common.parameters.annotations.Valid; public class TestValidation { - private static final String L0_PARAMETERS = "l0Parameters"; - private static final String NOT_BLANK_STRING_MESSAGE = "field 'notBlankString' type 'java.lang.String' value '' INVALID, must be a non-blank string\n" .replace('\'', '"'); @@ -74,177 +66,15 @@ public class TestValidation { private long maxLong; @Test - public void testValidationOk() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertTrue(validationResult.isClean()); - assertNull(validationResult.getResult()); - assertEquals(l0Parameters, validationResult.getParameterGroup()); - assertEquals(l0Parameters.getName(), validationResult.getName()); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_0_OK.txt"))) - .replaceAll("\\s+", ""); - assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", "")); - } - - @Test - public void testValidationObservation() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 3); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Observation.txt"))) - .replaceAll("\\s+", ""); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertFalse(validationResult.isClean()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 2); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Observation.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 1); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Observation.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.OBSERVATION, 0); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(null, validationResult.getResult()); - } - - @Test - public void testValidationWarning() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 3); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Warning.txt"))) - .replaceAll("\\s+", ""); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 2); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Warning.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 1); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Warning.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.WARNING, 0); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(null, validationResult.getResult()); - } - - @Test - public void testValidationInvalid() throws IOException { - TestParametersL00 l0Parameters = new TestParametersL00(L0_PARAMETERS); - - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 3); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_3_Invalid.txt"))) - .replaceAll("\\s+", ""); - - GroupValidationResult validationResult = l0Parameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 2); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_2_Invalid.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 1); - - expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestParametersL0_1_Invalid.txt"))) - .replaceAll("\\s+", ""); - - validationResult = l0Parameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals(expectedResult, validationResult.getResult().replaceAll("\\s+", "")); - - l0Parameters.triggerValidationStatus(ValidationStatus.CLEAN, 3); - l0Parameters.triggerValidationStatus(ValidationStatus.INVALID, 0); - - validationResult = l0Parameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(null, validationResult.getResult()); - } - - @Test - public void testValidationEmptySubGroup() { - TestParametersL10 l10Parameters = new TestParametersL10("l10Parameters"); - - l10Parameters.setL10LGenericNested0(null); - - GroupValidationResult validationResult = l10Parameters.validate(); - assertTrue(validationResult.isValid()); - - assertTrue(validationResult.getResult("", "", true).contains("UNDEFINED")); - } - - @Test public void testGetValidationResult() { Contained item = new Contained(); item.setName("item"); Container cont = new Container(); cont.item = item; - GroupValidationResult result = cont.validate(); + BeanValidationResult result = cont.validate(); assertEquals(ValidationStatus.INVALID, result.getStatus()); - assertTrue(result.getResult().contains(">= 1")); + assertThat(result.getResult()).contains("minimum"); item.minInt = 1000; result = cont.validate(); @@ -253,7 +83,7 @@ public class TestValidation { cont.item = null; result = cont.validate(); assertEquals(ValidationStatus.INVALID, result.getStatus()); - assertTrue(result.getResult().contains("is null")); + assertThat(result.getResult()).contains("is null"); } @Test @@ -429,6 +259,7 @@ public class TestValidation { private static class Container extends ParameterGroupImpl { @NotNull + @Valid private Contained item; public Container() { diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java deleted file mode 100644 index b02022d7..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationErrors.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.ParameterGroupMissingGetter; -import org.onap.policy.common.parameters.testclasses.ParameterGroupPrivateGetter; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithArray; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithCollection; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithIllegalMapKey; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithIllegalMapValue; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullCollection; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullMapValue; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithNullSubGroup; -import org.onap.policy.common.parameters.testclasses.ParameterGroupWithParameterGroupCollection; - -public class TestValidationErrors { - @Test - public void testBadArrayValidation() { - ParameterGroupWithArray groupWithArray = new ParameterGroupWithArray("Illegal Array Group"); - assertTrue(groupWithArray.isValid()); - } - - @Test - public void testCollectionValidation() { - ParameterGroupWithCollection legalCollection = new ParameterGroupWithCollection("Legal Collection"); - assertTrue(legalCollection.isValid()); - - ParameterGroupWithParameterGroupCollection illegalCollection = new ParameterGroupWithParameterGroupCollection( - "Illegal Collection"); - - assertThatThrownBy(illegalCollection::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("collection parameter \"parameterGroupArrayList\" is illegal," - + " parameter groups are not allowed as collection members"); - } - - @Test - public void testNullCollection() { - ParameterGroupWithNullCollection nullCollection = new ParameterGroupWithNullCollection("Null Collection"); - - assertThatThrownBy(nullCollection::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("collection parameter \"nullList\" is null"); - } - - @Test - public void testMapNullSubGroupValidation() { - ParameterGroupWithNullSubGroup nullSub = new ParameterGroupWithNullSubGroup("Null sub group value"); - - nullSub.isValid(); - assertNull(nullSub.getSubGroup()); - } - - @Test - public void testMapNullValueValidation() { - ParameterGroupWithNullMapValue nullMap = new ParameterGroupWithNullMapValue("Null Map value"); - - assertThatThrownBy(nullMap::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("map parameter \"nullMap\" is null"); - } - - @Test - public void testBadMapKeyValidation() { - ParameterGroupWithIllegalMapKey illegalMap = new ParameterGroupWithIllegalMapKey("Illegal Map"); - - assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("map entry is not a parameter group keyed by a string, key \"1\" " - + "in map \"badMap\" is not a string"); - } - - @Test - public void testBadMapValueValidation() { - ParameterGroupWithIllegalMapValue illegalMap = new ParameterGroupWithIllegalMapValue("Illegal Map"); - - assertThatThrownBy(illegalMap::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("map entry is not a parameter group keyed by a string, value \"1\" in " - + "map \"intMap\" is not a parameter group"); - } - - @Test - public void testMissingGetter() { - ParameterGroupMissingGetter badGetterName = new ParameterGroupMissingGetter("BGN"); - - assertThatThrownBy(badGetterName::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("could not get getter method for parameter \"value\""); - } - - @Test - public void testPrivateGetter() { - ParameterGroupPrivateGetter privateGetter = new ParameterGroupPrivateGetter("privateGetter"); - - assertThatThrownBy(privateGetter::isValid).isInstanceOf(ParameterRuntimeException.class) - .hasMessage("could not get getter method for parameter \"value\""); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java deleted file mode 100644 index 46360ef9..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValidationResults.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.TestParametersL10; -import org.onap.policy.common.parameters.testclasses.TestParametersLGeneric; - -public class TestValidationResults { - private static final String NON_EXISTANT_PARAMETER = "nonExistantParameter"; - private static final String L10L_GENERIC_NESTED_MAP_VAL0 = "l10LGenericNestedMapVal0"; - private static final String L10_INT_FIELD = "l10IntField"; - private static final String ENTRY0 = "entry0"; - private static final String THIS_VALUE_IS_INVALID = "This value is invalid"; - private static final String SOMETHING_WAS_OBSERVED = "Something was observed"; - private static final String PG_MAP = "pgMap"; - - private Map<String, ParameterGroup> pgMap = new LinkedHashMap<>(); - private ParameterGroup pg = new TestParametersL10("pg"); - - @Before - public void initMap() { - pgMap.put(ENTRY0, new TestParametersLGeneric(ENTRY0)); - } - - @Test - public void testGroupMapValidationResult() throws NoSuchFieldException { - GroupMapValidationResult result = new GroupMapValidationResult(this.getClass().getDeclaredField(PG_MAP), - pgMap); - - assertTrue(result.isValid()); - assertEquals(PG_MAP, result.getName()); - - result.setResult(ValidationStatus.OBSERVATION); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - // Once the status is stepped, it can't be reset back because it is the status of map members - result.setResult(ValidationStatus.CLEAN); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim()); - - result.setResult(ENTRY0, new GroupValidationResult(pgMap.get(ENTRY0))); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - assertEquals("parameter group map \"pgMap\" OBSERVATION, Something was observed", result.getResult().trim()); - - assertThatThrownBy(() -> result.setResult("nonExistantEntry", new GroupValidationResult(pgMap.get(ENTRY0)))) - .hasMessage("no entry with name \"nonExistantEntry\" exists"); - } - - @Test - public void testGroupValidationResult() throws NoSuchFieldException { - GroupValidationResult result = new GroupValidationResult(pg); - - assertTrue(result.isValid()); - assertEquals(pg, result.getParameterGroup()); - assertEquals("pg", result.getName()); - - result.setResult(ValidationStatus.OBSERVATION); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - // Once the status is stepped, it can't be reset back because it is the status of map members - result.setResult(ValidationStatus.CLEAN); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - - result.setResult(ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED); - assertTrue(result.isValid()); - assertEquals(ValidationStatus.OBSERVATION, result.getStatus()); - assertEquals("parameter group \"pg\" type \"org.onap.policy.common.parameters.testclasses.TestParametersL10\"" - + " OBSERVATION, Something was observed", result.getResult().trim()); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ValidationStatus.OBSERVATION, - SOMETHING_WAS_OBSERVED)) - .hasMessage("no parameter field exists for parameter: nonExistantParameter"); - - result.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, SOMETHING_WAS_OBSERVED); - assertTrue(result.isValid()); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, new GroupValidationResult(pg))) - .hasMessage("no nested parameter field exists for parameter: nonExistantParameter"); - - assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, new GroupValidationResult(pg))) - .hasMessage("parameter is not a nested group parameter: l10IntField"); - - GroupMapValidationResult groupMapResult = new GroupMapValidationResult( - this.getClass().getDeclaredField(PG_MAP), pgMap); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, ENTRY0, groupMapResult)) - .hasMessage("no group map parameter field exists for parameter: nonExistantParameter"); - - assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, ENTRY0, groupMapResult)) - .hasMessage("parameter is not a nested group map parameter: l10IntField"); - - result.setResult("l10LGenericNestedMap", L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID, - THIS_VALUE_IS_INVALID); - assertEquals(ValidationStatus.INVALID, result.getStatus()); - - assertThatThrownBy(() -> result.setResult(L10_INT_FIELD, L10L_GENERIC_NESTED_MAP_VAL0, ValidationStatus.INVALID, - THIS_VALUE_IS_INVALID)) - .hasMessage("parameter is not a nested group map parameter: l10IntField"); - - assertThatThrownBy(() -> result.setResult(NON_EXISTANT_PARAMETER, L10L_GENERIC_NESTED_MAP_VAL0, - ValidationStatus.INVALID, THIS_VALUE_IS_INVALID)).hasMessage( - "no group map parameter field exists for parameter: nonExistantParameter"); - - assertThatThrownBy(() -> result.setResult("l10LGenericNestedMap", "NonExistantKey", ValidationStatus.INVALID, - THIS_VALUE_IS_INVALID)).hasMessage("no entry with name \"NonExistantKey\" exists"); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java new file mode 100644 index 00000000..dcf08695 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestValueValidator.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.annotation.Annotation; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +public class TestValueValidator extends ValidatorUtil { + + private ValueValidator validator; + + // these fields just provide place-holders for annotations + + @NotNull + @NotBlank + private final int annotField = 1; + + + @Before + public void setUp() { + validator = new MyValueValidator(); + } + + @Test + public void testIsEmpty() { + assertThat(validator.isEmpty()).isTrue(); + + validator.addAnnotation(NotNull.class, (result2, fieldName, value) -> true); + assertThat(validator.isEmpty()).isFalse(); + } + + @Test + public void testValidateValue_NullValue() { + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + + validator.validateValue(result, MY_FIELD, null); + assertThat(result.getResult()).isNull(); + + validator.addAnnotation(NotNull.class, + (result2, fieldName, value) -> result2.validateNotNull(fieldName, value)); + validator.validateValue(result, MY_FIELD, null); + assertThat(result.getResult()).contains(MY_FIELD, "null"); + } + + @Test + public void testValidateValue_NotNullValue() { + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + + validator.addAnnotation(NotNull.class, + (result2, fieldName, value) -> result2.validateNotNull(fieldName, value)); + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + } + + @Test + public void testAddAnnotationClassOfTChecker() { + // the field does not have this annotation + validator.addAnnotation(Min.class, (result2, fieldName, value) -> true); + assertThat(validator.isEmpty()).isTrue(); + + // "null" flag should stay true with this annotation + assertThat(validator.isNullAllowed()).isTrue(); + validator.addAnnotation(NotBlank.class, (result2, fieldName, value) -> true); + assertThat(validator.isNullAllowed()).isTrue(); + + // "null" flag should become false with this annotation + assertThat(validator.isNullAllowed()).isTrue(); + validator.addAnnotation(NotNull.class, (result2, fieldName, value) -> true); + assertThat(validator.isNullAllowed()).isFalse(); + } + + @Test + public void testAddAnnotationClassOfTCheckerWithAnnotOfT() { + // the field does not have this annotation + validator.addAnnotation(Min.class, (result2, fieldName, annot, value) -> true); + assertThat(validator.isEmpty()).isTrue(); + + // indicates the annotation value + AtomicBoolean wasNull = new AtomicBoolean(false); + + // the field DOES have this annotation + validator.addAnnotation(NotNull.class, (result2, fieldName, annot, value) -> { + wasNull.set(annot instanceof NotNull); + return result2.validateNotNull(fieldName, value); + }); + assertThat(validator.isEmpty()).isFalse(); + + // ensure that the checker is invoked + BeanValidationResult result = new BeanValidationResult(MY_NAME, this); + validator.validateValue(result, MY_FIELD, HELLO); + assertThat(result.getResult()).isNull(); + + assertThat(wasNull.get()).isTrue(); + } + + @Test + public void testGetAnnotation() { + assertThat(new ValueValidator().getAnnotation(NotNull.class)).isNull(); + } + + /** + * Checks for annotations on the "annotField" field. + */ + private static class MyValueValidator extends ValueValidator { + @Override + public <T extends Annotation> T getAnnotation(Class<T> annotClass) { + try { + return TestValueValidator.class.getDeclaredField("annotField").getAnnotation(annotClass); + } catch (NoSuchFieldException | SecurityException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java deleted file mode 100644 index 66656844..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/TestYamlInput.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.FileReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import org.junit.Test; -import org.onap.policy.common.parameters.testclasses.TestParametersL00; -import org.yaml.snakeyaml.Yaml; - -public class TestYamlInput { - @Test - public void testYamlInput() throws IOException { - TestParametersL00 testParameterGroup = null; - - // Read the parameters from JSON using Gson - final Yaml yaml = new Yaml(); - testParameterGroup = yaml.loadAs(new FileReader("src/test/resources/parameters/TestParameters.yaml"), - TestParametersL00.class); - - GroupValidationResult validationResult = testParameterGroup.validate(); - assertTrue(validationResult.isValid()); - assertEquals("l00NameFromFile", testParameterGroup.getName()); - - String expectedResult = new String(Files.readAllBytes( - Paths.get("src/test/resources/expectedValidationResults/TestJsonYamlValidationResult.txt"))) - .replaceAll("\\s+", ""); - assertEquals(expectedResult, validationResult.getResult("", " ", true).replaceAll("\\s+", "")); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java new file mode 100644 index 00000000..e39b5b86 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ValidatorUtil.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2021 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.parameters; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedType; +import java.lang.reflect.Field; + +/** + * Utilities for validator tests. + */ +public class ValidatorUtil { + protected static final String MY_NAME = "My-Name"; + protected static final String MY_FIELD = "My-Field"; + protected static final String HELLO = "hello"; + + protected BeanValidator bean; + + /** + * Gets the single annotation for a given field. + * + * @param fieldName name of the field having the desired annotation + * @return the given field's annotation + */ + protected Annotation getAnnot(String fieldName) { + return getField(fieldName).getAnnotations()[0]; + } + + /** + * Gets the annotated type for a given field. + * + * @param fieldName name of the field of interest + * @return the given field's annotated type + */ + protected AnnotatedType getAnnotType(String fieldName) { + return getField(fieldName).getAnnotatedType(); + } + + /** + * Gets a field from this object. + * + * @param fieldName name of the field of interest + * @return the given field + */ + protected Field getField(String fieldName) { + return getField(getClass(), fieldName); + } + + /** + * Gets a field from a given class. + * + * @param clazz class containing the field + * @param fieldName name of the field of interest + * @return the given field + */ + protected Field getField(Class<?> clazz, String fieldName) { + try { + return clazz.getDeclaredField(fieldName); + + } catch (NoSuchFieldException | SecurityException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java deleted file mode 100644 index d1787482..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/EmptyParameterGroup.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class EmptyParameterGroup extends ParameterGroupImpl { - - public EmptyParameterGroup(String name) { - super(name); - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java deleted file mode 100644 index e6c85923..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupMissingGetter.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupMissingGetter extends ParameterGroupImpl { - private String value; - - public ParameterGroupMissingGetter(final String name) { - super(name); - } - - public String getTheValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java deleted file mode 100644 index 1d90ca1f..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupPrivateGetter.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupPrivateGetter extends ParameterGroupImpl { - private String value; - - public ParameterGroupPrivateGetter(final String name) { - super(name); - } - - public String getTheValue() { - return getValue(); - } - - private String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java deleted file mode 100644 index e37b47ae..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithArray.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithArray extends ParameterGroupImpl { - private int[] intArray = {1, 2, 3}; - - public ParameterGroupWithArray(final String name) { - super(name); - } - - public int[] getIntArray() { - return intArray; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java deleted file mode 100644 index ee7c1715..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithCollection.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.ArrayList; -import java.util.List; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithCollection extends ParameterGroupImpl { - private List<Integer> intArrayList = new ArrayList<>(); - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public ParameterGroupWithCollection(final String name) { - super(name); - - intArrayList.add(1); - intArrayList.add(2); - intArrayList.add(3); - } - - public List<Integer> getIntArrayList() { - return intArrayList; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java deleted file mode 100644 index b3c7d1b7..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapKey.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.onap.policy.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithIllegalMapKey extends ParameterGroupImpl { - private Map<Integer, ParameterGroup> badMap = new LinkedHashMap<>(); - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithIllegalMapKey(final String name) { - super(name); - - badMap.put(1, new TestParametersLGeneric("One")); - badMap.put(2, new TestParametersLGeneric("Two")); - badMap.put(3, new TestParametersLGeneric("Three")); - } - - public Map<Integer, ParameterGroup> getBadMap() { - return badMap; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java deleted file mode 100644 index 4df708a4..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithIllegalMapValue.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithIllegalMapValue extends ParameterGroupImpl { - private Map<String, Integer> intMap = new LinkedHashMap<>(); - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithIllegalMapValue(final String name) { - super(name); - - intMap.put("One", 1); - intMap.put("Two", 2); - intMap.put("Three", 3); - } - - public Map<String, Integer> getIntMap() { - return intMap; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java deleted file mode 100644 index 35752c75..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullCollection.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.List; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithNullCollection extends ParameterGroupImpl { - private List<Integer> nullList = null; - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithNullCollection(final String name) { - super(name); - } - - public List<Integer> getNullList() { - return nullList; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java deleted file mode 100644 index 1a640023..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullMapValue.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.Map; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithNullMapValue extends ParameterGroupImpl { - private Map<String, Integer> nullMap = null; - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithNullMapValue(final String name) { - super(name); - } - - public Map<String, Integer> getNullMap() { - return nullMap; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java deleted file mode 100644 index 7fe1402f..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithNullSubGroup.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithNullSubGroup extends ParameterGroupImpl { - private ParameterGroup subGroup = null; - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithNullSubGroup(final String name) { - super(name); - } - - public ParameterGroup getSubGroup() { - return subGroup; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java deleted file mode 100644 index 08c799f5..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/ParameterGroupWithParameterGroupCollection.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.ArrayList; -import java.util.List; -import org.onap.policy.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterGroupImpl; - -public class ParameterGroupWithParameterGroupCollection extends ParameterGroupImpl { - private List<ParameterGroup> parameterGroupArrayList = new ArrayList<>(); - - /** - * Create a test parameter group. - * @param name the parameter group name - */ - public ParameterGroupWithParameterGroupCollection(final String name) { - super(name); - - parameterGroupArrayList.add(new TestParametersLGeneric("Generic0")); - parameterGroupArrayList.add(new TestParametersLGeneric("Generic1")); - parameterGroupArrayList.add(new TestParametersLGeneric("Generic2")); - } - - public List<ParameterGroup> getParameterGroupArrayList() { - return parameterGroupArrayList; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java deleted file mode 100644 index 51440546..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL00.java +++ /dev/null @@ -1,208 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ParameterConstants; -import org.onap.policy.common.parameters.ParameterGroupImpl; -import org.onap.policy.common.parameters.ValidationStatus; - -public class TestParametersL00 extends ParameterGroupImpl { - private static final String L00_INT_FIELD = "l00IntField"; - private static final String L00_STRING_FIELD = "l00StringField"; - - private static final String A_CONSTANT = "A Constant"; - - private int l00IntField = 0; - private String l00StringField = "Legal " + this.getClass().getName(); - private TestParametersL10 l00L10Nested = new TestParametersL10("l00L10Nested"); - private TestParametersLGeneric l00LGenericNested = new TestParametersLGeneric("l00LGenericNested"); - private Map<String, TestParametersLGeneric> l00LGenericNestedMap = new LinkedHashMap<>(); - private boolean isSomeFlag; - private boolean someNonIsFlag; - - /** - * Default constructor. - */ - public TestParametersL00() { - super(A_CONSTANT); - } - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public TestParametersL00(final String name) { - super(name); - - TestParametersLGeneric l00LGenericNestedMapVal0 = new TestParametersLGeneric("l00LGenericNestedMapVal0"); - l00LGenericNestedMap.put(l00LGenericNestedMapVal0.getName(), l00LGenericNestedMapVal0); - TestParametersLGeneric l00LGenericNestedMapVal1 = new TestParametersLGeneric("l00LGenericNestedMapVal1"); - l00LGenericNestedMap.put(l00LGenericNestedMapVal1.getName(), l00LGenericNestedMapVal1); - } - - public int getL00IntField() { - return l00IntField; - } - - public String getL00StringField() { - return l00StringField; - } - - public TestParametersL10 getL00L10Nested() { - return l00L10Nested; - } - - public TestParametersLGeneric getL00LGenericNested() { - return l00LGenericNested; - } - - public Map<String, TestParametersLGeneric> getL00LGenericNestedMap() { - return l00LGenericNestedMap; - } - - public boolean isSomeFlag() { - return isSomeFlag; - } - - public boolean isSomeNonIsFlag() { - return someNonIsFlag; - } - - public void setSomeFlag(boolean isSomeFlag) { - this.isSomeFlag = isSomeFlag; - } - - public void setL00IntField(int l00IntField) { - this.l00IntField = l00IntField; - } - - public void setL00StringField(String l00StringField) { - this.l00StringField = l00StringField; - } - - public void setL00L10Nested(TestParametersL10 l00l10Nested) { - l00L10Nested = l00l10Nested; - } - - public void setL00LGenericNested(TestParametersLGeneric l00lGenericNested) { - l00LGenericNested = l00lGenericNested; - } - - public void setL00LGenericNestedMap(Map<String, TestParametersLGeneric> l00lGenericNestedMap) { - l00LGenericNestedMap = l00lGenericNestedMap; - } - - /** - * Trigger a validation message. - * - * @param triggerStatus Validation status to trigger - * @param level Number of levels to recurse before stopping - */ - public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) { - if (level == 0) { - return; - } else { - level--; - } - - switch (triggerStatus) { - case CLEAN: - l00StringField = "Legal " + this.getClass().getName(); - l00IntField = 0; - break; - case OBSERVATION: - l00StringField = "aString"; - l00IntField = 2; - break; - case WARNING: - l00StringField = L00_STRING_FIELD; - l00IntField = 3; - break; - case INVALID: - l00StringField = ""; - l00IntField = -1; - break; - default: - break; - } - - l00L10Nested.triggerValidationStatus(triggerStatus, level); - l00LGenericNested.triggerValidationStatus(triggerStatus, level); - - for (TestParametersLGeneric nestedParameterGroup : l00LGenericNestedMap.values()) { - nestedParameterGroup.triggerValidationStatus(triggerStatus, level); - } - - } - - @Override - public GroupValidationResult validate() { - GroupValidationResult validationResult = super.validate(); - - if (StringUtils.isBlank(getName())) { - validationResult.setResult("name", ValidationStatus.INVALID, "name must be a non-blank string"); - } - - if (StringUtils.isBlank(l00StringField)) { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.INVALID, - "l00StringField must be a non-blank string"); - } else if (l00StringField.equals(L00_STRING_FIELD)) { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.WARNING, - "using the field name for the parameter value is dangerous"); - } else if (l00StringField.equals("aString")) { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.OBSERVATION, - "this value for name is unhelpful"); - } else { - validationResult.setResult(L00_STRING_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - if (l00IntField < 0) { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.INVALID, - "l00IntField must be a positive integer"); - } else if (l00IntField > 2) { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.WARNING, - "values greater than 2 are not recommended"); - } else if (l00IntField == 2) { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2"); - } else { - validationResult.setResult(L00_INT_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - validationResult.setResult("l00L10Nested", l00L10Nested.validate()); - validationResult.setResult("l00LGenericNested", l00LGenericNested.validate()); - - for (Entry<String, TestParametersLGeneric> nestedGroupEntry : l00LGenericNestedMap.entrySet()) { - validationResult.setResult("l00LGenericNestedMap", nestedGroupEntry.getKey(), - nestedGroupEntry.getValue().validate()); - } - - return validationResult; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java deleted file mode 100644 index 7276b504..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersL10.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ParameterConstants; -import org.onap.policy.common.parameters.ParameterGroupImpl; -import org.onap.policy.common.parameters.ValidationStatus; - -public class TestParametersL10 extends ParameterGroupImpl { - private static final String L10_INT_FIELD = "l10IntField"; - private static final String L10_STRING_FIELD = "l10StringField"; - - private int l10IntField = 0; - private String l10StringField = "Legal " + this.getClass().getName(); - private TestParametersLGeneric l10LGenericNested0 = new TestParametersLGeneric("l10LGenericNested0"); - private TestParametersLGeneric l10LGenericNested1 = new TestParametersLGeneric("l10LGenericNested1"); - private Map<String, TestParametersLGeneric> l10LGenericNestedMap = new LinkedHashMap<>(); - - /** - * Default constructor. - */ - public TestParametersL10() { - // Default Constructor - } - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public TestParametersL10(final String name) { - super(name); - - TestParametersLGeneric l10LGenericNestedMapVal0 = new TestParametersLGeneric("l10LGenericNestedMapVal0"); - l10LGenericNestedMap.put(l10LGenericNestedMapVal0.getName(), l10LGenericNestedMapVal0); - TestParametersLGeneric l10LGenericNestedMapVal1 = new TestParametersLGeneric("l10LGenericNestedMapVal1"); - l10LGenericNestedMap.put(l10LGenericNestedMapVal1.getName(), l10LGenericNestedMapVal1); - } - - public int getL10IntField() { - return l10IntField; - } - - public String getL10StringField() { - return l10StringField; - } - - public TestParametersLGeneric getL10LGenericNested0() { - return l10LGenericNested0; - } - - public TestParametersLGeneric getL10LGenericNested1() { - return l10LGenericNested1; - } - - public Map<String, TestParametersLGeneric> getL10LGenericNestedMap() { - return l10LGenericNestedMap; - } - - public void setL10IntField(int l10IntField) { - this.l10IntField = l10IntField; - } - - public void setL10StringField(String l10StringField) { - this.l10StringField = l10StringField; - } - - public void setL10LGenericNested0(TestParametersLGeneric l10lGenericNested0) { - l10LGenericNested0 = l10lGenericNested0; - } - - public void setL10LGenericNested1(TestParametersLGeneric l10lGenericNested1) { - l10LGenericNested1 = l10lGenericNested1; - } - - public void setL10LGenericNestedMap(Map<String, TestParametersLGeneric> l10lGenericNestedMap) { - l10LGenericNestedMap = l10lGenericNestedMap; - } - - /** - * Trigger a validation message. - * - * @param level Number of levels to recurse before stopping - */ - public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) { - if (level == 0) { - return; - } - else { - level--; - } - - switch (triggerStatus) { - case CLEAN: - l10StringField = "Legal " + this.getClass().getName(); - l10IntField = 0; - break; - case OBSERVATION: - l10StringField = "aString"; - l10IntField = 2; - break; - case WARNING: - l10StringField = L10_STRING_FIELD; - l10IntField = 3; - break; - case INVALID: - l10StringField = ""; - l10IntField = -1; - break; - default: - break; - } - - l10LGenericNested0.triggerValidationStatus(triggerStatus, level); - l10LGenericNested1.triggerValidationStatus(triggerStatus, level); - - for (TestParametersLGeneric nestedParameterGroup : l10LGenericNestedMap.values()) { - nestedParameterGroup.triggerValidationStatus(triggerStatus, level); - } - } - - @Override - public GroupValidationResult validate() { - GroupValidationResult validationResult = super.validate(); - - if (StringUtils.isBlank(l10StringField)) { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.INVALID, - "l10StringField must be a non-blank string"); - } else if (l10StringField.equals(L10_STRING_FIELD)) { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.WARNING, - "using the field name for the parameter value is dangerous"); - } else if (l10StringField.equals("aString")) { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.OBSERVATION, - "this value for name is unhelpful"); - } else { - validationResult.setResult(L10_STRING_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - if (l10IntField < 0) { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.INVALID, - "l10IntField must be a positive integer"); - } else if (l10IntField > 2) { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.WARNING, - "values greater than 2 are not recommended"); - } else if (l10IntField == 2) { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.OBSERVATION, "this field has been set to 2"); - } else { - validationResult.setResult(L10_INT_FIELD, ValidationStatus.CLEAN, - ParameterConstants.PARAMETER_HAS_STATUS_MESSAGE + ValidationStatus.CLEAN.toString()); - } - - if (l10LGenericNested0 != null) { - validationResult.setResult("l10LGenericNested0", l10LGenericNested0.validate()); - } - validationResult.setResult("l10LGenericNested1", l10LGenericNested1.validate()); - - for (Entry<String, TestParametersLGeneric> nestedGroupEntry : l10LGenericNestedMap.entrySet()) { - validationResult.setResult("l10LGenericNestedMap", nestedGroupEntry.getKey(), - nestedGroupEntry.getValue().validate()); - } - - return validationResult; - } -} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java deleted file mode 100644 index f9d6cdc4..00000000 --- a/common-parameters/src/test/java/org/onap/policy/common/parameters/testclasses/TestParametersLGeneric.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.parameters.testclasses; - -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.parameters.ParameterGroupImpl; -import org.onap.policy.common.parameters.ValidationStatus; -import org.onap.policy.common.parameters.annotations.NotBlank; -import org.onap.policy.common.parameters.annotations.NotNull; - -public class TestParametersLGeneric extends ParameterGroupImpl { - private static final String LGENERIC_INT_FIELD = "lgenericIntField"; - private static final String LGENERIC_STRING_FIELD = "lgenericStringField"; - - private int lgenericIntField = 0; - - @NotNull @NotBlank - private String lgenericStringField = "Legal " + this.getClass().getName(); - - /** - * Default constructor. - */ - public TestParametersLGeneric() { - // Default Constructor - } - - /** - * Create a test parameter group. - * - * @param name the parameter group name - */ - public TestParametersLGeneric(final String name) { - super(name); - } - - public int getLgenericIntField() { - return lgenericIntField; - } - - public String getLgenericStringField() { - return lgenericStringField; - } - - public void setLgenericIntField(int lgenericIntField) { - this.lgenericIntField = lgenericIntField; - } - - public void setLgenericStringField(String lgenericStringField) { - this.lgenericStringField = lgenericStringField; - } - - /** - * Trigger a validation message. - * - * @param level Number of levels to recurse before stopping - */ - public void triggerValidationStatus(final ValidationStatus triggerStatus, int level) { - if (level == 0) { - return; - } - - switch (triggerStatus) { - case CLEAN: - lgenericStringField = "Legal " + this.getClass().getName(); - lgenericIntField = 0; - break; - case OBSERVATION: - lgenericStringField = "aString"; - lgenericIntField = 2; - break; - case WARNING: - lgenericStringField = LGENERIC_STRING_FIELD; - lgenericIntField = 3; - break; - case INVALID: - lgenericStringField = ""; - lgenericIntField = -1; - break; - default: - break; - } - - } - - @Override - public GroupValidationResult validate() { - GroupValidationResult validationResult = super.validate(); - - if (LGENERIC_STRING_FIELD.equals(lgenericStringField)) { - validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.WARNING, - "using the field name for the parameter value is dangerous"); - } else if ("aString".equals(lgenericStringField)) { - validationResult.setResult(LGENERIC_STRING_FIELD, ValidationStatus.OBSERVATION, - "this value for name is unhelpful"); - } - - if (lgenericIntField < 0) { - validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.INVALID, - "lgenericIntField must be a positive integer"); - } else if (lgenericIntField > 2) { - validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.WARNING, - "values greater than 2 are not recommended"); - } else if (lgenericIntField == 2) { - validationResult.setResult(LGENERIC_INT_FIELD, ValidationStatus.OBSERVATION, - "this field has been set to 2"); - } - - return validationResult; - } -} |