diff options
Diffstat (limited to 'utils/src/test/java/org')
27 files changed, 1361 insertions, 240 deletions
diff --git a/utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java b/utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java new file mode 100644 index 00000000..b45f107d --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021, 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.common.utils.cmd; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.junit.Test; + +public class TestCommandLineArguments { + private static final String FAKE_HELP_CLASS = "org.onap.policy.HelpClass"; + private static final String FAKE_COMPONENT = "fake policy cpm"; + private static final String TEST_CONFIG_FILE = "cmdFiles/configuration.json"; + private static final String TEST_PROPERTY_FILE = "cmdFiles/property.json"; + private static final String ERR_MSG_INVALID_ARGS = "invalid command line arguments specified"; + private static final String ERR_MSG_POLICY_CONFIG_FILE = + "fake policy cpm configuration file was not specified as an argument"; + + CommandLineArgumentsHandler testCmd = new CommandLineArgumentsHandler(FAKE_HELP_CLASS, FAKE_COMPONENT); + + @Test + public void testVersion() throws CommandLineException { + String[] version = {"-v"}; + assertThat(testCmd.parse(version)).startsWith("ONAP Version test."); + } + + @Test + public void testHelp() throws CommandLineException { + String[] help = {"-h"}; + assertThat(testCmd.parse(help)).startsWith("usage: org.onap.policy.HelpClass [options...]"); + } + + @Test + public void testParse() throws CommandLineException { + String[] args = {"-c", TEST_CONFIG_FILE}; + testCmd.parse(args); + + assertTrue(testCmd.checkSetConfigurationFilePath()); + assertThat(testCmd.getFullConfigurationFilePath()).contains(TEST_CONFIG_FILE); + } + + @Test + public void testParse_ShouldThrowExceptionWithInvalidArguments() { + String[] invalidArgs = {"-a"}; + assertThatThrownBy(() -> testCmd.parse(invalidArgs)).hasMessage(ERR_MSG_INVALID_ARGS) + .hasRootCauseMessage("Unrecognized option: -a"); + } + + @Test + public void testParse_ShouldThrowExceptionWithExtraArguments() { + String[] remainingArgs = {"-c", TEST_CONFIG_FILE, "extraArgs"}; + String expectedErrorMsg = + "too many command line arguments specified: [-c, cmdFiles/configuration.json, extraArgs]"; + assertThatThrownBy(() -> testCmd.parse(remainingArgs)).hasMessage(expectedErrorMsg); + } + + @Test + public void testParse_ShouldThrowExceptionWhenFileNameNull() { + String[] nullArgs = {"-c", null}; + assertThatThrownBy(() -> testCmd.parse(nullArgs)).hasMessage(ERR_MSG_INVALID_ARGS); + } + + @Test + public void testValidate() throws CommandLineException { + String[] validConfigArgs = {"-c", TEST_CONFIG_FILE}; + testCmd.parse(validConfigArgs); + assertThatCode(() -> testCmd.validate()).doesNotThrowAnyException(); + } + + @Test + public void testValidate_ShouldThrowExceptionWhenConfigFileNotPresent() throws CommandLineException { + String[] versionArgs = {"-v"}; + testCmd.parse(versionArgs); + assertValidate(versionArgs, ERR_MSG_POLICY_CONFIG_FILE); + } + + @Test + public void testValidate_ShouldThrowExceptionWhenFileNameEmpty() { + String[] argsOnlyKeyNoValue = {"-c", ""}; + assertValidate(argsOnlyKeyNoValue, ERR_MSG_POLICY_CONFIG_FILE); + assertFalse(testCmd.checkSetConfigurationFilePath()); + } + + @Test + public void testValidate_ShouldThrowExceptionWhenFileNameEmptySpace() { + String[] argsOnlyKeyNoValue = {"-c", " "}; + assertValidate(argsOnlyKeyNoValue, ERR_MSG_POLICY_CONFIG_FILE); + assertFalse(testCmd.checkSetConfigurationFilePath()); + } + + @Test + public void testValidate_ShouldThrowExceptionWhenFileNameDoesNotExist() { + String[] fileNameNotExistentArgs = {"-c", "someFileName.json"}; + assertValidate(fileNameNotExistentArgs, + "fake policy cpm configuration file \"someFileName.json\" does not exist"); + } + + @Test + public void testValidate_ShouldThrowExceptionWhenFileNameIsNotFile() { + String[] folderAsFileNameArgs = {"-c", "src/test/resources"}; + assertValidate(folderAsFileNameArgs, + "fake policy cpm configuration file \"src/test/resources\" is not a normal file"); + } + + @Test + public void testAddExtraOptions() throws CommandLineException { + Option extra = Option.builder("p").longOpt("property-file") + .desc("the full path to the topic property file to use, the property file contains the " + + FAKE_COMPONENT + " properties") + .hasArg().argName("PROP_FILE").required(false).type(String.class).build(); + + CommandLineArgumentsHandler testCmdExtraOpt = + new CommandLineArgumentsHandler(FAKE_HELP_CLASS, FAKE_COMPONENT, extra); + + String[] args = {"-p", TEST_PROPERTY_FILE}; + testCmdExtraOpt.parse(args); + + assertTrue(testCmdExtraOpt.checkSetPropertyFilePath()); + assertThat(testCmdExtraOpt.getFullPropertyFilePath()).contains(TEST_PROPERTY_FILE); + + String[] argsNoProperty = {"-p", ""}; + testCmdExtraOpt.parse(argsNoProperty); + + assertFalse(testCmdExtraOpt.checkSetPropertyFilePath()); + } + + @Test + public void testNewOptions() throws CommandLineException { + Options newOptions = new Options(); + newOptions.addOption( + Option.builder("a").longOpt("fake-option").desc("the fake property to check command line parse") + .hasArg().argName("FAKE_OPT").required(false).type(String.class).build()); + + CommandLineArgumentsHandler testCmdExtraOpt = + new CommandLineArgumentsHandler(FAKE_HELP_CLASS, FAKE_COMPONENT, newOptions); + + String[] args = {"-a", "aaaa"}; + testCmdExtraOpt.parse(args); + + assertTrue(testCmdExtraOpt.getCommandLine().hasOption("a")); + + // should raise exception as -c is not present on options; + // default options should've been replaced by constructor parameter. + String[] argsError = {"-c", "aaaa.json"}; + assertThatThrownBy(() -> testCmdExtraOpt.parse(argsError)).hasMessage(ERR_MSG_INVALID_ARGS) + .hasRootCauseMessage("Unrecognized option: -c"); + } + + private void assertValidate(String[] testArgs, String expectedErrorMsg) { + try { + testCmd.parse(testArgs); + } catch (CommandLineException e) { + fail(e.getMessage()); + } + assertThatThrownBy(() -> testCmd.validate()).hasMessage(expectedErrorMsg); + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java new file mode 100644 index 00000000..01821504 --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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. + * 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.utils.coder; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import org.junit.Before; +import org.junit.Test; + +public class CoderTest { + private static final Long LONG = 10L; + private static final Integer INTEGER = 10; + private static final String INT_TEXT = INTEGER.toString(); + private static final String TEXT = "some text"; + private static final String ENCODED = "encoded value"; + private static final String DECODED = "decoded value"; + + private MyCoder coder; + + @Before + public void setUp() { + coder = new MyCoder(); + } + + @Test + public void testConvert() throws CoderException { + assertNull(coder.convert(null, String.class)); + + // same class of object + assertEquals(TEXT, coder.convert(TEXT, String.class)); + assertEquals(INTEGER, coder.convert(INTEGER, Integer.class)); + + // source is a string + assertEquals(INTEGER, coder.convert(TEXT, Integer.class)); + + // target is a string + assertEquals(INT_TEXT, coder.convert(INTEGER, String.class)); + + // source and target are different types, neither is a string + assertEquals(INTEGER, coder.convert(LONG, Integer.class)); + } + + private static class MyCoder implements Coder { + @Override + public String encode(Object object) throws CoderException { + return (object.getClass() == String.class ? ENCODED : INT_TEXT); + } + + @Override + public String encode(Object object, boolean pretty) throws CoderException { + // unused + return null; + } + + @Override + public void encode(Writer target, Object object) throws CoderException { + // unused + } + + @Override + public void encode(OutputStream target, Object object) throws CoderException { + // unused + } + + @Override + public void encode(File target, Object object) throws CoderException { + // unused + } + + @Override + public <T> T decode(String json, Class<T> clazz) throws CoderException { + return (clazz == String.class ? clazz.cast(DECODED) : clazz.cast(INTEGER)); + } + + @Override + public <T> T decode(Reader source, Class<T> clazz) throws CoderException { + // unused + return null; + } + + @Override + public <T> T decode(InputStream source, Class<T> clazz) throws CoderException { + // unused + return null; + } + + @Override + public <T> T decode(File source, Class<T> clazz) throws CoderException { + // unused + return null; + } + + @Override + public StandardCoderObject toStandard(Object object) throws CoderException { + // unused + return null; + } + + @Override + public <T> T fromStandard(StandardCoderObject sco, Class<T> clazz) throws CoderException { + // unused + return null; + } + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java index 83017e70..86f8a1b1 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * 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. @@ -23,28 +23,39 @@ package org.onap.policy.common.utils.coder; import static org.junit.Assert.assertEquals; import com.google.gson.annotations.SerializedName; - import java.io.Reader; import java.io.StringReader; import java.util.List; - import lombok.Getter; - import org.junit.Before; import org.junit.Test; public class PropertyCoderTest { private PropertyCoder propertyCoder = null; private static final String AES_ENCRYPTION_KEY = "aes_encryption_key"; + + /* + * Note: to generate the encrypted values, invoke CryptoUtils passing both the value + * to be encrypted and the secret key. + * + * The secret key should typically be 32 characters long, resulting in a 256-bit + * key, and is placed in "aes_encryption_key". + * + * For "xacml.pdp.rest.password", the encrypted value was generated via: + * java org.onap.policy.common.utils.security.CryptoUtils enc alpha abcdefghijklmnopqrstuvwxyzabcdef + * + * For "pass", the encrypted value was generated via: + * java org.onap.policy.common.utils.security.CryptoUtils enc hello abcdefghijklmnopqrstuvwxyzabcdef + */ private static final String json = ("{'aes_encryption_key':'abcdefghijklmnopqrstuvwxyzabcdef'" - + ",'xacml.pdp.rest.password':'enc:YZ8EqzsxIOzIuK416SWAdrv+0cKKkqsQt/NYH9+uxwI='" + + ",'xacml.pdp.rest.password':'enc:FSfOhDygtmnX3gkMSfTFMoBFW+AG5k6goNj2KZgQmeF0DqgcMg=='" + ",'xacml.pdp.rest.user':'testpdp'" + ",'xacml.pdp.rest.client.user':'policy'" + ",'xacml.pdp.rest.client.password':'policy'" + ",'xacml.pdp.rest.environment':'TEST'" + ",'servers':[{'name':'server1','port':'10'," - + "'pass':'enc:KXIY94KcAapOAAeFbtjQL4kBPB4k+NJfwdP+GpG3LWQ='}" + + "'pass':'enc:08Fj6tLhmWjkZkf52O2A2ZNT8PpL80yEOEKXlbV/gnm0lkR9OA=='}" + ",{'name':'server2','port':'20','pass':'plaintext'}]" + "}").replace('\'', '"'); @@ -102,4 +113,4 @@ public class PropertyCoderTest { private String port; private String pass; } -}
\ No newline at end of file +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java new file mode 100644 index 00000000..ec977da6 --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java @@ -0,0 +1,160 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * 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. + * 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.utils.coder; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import com.google.gson.JsonElement; +import java.io.StringReader; +import java.io.StringWriter; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import lombok.ToString; +import org.junit.Before; +import org.junit.Test; + +public class StandardCoderInstantAsMillisTest { + private static final long INSTANT_MILLIS = 1583249713500L; + private static final String INSTANT_TEXT = String.valueOf(INSTANT_MILLIS); + + private StandardCoder coder; + + @Before + public void setUp() { + coder = new StandardCoderInstantAsMillis(); + } + + @Test + public void testConvert() throws CoderException { + MyObject obj = makeObject(); + + @SuppressWarnings("unchecked") + Map<String, Object> map = coder.convert(obj, LinkedHashMap.class); + + assertThat(map.toString()).contains(INSTANT_TEXT); + + MyObject obj2 = coder.convert(map, MyObject.class); + assertEquals(obj.toString(), obj2.toString()); + } + + @Test + public void testEncodeDecode() throws CoderException { + MyObject obj = makeObject(); + assertThat(coder.encode(obj, false)).contains(INSTANT_TEXT); + assertThat(coder.encode(obj, true)).contains(INSTANT_TEXT); + + String json = coder.encode(obj); + MyObject obj2 = coder.decode(json, MyObject.class); + assertEquals(obj.toString(), obj2.toString()); + + StringWriter wtr = new StringWriter(); + coder.encode(wtr, obj); + json = wtr.toString(); + assertThat(json).contains(INSTANT_TEXT); + + StringReader rdr = new StringReader(json); + obj2 = coder.decode(rdr, MyObject.class); + assertEquals(obj.toString(), obj2.toString()); + } + + @Test + public void testJson() { + MyObject obj = makeObject(); + assertThat(coder.toPrettyJson(obj)).contains(INSTANT_TEXT); + } + + @Test + public void testToJsonTree_testFromJsonJsonElementClassT() throws Exception { + MyMap map = new MyMap(); + map.props = new LinkedHashMap<>(); + map.props.put("jel keyA", "jel valueA"); + map.props.put("jel keyB", "jel valueB"); + + JsonElement json = coder.toJsonTree(map); + assertEquals("{'props':{'jel keyA':'jel valueA','jel keyB':'jel valueB'}}".replace('\'', '"'), json.toString()); + + Object result = coder.fromJson(json, MyMap.class); + + assertNotNull(result); + assertEquals("{jel keyA=jel valueA, jel keyB=jel valueB}", result.toString()); + } + + @Test + public void testConvertFromDouble() throws Exception { + String text = "[listA, {keyA=100}, 200]"; + assertEquals(text, coder.decode(text, Object.class).toString()); + + text = "{keyB=200}"; + assertEquals(text, coder.decode(text, Object.class).toString()); + } + + @Test + public void testToStandard() throws Exception { + MyObject obj = makeObject(); + StandardCoderObject sco = coder.toStandard(obj); + assertNotNull(sco.getData()); + assertEquals("{'abc':'xyz','instant':1583249713500}".replace('\'', '"'), sco.getData().toString()); + + // class instead of object -> exception + assertThatThrownBy(() -> coder.toStandard(String.class)).isInstanceOf(CoderException.class); + } + + @Test + public void testFromStandard() throws Exception { + MyObject obj = new MyObject(); + obj.abc = "pdq"; + StandardCoderObject sco = coder.toStandard(obj); + + MyObject obj2 = coder.fromStandard(sco, MyObject.class); + assertEquals(obj.toString(), obj2.toString()); + + // null class -> exception + assertThatThrownBy(() -> coder.fromStandard(sco, null)).isInstanceOf(CoderException.class); + } + + + private MyObject makeObject() { + MyObject obj = new MyObject(); + obj.abc = "xyz"; + obj.instant = Instant.ofEpochMilli(INSTANT_MILLIS); + return obj; + } + + + @ToString + private static class MyObject { + private String abc; + private Instant instant; + } + + public static class MyMap { + private Map<String, Object> props; + + @Override + public String toString() { + return props.toString(); + } + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java index 44086f30..1748aed3 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * 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. @@ -20,6 +20,7 @@ package org.onap.policy.common.utils.coder; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -34,10 +35,11 @@ public class StandardCoderObjectTest { private static final String PROP1 = "abc"; private static final String PROP2 = "ghi"; + private static final Integer PROP2_INDEX = 1; private static final String PROP2b = "jkl"; private static final String VAL1 = "def"; private static final String VAL2 = "mno"; - private static final String JSON = "{'abc':'def','ghi':{'jkl':'mno'}}".replace('\'', '"'); + private static final String JSON = "{'abc':'def','ghi':[{},{'jkl':'mno'}]}".replace('\'', '"'); private StandardCoderObject sco; @@ -68,7 +70,7 @@ public class StandardCoderObjectTest { assertEquals(VAL1, sco.getString(PROP1)); // multiple fields - assertEquals(VAL2, sco.getString(PROP2, PROP2b)); + assertEquals(VAL2, sco.getString(PROP2, PROP2_INDEX, PROP2b)); // not found assertNull(sco.getString("xyz")); @@ -85,5 +87,44 @@ public class StandardCoderObjectTest { // not a JSON object assertNull(sco.getString(PROP1, PROP2)); + + // invalid subscript + assertThatIllegalArgumentException().isThrownBy(() -> sco.getString(10.0)); + } + + @Test + public void testGetFieldFromObject() { + // not an object + assertNull(sco.getFieldFromObject(fromJson("[]"), PROP1)); + + // field doesn't exist + assertNull(sco.getFieldFromObject(fromJson("{}"), "non-existent")); + + // field exists + assertEquals(4, sco.getFieldFromObject(fromJson("{\"world\":4}"), "world").getAsInt()); + } + + @Test + public void testGetItemFromArray() { + // not an array + assertNull(sco.getItemFromArray(fromJson("{}"), 0)); + + // negative index + assertThatIllegalArgumentException().isThrownBy(() -> sco.getItemFromArray(fromJson("[]"), -1)); + + // index out of bounds + assertNull(sco.getItemFromArray(fromJson("[5]"), 1)); + assertNull(sco.getItemFromArray(fromJson("[5]"), 2)); + + // index exists + assertEquals(6, sco.getItemFromArray(fromJson("[5,6,7]"), 1).getAsInt()); + + // edge case: first and last item + assertEquals(50, sco.getItemFromArray(fromJson("[50,60,70]"), 0).getAsInt()); + assertEquals(700, sco.getItemFromArray(fromJson("[500,600,700]"), 2).getAsInt()); + } + + private JsonElement fromJson(String json) { + return gson.fromJson(json, JsonElement.class); } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java index 2a70f85a..33c7331e 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP PAP * ================================================================================ - * 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. @@ -23,12 +23,15 @@ package org.onap.policy.common.utils.coder; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; +import com.google.gson.JsonSyntaxException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -45,8 +48,11 @@ import java.nio.file.Files; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.TreeMap; +import lombok.ToString; import org.junit.Before; import org.junit.Test; @@ -64,6 +70,35 @@ public class StandardCoderTest { } @Test + public void testConvert() throws CoderException { + // null source + assertNull(coder.convert(null, StandardCoderObject.class)); + + // same class of object + StandardCoderObject sco = new StandardCoderObject(); + assertSame(sco, coder.convert(sco, StandardCoderObject.class)); + + // source is a string + assertEquals(Integer.valueOf(10), coder.convert("10", Integer.class)); + + // target is a string + assertEquals("10", coder.convert(10, String.class)); + + // source and target are different types, neither is a string + sco = coder.convert(Map.of("hello", "world"), StandardCoderObject.class); + assertEquals("world", sco.getString("hello")); + + // throw an exeception + coder = new StandardCoder() { + @Override + protected <T> T fromJson(JsonElement json, Class<T> clazz) { + throw jpe; + } + }; + assertThatThrownBy(() -> coder.convert(10, Long.class)).isInstanceOf(CoderException.class).hasCause(jpe); + } + + @Test public void testEncodeObject() throws Exception { List<Integer> arr = Arrays.asList(1100, 1110); assertEquals("[1100,1110]", coder.encode(arr)); @@ -75,6 +110,32 @@ public class StandardCoderTest { } @Test + public void testEncodeObjectBoolean() throws Exception { + final List<Integer> arr = Arrays.asList(1100, 1110); + + /* + * As plain json. + */ + assertEquals("[1100,1110]", coder.encode(arr, false)); + + // test exception case + coder = spy(new StandardCoder()); + when(coder.toJson(arr)).thenThrow(jpe); + assertThatThrownBy(() -> coder.encode(arr, false)).isInstanceOf(CoderException.class).hasCause(jpe); + + + /* + * As pretty json. + */ + assertEquals("[\n 1100,\n 1110\n]", coder.encode(arr, true)); + + // test exception case + coder = spy(new StandardCoder()); + when(coder.toPrettyJson(arr)).thenThrow(jpe); + assertThatThrownBy(() -> coder.encode(arr, true)).isInstanceOf(CoderException.class).hasCause(jpe); + } + + @Test public void testEncodeWriterObject() throws Exception { List<Integer> arr = Arrays.asList(1200, 1210); StringWriter wtr = new StringWriter(); @@ -260,7 +321,9 @@ public class StandardCoderTest { assertEquals(json, coder.toJson(sco)); // invalid json -> exception - assertThatThrownBy(() -> coder.fromJson(new StringReader("["), StandardCoderObject.class)); + StringReader rdr = new StringReader("["); + assertThatThrownBy(() -> coder.fromJson(rdr, StandardCoderObject.class)) + .isInstanceOf(JsonSyntaxException.class); } @Test @@ -281,16 +344,24 @@ public class StandardCoderTest { assertEquals(-10, map.props.get("negInt")); assertEquals(100000000000L, map.props.get("posLong")); assertEquals(12.5, map.props.get("doubleVal")); + + // test when decoding into a map + @SuppressWarnings("unchecked") + Map<String, Object> map2 = coder.decode("{'intValue':10, 'dblVal':20.1}", TreeMap.class); + assertEquals("{dblVal=20.1, intValue=10}", map2.toString()); + } + + @Test + public void testListDouble() throws Exception { + @SuppressWarnings("unchecked") + List<Object> list = coder.decode("[10, 20.1, 30]", LinkedList.class); + assertEquals("[10, 20.1, 30]", list.toString()); } + @ToString private static class MyObject { private String abc; - - @Override - public String toString() { - return "MyObject [abc=" + abc + "]"; - } } public static class MyMap { diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java new file mode 100644 index 00000000..2fcdb0dd --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java @@ -0,0 +1,165 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 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. + * 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.utils.coder; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.worldturner.medeia.api.ValidationFailedException; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.junit.Before; +import org.junit.Test; + +public class StandardValCoderTest { + private String jsonSchema; + private String validJson; + private String missingReqJson; + private String badRegexJson; + + @Data + @NoArgsConstructor + public static class ValOuter { + @Data + @NoArgsConstructor + public static class ValInner { + public String subItemString; + public Integer subItemInteger; + } + + public String aaString; + public int anInteger; + public boolean aaBoolean; + public List<ValInner> aaCollection; + } + + @Before + public void testSetUp() throws Exception { + jsonSchema = getJson("src/test/resources/org/onap/policy/common/utils/coder/test.schema.json"); + validJson = getJson("src/test/resources/org/onap/policy/common/utils/coder/valid.json"); + missingReqJson = getJson("src/test/resources/org/onap/policy/common/utils/coder/missing-required.json"); + badRegexJson = getJson("src/test/resources/org/onap/policy/common/utils/coder/bad-regex.json"); + } + + @Test + public void testDecode() throws CoderException { + StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema"); + + ValOuter valOuter = valCoder.decode(validJson, ValOuter.class); + assertValidJson(valOuter); + + StringReader reader = new StringReader(validJson); + valOuter = valCoder.decode(reader, ValOuter.class); + assertValidJson(valOuter); + + try { + valCoder.decode(missingReqJson, ValOuter.class); + fail("missing required field should have been flagged by the schema validation"); + } catch (CoderException e) { + assertEquals("required", ((ValidationFailedException) e.getCause()).getFailures().get(0).getRule()); + assertEquals("aaCollection", + ((ValidationFailedException) e.getCause()).getFailures().get(0).getProperty()); + assertEquals("Required property aaCollection is missing from object", + ((ValidationFailedException) e.getCause()).getFailures().get(0).getMessage()); + } + + try { + valCoder.decode(badRegexJson, ValOuter.class); + fail("bad regex should have been flagged by the schema validation"); + } catch (CoderException e) { + assertEquals("properties", ((ValidationFailedException) e.getCause()).getFailures().get(0).getRule()); + assertEquals("aaString", + ((ValidationFailedException) e.getCause()).getFailures().get(0).getProperty()); + assertEquals("Property validation failed", + ((ValidationFailedException) e.getCause()).getFailures().get(0).getMessage()); + assertEquals("pattern", + ((ValidationFailedException) e.getCause()).getFailures() + .get(0).getDetails().iterator().next().getRule()); + assertEquals("Pattern ^([a-z]*)$ is not contained in text", + ((ValidationFailedException) e.getCause()).getFailures() + .get(0).getDetails().iterator().next().getMessage()); + } + } + + @Test + public void testEncode() throws CoderException { + StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema"); + ValOuter valOuter = valCoder.decode(validJson, ValOuter.class); + + String valOuterJson = valCoder.encode(valOuter); + assertEquals(valOuter, valCoder.decode(valOuterJson, ValOuter.class)); + assertValidJson(valOuter); + + StringWriter writer = new StringWriter(); + valCoder.encode(writer, valOuter); + assertEquals(valOuterJson, writer.toString()); + + // test exception case with an empty object + assertThatThrownBy(() -> valCoder.encode(new ValOuter())).isInstanceOf(CoderException.class); + } + + @Test + public void testPretty() throws CoderException { + StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema"); + ValOuter valOuter = valCoder.decode(validJson, ValOuter.class); + + String valOuterJson = valCoder.encode(valOuter); + assertEquals(valOuterJson, valCoder.encode(valOuter, false)); + String prettyValOuterJson = valCoder.encode(valOuter, true); + assertNotEquals(valOuterJson, prettyValOuterJson); + + assertEquals(valOuter, valCoder.decode(prettyValOuterJson, ValOuter.class)); + + // test exception cases with an empty object + assertThatThrownBy(() -> valCoder.encode(new ValOuter(), false)).isInstanceOf(CoderException.class); + assertThatThrownBy(() -> valCoder.encode(new ValOuter(), true)).isInstanceOf(CoderException.class); + } + + @Test + public void testConformance() { + StandardValCoder valCoder = new StandardValCoder(jsonSchema, "test-schema"); + assertTrue(valCoder.isConformant(validJson)); + assertFalse(valCoder.isConformant(missingReqJson)); + assertFalse(valCoder.isConformant(badRegexJson)); + } + + private void assertValidJson(ValOuter valOuter) { + assertEquals("abcd", valOuter.getAaString()); + assertEquals(90, valOuter.getAnInteger()); + assertTrue(valOuter.isAaBoolean()); + assertEquals("defg", valOuter.getAaCollection().get(0).getSubItemString()); + assertEquals(Integer.valueOf(1200), valOuter.getAaCollection().get(0).getSubItemInteger()); + } + + private String getJson(String filePath) throws IOException { + return new String(Files.readAllBytes(Paths.get(filePath))); + } +}
\ No newline at end of file diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java index e38c5c9c..cadeb055 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * 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. @@ -20,8 +20,11 @@ package org.onap.policy.common.utils.coder; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import java.io.File; import java.io.StringWriter; @@ -45,6 +48,25 @@ public class StandardYamlCoderTest { } @Test + public void testToPrettyJson() throws CoderException { + String expected = coder.encode(cont); + assertEquals(expected, coder.encode(cont, false)); + + String yaml = coder.encode(cont, true); + assertEquals(expected, yaml); + + Container cont2 = coder.decode(yaml, Container.class); + assertEquals(cont, cont2); + + // test exception cases + IllegalArgumentException expex = new IllegalArgumentException("expected exception"); + coder = spy(new StandardYamlCoder()); + when(coder.toJson(cont)).thenThrow(expex); + assertThatThrownBy(() -> coder.encode(cont, false)).isInstanceOf(CoderException.class).hasCause(expex); + assertThatThrownBy(() -> coder.encode(cont, true)).isInstanceOf(CoderException.class).hasCause(expex); + } + + @Test public void testToJsonObject() throws CoderException { String yaml = coder.encode(cont); @@ -75,6 +97,12 @@ public class StandardYamlCoderTest { } @Test + public void testFromJsonDoubleToInteger() throws Exception { + Object value = coder.decode("20", Object.class); + assertEquals(Integer.valueOf(20), value); + } + + @Test public void testStandardTypeAdapter() throws Exception { String yaml = "abc: def\n"; StandardCoderObject sco = coder.fromJson(yaml, StandardCoderObject.class); diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java index 589d0924..17d7f7ff 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Common Utils * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 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. @@ -25,8 +26,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import javax.persistence.EntityManager; - +import jakarta.persistence.EntityManager; import org.junit.Before; import org.junit.Test; diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java index ca2b7220..0e8edca2 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Common Utils * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2020 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. @@ -25,8 +26,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import javax.persistence.EntityManagerFactory; - +import jakarta.persistence.EntityManagerFactory; import org.junit.Before; import org.junit.Test; diff --git a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java index d764e9d0..dc63c673 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * Common Utils * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-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. @@ -27,8 +28,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import javax.persistence.EntityTransaction; - +import jakarta.persistence.EntityTransaction; import org.junit.Before; import org.junit.Test; @@ -56,7 +56,7 @@ public class EntityTransCloserTest { public void testEntityTransCloser() { EntityTransCloser entityTransCloser = new EntityTransCloser(trans); - assertEquals(trans, entityTransCloser.getTransation()); + assertEquals(trans, entityTransCloser.getTransaction()); // verify that transaction was started verify(trans).begin(); @@ -73,7 +73,7 @@ public class EntityTransCloserTest { @Test public void testGetTransation() { try (EntityTransCloser t = new EntityTransCloser(trans)) { - assertEquals(trans, t.getTransation()); + assertEquals(trans, t.getTransaction()); } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java new file mode 100644 index 00000000..79db2093 --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java @@ -0,0 +1,53 @@ +/*- +* ============LICENSE_START======================================================= +* ONAP Policy +* ================================================================================ +* 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.utils.logging; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerUtilsTest { + protected static final Logger logger = LoggerFactory.getLogger(LoggerUtilsTest.class); + + @Test + public void testMarker() { + assertTrue(logger.isInfoEnabled()); + logger.info("line 1"); + logger.info(LoggerUtils.METRIC_LOG_MARKER, "line 1 Metric"); + logger.info(LoggerUtils.AUDIT_LOG_MARKER, "line 1 Audit"); + logger.info(LoggerUtils.SECURITY_LOG_MARKER, "line 1 Security"); + logger.info(LoggerUtils.TRANSACTION_LOG_MARKER, "line 1 Transaction"); + LoggerUtils.setLevel(LoggerUtils.ROOT_LOGGER, "debug"); + logger.debug("line 2"); + logger.debug(LoggerUtils.METRIC_LOG_MARKER, "line 2 Metric"); + logger.debug(LoggerUtils.AUDIT_LOG_MARKER, "line 2 Audit"); + logger.debug(LoggerUtils.SECURITY_LOG_MARKER, "line 2 Security"); + logger.info(LoggerUtils.TRANSACTION_LOG_MARKER, "line 2 Transaction"); + assertTrue(logger.isDebugEnabled()); + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java b/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java index a0b8353d..4019ca79 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-utils * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-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,8 +20,10 @@ package org.onap.policy.common.utils.network; +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.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -67,7 +69,7 @@ public class NetworkUtilTest { public void testAllocPort_testAllocPortString__testAllocPortInetSocketAddress() throws Exception { // allocate wild-card port int wildCardPort = NetworkUtil.allocPort(); - assertTrue(wildCardPort != 0); + assertNotEquals(0, wildCardPort); // verify that we can listen on the port try (ServerSocket wildSocket = new ServerSocket(wildCardPort)) { @@ -78,10 +80,10 @@ public class NetworkUtilTest { // allocate port using host name int localPort = NetworkUtil.allocPort(LOCALHOST); - assertTrue(localPort != 0); + assertNotEquals(0, localPort); // the OS should have allocated a new port, even though the first has been closed - assertTrue(localPort != wildCardPort); + assertNotEquals(wildCardPort, localPort); try (ServerSocket localSocket = new ServerSocket()) { localSocket.bind(new InetSocketAddress(LOCALHOST, localPort)); @@ -90,6 +92,15 @@ public class NetworkUtilTest { } } + @Test + public void testGenUniqueName() { + String name = NetworkUtil.genUniqueName(LOCALHOST); + assertThat(name).isNotBlank().isNotEqualTo(LOCALHOST); + + // second call should generate a different value + assertThat(NetworkUtil.genUniqueName(LOCALHOST)).isNotEqualTo(name); + } + /** * Thread that accepts a connection on a socket. */ diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java index 07e0795f..7da4eccd 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP - Common Modules * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * 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. @@ -80,6 +80,10 @@ public class BeanConfiguratorTest { @Test public void testConfigureFromProperties() throws PropertyException { + testStringValueNoDefault(); + } + + private void testStringValueNoDefault() throws PropertyException { props.setProperty(THE_VALUE, STRING_VALUE); PlainStringConfig cfg = new PlainStringConfig(); @@ -177,11 +181,7 @@ public class BeanConfiguratorTest { @Test public void testSetValueObjectFieldProperties_FieldSet() throws PropertyException { - props.setProperty(THE_VALUE, STRING_VALUE); - PlainStringConfig cfg = new PlainStringConfig(); - beancfg.configureFromProperties(cfg, props); - - assertEquals(STRING_VALUE, cfg.value); + testStringValueNoDefault(); } @Test @@ -500,11 +500,7 @@ public class BeanConfiguratorTest { @Test public void testGetStringValue() throws PropertyException { - props.setProperty(THE_VALUE, STRING_VALUE); - PlainStringConfig cfg = new PlainStringConfig(); - beancfg.configureFromProperties(cfg, props); - - assertEquals(STRING_VALUE, cfg.value); + testStringValueNoDefault(); } @Test @@ -721,12 +717,7 @@ public class BeanConfiguratorTest { @Test public void testGetPropValue_Prop_NoDefault() throws PropertyException { - props.setProperty(THE_VALUE, STRING_VALUE); - - PlainStringConfig cfg = new PlainStringConfig(); - beancfg.configureFromProperties(cfg, props); - - assertEquals(STRING_VALUE, cfg.value); + testStringValueNoDefault(); } @Test @@ -960,18 +951,8 @@ public class BeanConfiguratorTest { @Test(expected = PropertyInvalidException.class) public void testCheckDefaultValue_Empty_EmptyOk_Invalid() throws PropertyException { - class Config { - - @Property(name = THE_VALUE, defaultValue = "", accept = "empty") - private long value; - - @SuppressWarnings("unused") - public void setValue(long value) { - this.value = value; - } - } - beancfg.configureFromProperties(new Config(), props); + beancfg.configureFromProperties(new PrimLongDefaultBlankAcceptEmptyConfig(), props); } @Test @@ -1005,18 +986,8 @@ public class BeanConfiguratorTest { @Test(expected = PropertyMissingException.class) public void testIsEmptyOkPropertyString_False() throws PropertyException { - class Config { - - @Property(name = THE_VALUE, defaultValue = "", accept = "") - private long value; - @SuppressWarnings("unused") - public void setValue(long value) { - this.value = value; - } - } - - beancfg.configureFromProperties(new Config(), props); + beancfg.configureFromProperties(new PrimLongDefaultBlankAcceptBlankConfig(), props); } @Test @@ -1040,18 +1011,8 @@ public class BeanConfiguratorTest { @Test(expected = PropertyMissingException.class) public void testIsEmptyOkProperty_False() throws PropertyException { - class Config { - - @Property(name = THE_VALUE, defaultValue = "", accept = "") - private long value; - - @SuppressWarnings("unused") - public void setValue(long value) { - this.value = value; - } - } - beancfg.configureFromProperties(new Config(), props); + beancfg.configureFromProperties(new PrimLongDefaultBlankAcceptBlankConfig(), props); } @Test @@ -1420,6 +1381,26 @@ public class BeanConfiguratorTest { } } + class PrimLongDefaultBlankAcceptEmptyConfig { + + @Property(name = THE_VALUE, defaultValue = "", accept = "empty") + private long value; + + public void setValue(long value) { + this.value = value; + } + } + + class PrimLongDefaultBlankAcceptBlankConfig { + + @Property(name = THE_VALUE, defaultValue = "", accept = "") + private long value; + + public void setValue(long value) { + this.value = value; + } + } + /** * This is just used as a mix-in to ensure that the configuration ignores interfaces. */ diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java new file mode 100644 index 00000000..93b30643 --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java @@ -0,0 +1,212 @@ +/*- + * ============LICENSE_START======================================================= + * 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. + * 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.utils.properties; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.AbstractSet; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import org.junit.Test; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; + +public class PropertyObjectUtilsTest { + + @Test + public void testToObject() { + Map<String, String> map = Map.of("abc", "def", "ghi", "jkl"); + Properties props = new Properties(); + props.putAll(map); + + // with empty prefix + Map<String, Object> result = PropertyObjectUtils.toObject(props, ""); + assertEquals(map, result); + + // with dotted prefix - other items skipped + map = Map.of("pfx.abc", "def", "ghi", "jkl", "pfx.mno", "pqr", "differentpfx.stu", "vwx"); + props.clear(); + props.putAll(Map.of("pfx.abc", "def", "ghi", "jkl", "pfx.mno", "pqr", "differentpfx.stu", "vwx")); + result = PropertyObjectUtils.toObject(props, "pfx."); + map = Map.of("abc", "def", "mno", "pqr"); + assertEquals(map, result); + + // undotted prefix - still skips other items + result = PropertyObjectUtils.toObject(props, "pfx"); + assertEquals(map, result); + } + + @Test + public void testSetProperty() { + // one, two, and three components in the name, the last two with subscripts + Map<String, Object> map = Map.of("one", "one.abc", "two.def", "two.ghi", "three.jkl.mno[0]", "three.pqr", + "three.jkl.mno[1]", "three.stu"); + Properties props = new Properties(); + props.putAll(map); + + Map<String, Object> result = PropertyObjectUtils.toObject(props, ""); + // @formatter:off + map = Map.of( + "one", "one.abc", + "two", Map.of("def", "two.ghi"), + "three", Map.of("jkl", + Map.of("mno", + List.of("three.pqr", "three.stu")))); + // @formatter:on + assertEquals(map, result); + } + + @Test + public void testGetNode() { + Map<String, Object> map = Map.of("abc[0].def", "node.ghi", "abc[0].jkl", "node.mno", "abc[1].def", "node.pqr"); + Properties props = new Properties(); + props.putAll(map); + + Map<String, Object> result = PropertyObjectUtils.toObject(props, ""); + // @formatter:off + map = Map.of( + "abc", + List.of( + Map.of("def", "node.ghi", "jkl", "node.mno"), + Map.of("def", "node.pqr") + )); + // @formatter:on + assertEquals(map, result); + + } + + @Test + public void testExpand() { + // add subscripts out of order + Properties props = makeProperties("abc[2]", "expand.def", "abc[1]", "expand.ghi"); + + Map<String, Object> result = PropertyObjectUtils.toObject(props, ""); + // @formatter:off + Map<String, Object> map = + Map.of("abc", + Arrays.asList(null, "expand.ghi", "expand.def")); + // @formatter:on + assertEquals(map, result); + + } + + @Test + public void testGetObject() { + // first value is primitive, while second is a map + Properties props = makeProperties("object.abc", "object.def", "object.abc.ghi", "object.jkl"); + + Map<String, Object> result = PropertyObjectUtils.toObject(props, ""); + // @formatter:off + Map<String, Object> map = + Map.of("object", + Map.of("abc", + Map.of("ghi", "object.jkl"))); + // @formatter:on + assertEquals(map, result); + } + + @Test + public void testGetArray() { + // first value is primitive, while second is an array + Properties props = makeProperties("array.abc", "array.def", "array.abc[0].ghi", "array.jkl"); + + Map<String, Object> result = PropertyObjectUtils.toObject(props, ""); + // @formatter:off + Map<String, Object> map = + Map.of("array", + Map.of("abc", + List.of( + Map.of("ghi", "array.jkl")))); + // @formatter:on + assertEquals(map, result); + } + + @Test + @SuppressWarnings("unchecked") + public void testCompressLists() throws IOException, CoderException { + assertEquals("plain-string", PropertyObjectUtils.compressLists("plain-string").toString()); + + // @formatter:off + Map<String, Object> map = + Map.of( + "cmp.abc", "cmp.def", + "cmp.ghi", + Arrays.asList(null, "cmp.list1", null, "cmp.list2", + Map.of("cmp.map", Arrays.asList("cmp.map.list1", "cmp.map1.list2", null)))); + // @formatter:on + + // the data structure needs to be modifiable, so we'll encode/decode it + StandardCoder coder = new StandardCoder(); + map = coder.decode(coder.encode(map), LinkedHashMap.class); + + PropertyObjectUtils.compressLists(map); + + // @formatter:off + Map<String, Object> expected = + Map.of( + "cmp.abc", "cmp.def", + "cmp.ghi", + Arrays.asList("cmp.list1", "cmp.list2", + Map.of("cmp.map", Arrays.asList("cmp.map.list1", "cmp.map1.list2")))); + // @formatter:on + assertEquals(expected, map); + } + + /** + * Makes properties containing the specified key/value pairs. The property set returns + * names in the order listed. + * + * @return a new properties containing the specified key/value pairs + */ + private Properties makeProperties(String key1, String value1, String key2, String value2) { + // control the order in which the names are returned + List<String> keyList = List.of(key1, key2); + + Set<String> keySet = new AbstractSet<>() { + @Override + public Iterator<String> iterator() { + return keyList.iterator(); + } + + @Override + public int size() { + return 2; + } + }; + + Properties props = new Properties() { + private static final long serialVersionUID = 1L; + + @Override + public Set<String> stringPropertyNames() { + return keySet; + } + }; + + props.putAll(Map.of(key1, value1, key2, value2)); + + return props; + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java index 190fddd5..ef2051d8 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 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. * 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. @@ -28,46 +28,46 @@ import org.junit.Test; public class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTester { /** - * Test method for + * Test method for * {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException * (java.lang.String, java.lang.String)}. */ @Test public void testPropertyAccessExceptionStringField() { - doTestPropertyExceptionStringField_AllPopulated( new PropertyAccessException(PROPERTY, FIELD)); - doTestPropertyExceptionStringField_NullProperty( new PropertyAccessException(null, FIELD)); - doTestPropertyExceptionStringField_NullField( new PropertyAccessException(PROPERTY, null)); - doTestPropertyExceptionStringField_BothNull( new PropertyAccessException(null, null)); + verifyPropertyExceptionStringField_AllPopulated(new PropertyAccessException(PROPERTY, FIELD)); + verifyPropertyExceptionStringField_NullProperty(new PropertyAccessException(null, FIELD)); + verifyPropertyExceptionStringField_NullField(new PropertyAccessException(PROPERTY, null)); + verifyPropertyExceptionStringField_BothNull(new PropertyAccessException(null, null)); } /** - * Test method for + * Test method for * {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException * (java.lang.String, java.lang.String, java.lang.String)}. */ @Test public void testPropertyAccessExceptionStringFieldString() { - doTestPropertyExceptionStringFieldString(new PropertyAccessException(PROPERTY, FIELD, MESSAGE)); + verifyPropertyExceptionStringFieldString(new PropertyAccessException(PROPERTY, FIELD, MESSAGE)); } /** - * Test method for + * Test method for * {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException * (java.lang.String, java.lang.String, java.lang.Throwable)}. */ @Test public void testPropertyAccessExceptionStringFieldThrowable() { - doTestPropertyExceptionStringFieldThrowable(new PropertyAccessException(PROPERTY, FIELD, THROWABLE)); + verifyPropertyExceptionStringFieldThrowable(new PropertyAccessException(PROPERTY, FIELD, THROWABLE)); } /** - * Test method for + * Test method for * {@link org.onap.policy.common.utils.properties.exception.PropertyAccessException#PropertyAccessException * (java.lang.String, java.lang.String, java.lang.String, java.lang.Throwable)}. */ @Test public void testPropertyAccessExceptionStringFieldStringThrowable() { - doTestPropertyExceptionStringFieldStringThrowable( + verifyPropertyExceptionStringFieldStringThrowable( new PropertyAccessException(PROPERTY, FIELD, MESSAGE, THROWABLE)); } diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java index c4803912..91879763 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 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. * 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. @@ -34,10 +34,10 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti */ @Test public void testPropertyExceptionStringField() { - doTestPropertyExceptionStringField_AllPopulated(new PropertyAnnotationException(PROPERTY, FIELD)); - doTestPropertyExceptionStringField_NullProperty(new PropertyAnnotationException(null, FIELD)); - doTestPropertyExceptionStringField_NullField(new PropertyAnnotationException(PROPERTY, null)); - doTestPropertyExceptionStringField_BothNull(new PropertyAnnotationException(null, null)); + verifyPropertyExceptionStringField_AllPopulated(new PropertyAnnotationException(PROPERTY, FIELD)); + verifyPropertyExceptionStringField_NullProperty(new PropertyAnnotationException(null, FIELD)); + verifyPropertyExceptionStringField_NullField(new PropertyAnnotationException(PROPERTY, null)); + verifyPropertyExceptionStringField_BothNull(new PropertyAnnotationException(null, null)); } /** @@ -47,7 +47,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti */ @Test public void testPropertyExceptionStringFieldString() { - doTestPropertyExceptionStringFieldString(new PropertyAnnotationException(PROPERTY, FIELD, MESSAGE)); + verifyPropertyExceptionStringFieldString(new PropertyAnnotationException(PROPERTY, FIELD, MESSAGE)); } /** @@ -57,7 +57,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti */ @Test public void testPropertyExceptionStringFieldThrowable() { - doTestPropertyExceptionStringFieldThrowable(new PropertyAnnotationException(PROPERTY, FIELD, THROWABLE)); + verifyPropertyExceptionStringFieldThrowable(new PropertyAnnotationException(PROPERTY, FIELD, THROWABLE)); } /** @@ -67,7 +67,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti */ @Test public void testPropertyExceptionStringFieldStringThrowable() { - doTestPropertyExceptionStringFieldStringThrowable( + verifyPropertyExceptionStringFieldStringThrowable( new PropertyAnnotationException(PROPERTY, FIELD, MESSAGE, THROWABLE)); } diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java index 9055aeb7..9166749b 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 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. * 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. @@ -34,10 +34,10 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester { */ @Test public void testPropertyExceptionStringField() { - doTestPropertyExceptionStringField_AllPopulated(new PropertyException(PROPERTY, FIELD)); - doTestPropertyExceptionStringField_NullProperty(new PropertyException(null, FIELD)); - doTestPropertyExceptionStringField_NullField(new PropertyException(PROPERTY, null)); - doTestPropertyExceptionStringField_BothNull(new PropertyException(null, null)); + verifyPropertyExceptionStringField_AllPopulated(new PropertyException(PROPERTY, FIELD)); + verifyPropertyExceptionStringField_NullProperty(new PropertyException(null, FIELD)); + verifyPropertyExceptionStringField_NullField(new PropertyException(PROPERTY, null)); + verifyPropertyExceptionStringField_BothNull(new PropertyException(null, null)); } /** @@ -47,7 +47,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester { */ @Test public void testPropertyExceptionStringFieldString() { - doTestPropertyExceptionStringFieldString(new PropertyException(PROPERTY, FIELD, MESSAGE)); + verifyPropertyExceptionStringFieldString(new PropertyException(PROPERTY, FIELD, MESSAGE)); } /** @@ -57,7 +57,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester { */ @Test public void testPropertyExceptionStringFieldThrowable() { - doTestPropertyExceptionStringFieldThrowable(new PropertyException(PROPERTY, FIELD, THROWABLE)); + verifyPropertyExceptionStringFieldThrowable(new PropertyException(PROPERTY, FIELD, THROWABLE)); } /** @@ -67,7 +67,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester { */ @Test public void testPropertyExceptionStringFieldStringThrowable() { - doTestPropertyExceptionStringFieldStringThrowable(new PropertyException(PROPERTY, FIELD, MESSAGE, THROWABLE)); + verifyPropertyExceptionStringFieldStringThrowable(new PropertyException(PROPERTY, FIELD, MESSAGE, THROWABLE)); } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java index 69ab1bd3..3edd7ff4 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 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. * 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. @@ -34,10 +34,10 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT */ @Test public void testPropertyExceptionStringField() { - doTestPropertyExceptionStringField_AllPopulated(new PropertyInvalidException(PROPERTY, FIELD)); - doTestPropertyExceptionStringField_NullProperty(new PropertyInvalidException(null, FIELD)); - doTestPropertyExceptionStringField_NullField(new PropertyInvalidException(PROPERTY, null)); - doTestPropertyExceptionStringField_BothNull(new PropertyInvalidException(null, null)); + verifyPropertyExceptionStringField_AllPopulated(new PropertyInvalidException(PROPERTY, FIELD)); + verifyPropertyExceptionStringField_NullProperty(new PropertyInvalidException(null, FIELD)); + verifyPropertyExceptionStringField_NullField(new PropertyInvalidException(PROPERTY, null)); + verifyPropertyExceptionStringField_BothNull(new PropertyInvalidException(null, null)); } /** @@ -47,7 +47,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT */ @Test public void testPropertyExceptionStringFieldString() { - doTestPropertyExceptionStringFieldString(new PropertyInvalidException(PROPERTY, FIELD, MESSAGE)); + verifyPropertyExceptionStringFieldString(new PropertyInvalidException(PROPERTY, FIELD, MESSAGE)); } /** @@ -57,7 +57,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT */ @Test public void testPropertyExceptionStringFieldThrowable() { - doTestPropertyExceptionStringFieldThrowable(new PropertyInvalidException(PROPERTY, FIELD, THROWABLE)); + verifyPropertyExceptionStringFieldThrowable(new PropertyInvalidException(PROPERTY, FIELD, THROWABLE)); } /** @@ -67,7 +67,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT */ @Test public void testPropertyExceptionStringFieldStringThrowable() { - doTestPropertyExceptionStringFieldStringThrowable( + verifyPropertyExceptionStringFieldStringThrowable( new PropertyInvalidException(PROPERTY, FIELD, MESSAGE, THROWABLE)); } diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java index 81a7c36a..948bc18e 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 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. * 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. @@ -34,10 +34,10 @@ public class PropertyMissingExceptionTest extends SupportBasicPropertyExceptionT */ @Test public void testPropertyExceptionStringField() { - doTestPropertyExceptionStringField_AllPopulated(new PropertyMissingException(PROPERTY, FIELD)); - doTestPropertyExceptionStringField_NullProperty(new PropertyMissingException(null, FIELD)); - doTestPropertyExceptionStringField_NullField(new PropertyMissingException(PROPERTY, null)); - doTestPropertyExceptionStringField_BothNull(new PropertyMissingException(null, null)); + verifyPropertyExceptionStringField_AllPopulated(new PropertyMissingException(PROPERTY, FIELD)); + verifyPropertyExceptionStringField_NullProperty(new PropertyMissingException(null, FIELD)); + verifyPropertyExceptionStringField_NullField(new PropertyMissingException(PROPERTY, null)); + verifyPropertyExceptionStringField_BothNull(new PropertyMissingException(null, null)); } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java index 97503f8c..be3f8183 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 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. * 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. @@ -20,11 +20,9 @@ package org.onap.policy.common.utils.properties.exception; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -import org.hamcrest.CoreMatchers; /** * Superclass used to test subclasses of {@link PropertyException}. @@ -52,45 +50,45 @@ public class SupportBasicPropertyExceptionTester { protected static final String FIELD = "PROPERTY"; /* - * Methods to perform various tests on the except subclass. + * Methods to perform various tests on the except subclass. */ - protected void doTestPropertyExceptionStringField_AllPopulated(PropertyException ex) { + protected void verifyPropertyExceptionStringField_AllPopulated(PropertyException ex) { standardTests(ex); } - protected void doTestPropertyExceptionStringField_NullProperty(PropertyException ex) { + protected void verifyPropertyExceptionStringField_NullProperty(PropertyException ex) { assertEquals(null, ex.getPropertyName()); assertEquals(FIELD, ex.getFieldName()); assertNotNull(ex.getMessage()); assertNotNull(ex.toString()); } - protected void doTestPropertyExceptionStringField_NullField(PropertyException ex) { + protected void verifyPropertyExceptionStringField_NullField(PropertyException ex) { assertEquals(PROPERTY, ex.getPropertyName()); assertEquals(null, ex.getFieldName()); assertNotNull(ex.getMessage()); assertNotNull(ex.toString()); } - protected void doTestPropertyExceptionStringField_BothNull(PropertyException ex) { + protected void verifyPropertyExceptionStringField_BothNull(PropertyException ex) { assertEquals(null, ex.getPropertyName()); assertEquals(null, ex.getFieldName()); assertNotNull(ex.getMessage()); assertNotNull(ex.toString()); } - protected void doTestPropertyExceptionStringFieldString(PropertyException ex) { + protected void verifyPropertyExceptionStringFieldString(PropertyException ex) { standardTests(ex); standardMessageTests(ex); } - protected void doTestPropertyExceptionStringFieldThrowable(PropertyException ex) { + protected void verifyPropertyExceptionStringFieldThrowable(PropertyException ex) { standardTests(ex); standardThrowableTests(ex); } - protected void doTestPropertyExceptionStringFieldStringThrowable(PropertyException ex) { + protected void verifyPropertyExceptionStringFieldStringThrowable(PropertyException ex) { standardTests(ex); standardMessageTests(ex); standardThrowableTests(ex); @@ -98,7 +96,7 @@ public class SupportBasicPropertyExceptionTester { /** * Performs standard tests that should apply to all subclasses. - * + * * @param ex exception to test */ protected void standardTests(PropertyException ex) { @@ -111,17 +109,17 @@ public class SupportBasicPropertyExceptionTester { /** * Performs standard tests for exceptions that were provided a message in their * constructor. - * + * * @param ex exception to test */ protected void standardMessageTests(PropertyException ex) { - assertThat(ex.getMessage(), CoreMatchers.endsWith(MESSAGE)); + assertThat(ex.getMessage()).endsWith(MESSAGE); } /** * Performs standard tests for exceptions that were provided a throwable in their * constructor. - * + * * @param ex exception to test */ protected void standardThrowableTests(PropertyException ex) { diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java new file mode 100644 index 00000000..c12ef9f8 --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java @@ -0,0 +1,42 @@ +/*- + * ============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.utils.resources; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Path; +import org.apache.commons.io.FileUtils; +import org.junit.Test; + +public class DirectoryUtilsTest { + + @Test + public void testCreateTempDirectory() throws IOException { + Path path = DirectoryUtils.createTempDirectory("directoryUtilsTest"); + + var file = path.toFile(); + FileUtils.forceDeleteOnExit(file); + + assertThat(file).canRead().canWrite().isDirectory(); + assertThat(file.canExecute()).isTrue(); + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java index 2991009f..c56409ee 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java @@ -1,8 +1,8 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2020-2021, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ package org.onap.policy.common.utils.resources; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -30,11 +31,9 @@ import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Set; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -79,12 +78,12 @@ public class ResourceUtilsTest { } /** - * Cleandown resource utils test. + * Clean resource utils test. */ @After - public void cleandownResourceUtilsTest() { - tmpEmptyFile.delete(); - tmpUsedFile.delete(); + public void cleanDownResourceUtilsTest() { + assertTrue(tmpEmptyFile.delete()); + assertTrue(tmpUsedFile.delete()); } /** @@ -184,45 +183,26 @@ public class ResourceUtilsTest { * Test get resource as stream. */ @Test - public void testGetResourceAsStream() { - InputStream theStream = ResourceUtils.getResourceAsStream(tmpDir.getAbsolutePath()); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(tmpEmptyFile.getAbsolutePath()); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(tmpUsedFile.getAbsolutePath()); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(jarDirResource); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(jarFileResource); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(PATH_DIR_RESOURCE); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(PATH_FILE_RESOURCE); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(RESOURCES_PATH + PATH_DIR_RESOURCE); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(RESOURCES_PATH + PATH_FILE_RESOURCE); - assertNotNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(NON_EXISTENT_RESOURCE); - assertNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(INVALID_RESOURCE); - assertNull(theStream); - - theStream = ResourceUtils.getResourceAsStream(null); - assertNull(theStream); + public void testGetResourceAsStream() throws IOException { + verifyStream(tmpDir.getAbsolutePath()); + verifyStream(tmpEmptyFile.getAbsolutePath()); + verifyStream(tmpUsedFile.getAbsolutePath()); + verifyStream(jarDirResource); + verifyStream(jarFileResource); + verifyStream(PATH_DIR_RESOURCE); + verifyStream(PATH_FILE_RESOURCE); + verifyStream(RESOURCES_PATH + PATH_DIR_RESOURCE); + verifyStream(RESOURCES_PATH + PATH_FILE_RESOURCE); + assertNull(ResourceUtils.getResourceAsStream(NON_EXISTENT_RESOURCE)); + assertNull(ResourceUtils.getResourceAsStream(INVALID_RESOURCE)); + assertNull(ResourceUtils.getResourceAsStream(null)); + verifyStream(""); + } - theStream = ResourceUtils.getResourceAsStream(""); - assertNotNull(theStream); + private void verifyStream(String path) throws IOException { + try (var theStream = ResourceUtils.getResourceAsStream(path)) { + assertNotNull(theStream); + } } /** @@ -234,10 +214,10 @@ public class ResourceUtilsTest { assertNotNull(theString); theString = ResourceUtils.getResourceAsString(tmpEmptyFile.getAbsolutePath()); - assertTrue(theString.equals("")); + assertEquals("", theString); theString = ResourceUtils.getResourceAsString(tmpUsedFile.getAbsolutePath()); - assertTrue(theString.equals("Bluebirds fly over the rainbow")); + assertEquals("Bluebirds fly over the rainbow", theString); theString = ResourceUtils.getResourceAsString(jarFileResource); assertNotNull(theString); @@ -265,7 +245,7 @@ public class ResourceUtilsTest { theString = ResourceUtils.getResourceAsString(""); - assertEquals("logback-test.xml\nMETA-INF\norg\ntestdir\n", theString); + assertEquals("cmdFiles\nlogback-test.xml\nMETA-INF\norg\ntestdir\nversion.txt\n", theString); } @@ -310,7 +290,7 @@ public class ResourceUtilsTest { assertNull(ResourceUtils.getFilePath4Resource(null)); assertEquals("/something/else", ResourceUtils.getFilePath4Resource("/something/else")); assertTrue(ResourceUtils.getFilePath4Resource("xml/example.xml").endsWith("xml/example.xml")); - assertTrue(ResourceUtils.getFilePath4Resource("com/google").endsWith("com/google")); + assertTrue(ResourceUtils.getFilePath4Resource("com/google").contains("com/google")); } @Test @@ -321,26 +301,37 @@ public class ResourceUtilsTest { Set<String> resultD0 = ResourceUtils.getDirectoryContents("testdir"); assertEquals(1, resultD0.size()); - assertEquals("testdir/testfile.xml", resultD0.iterator().next()); + assertEquals("testdir/testfile.xml", normalizePath(resultD0.iterator().next())); Set<String> resultD1 = ResourceUtils.getDirectoryContents("org/onap/policy/common"); - assertTrue(resultD1.size() > 0); - assertEquals("org/onap/policy/common/utils/", resultD1.iterator().next()); + assertFalse(resultD1.isEmpty()); + assertEquals("org/onap/policy/common/utils/", normalizePath(resultD1.iterator().next())); Set<String> resultD2 = ResourceUtils.getDirectoryContents("org/onap/policy/common/utils/coder"); assertTrue(resultD2.size() >= 15); - assertEquals("org/onap/policy/common/utils/coder/CoderExceptionTest.class", resultD2.iterator().next()); + assertEquals("org/onap/policy/common/utils/coder/CoderExceptionTest.class", + normalizePath(resultD2.iterator().next())); Set<String> resultJ0 = ResourceUtils.getDirectoryContents("com"); - assertEquals(189, resultJ0.size()); - assertEquals("com/google/", resultJ0.iterator().next()); + assertTrue(resultJ0.contains("com/google/gson/")); + assertEquals("com/google/", normalizePath(resultJ0.iterator().next())); - Set<String> resultJ1 = ResourceUtils.getDirectoryContents("com/google/gson/util"); - assertEquals(1, resultJ1.size()); - assertEquals("com/google/gson/util/VersionUtils.class", resultJ1.iterator().next()); + Set<String> resultJ1 = ResourceUtils.getDirectoryContents("com/google/gson"); + assertTrue(resultJ1.size() > 1); + assertTrue(resultJ1.contains("com/google/gson/JsonElement.class")); URL dummyUrl = new URL("http://even/worse"); assertTrue(ResourceUtils.getDirectoryContentsJar(dummyUrl, "nonexistantdirectory").isEmpty()); } + + /** + * Normalizes a path name, replacing OS-specific separators with "/". + * + * @param pathName path name to be normalized + * @return the normalized path name + */ + private String normalizePath(String pathName) { + return pathName.replace(File.separator, "/"); + } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java index 0952b168..91268979 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications 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. @@ -20,12 +21,13 @@ package org.onap.policy.common.utils.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import java.io.IOException; - +import org.apache.commons.io.FileUtils; import org.junit.Test; /** @@ -39,35 +41,80 @@ public class TextFileUtilsTest { @Test public void testPutToFile() throws IOException { - final File tempTextFile = File.createTempFile("Test", "txt"); + final File tempTextFile = File.createTempFile("Test", ".txt"); + tempTextFile.deleteOnExit(); TextFileUtils.putStringAsTextFile(FILE_CONTENT, tempTextFile.getAbsolutePath()); final String textFileString0 = TextFileUtils.getTextFileAsString(tempTextFile.getAbsolutePath()); assertEquals(FILE_CONTENT, textFileString0); - final FileInputStream fis = new FileInputStream(tempTextFile); - final String textFileString1 = TextFileUtils.getStreamAsString(fis); - assertEquals(textFileString0, textFileString1); + try (final FileInputStream fis = new FileInputStream(tempTextFile)) { + final String textFileString1 = TextFileUtils.getStreamAsString(fis); + assertEquals(textFileString0, textFileString1); + } } @Test public void testPutToFileWithNewPath() throws IOException { String tempDirAndFileName = System.getProperty("java.io.tmpdir") + "/non/existant/path/Test.txt"; + FileUtils.forceDeleteOnExit(new File(tempDirAndFileName)); TextFileUtils.putStringAsTextFile(FILE_CONTENT, tempDirAndFileName); final String textFileString0 = TextFileUtils.getTextFileAsString(tempDirAndFileName); assertEquals(FILE_CONTENT, textFileString0); - final FileInputStream fis = new FileInputStream(tempDirAndFileName); - final String textFileString1 = TextFileUtils.getStreamAsString(fis); - assertEquals(textFileString0, textFileString1); + try (final FileInputStream fis = new FileInputStream(tempDirAndFileName)) { + final String textFileString1 = TextFileUtils.getStreamAsString(fis); + assertEquals(textFileString0, textFileString1); + } + } + + @Test + public void testCreateTempFile() throws IOException { + var file = TextFileUtils.createTempFile("textFileUtilsTest", ".txt"); + file.deleteOnExit(); + + verifyDefaultPermissions(file); + } + + @Test + public void testSetDefaultPermissions() throws IOException { + var file = new File("target/tempfile.txt"); + file.deleteOnExit(); + + // ensure it doesn't exist before we create it + file.delete(); + assertThat(file.createNewFile()).isTrue(); + + // check using whatever permissions it comes with + + TextFileUtils.setDefaultPermissions(file); + + verifyDefaultPermissions(file); + + // prevent read-write-execute by anyone + file.setReadable(false); + file.setWritable(false); + file.setExecutable(false); + + TextFileUtils.setDefaultPermissions(file); + + verifyDefaultPermissions(file); + + // make it read-write-execute by everyone + file.setReadable(true); + file.setWritable(true); + file.setExecutable(true); + + TextFileUtils.setDefaultPermissions(file); + + verifyDefaultPermissions(file); + } - File tempDirAndFile = new File(tempDirAndFileName); - tempDirAndFile.delete(); - tempDirAndFile.getParentFile().delete(); - tempDirAndFile.getParentFile().getParentFile().delete(); - tempDirAndFile.getParentFile().getParentFile().getParentFile().delete(); + private void verifyDefaultPermissions(File file) { + assertThat(file).canRead().canWrite(); + assertThat(file.canExecute()).isTrue(); } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java index ce9435d8..625fd1f5 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * 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. @@ -37,7 +37,7 @@ public class CryptoUtilsTest { private static Logger logger = LoggerFactory.getLogger(CryptoUtilsTest.class); private static final String PASS = "HelloWorld"; private static final String SECRET_KEY = "MTIzNDU2Nzg5MDEyMzQ1Ng=="; - private static final String ENCRYPTED_PASS = "enc:hcI2XVX+cxPz/6rlbebkWpCFF6WPbBtT7iJRr2VHUkA="; + private static final String ENCRYPTED_PASS = "enc:Z6QzirpPyDpwmIcNbE3U2iq6g/ubJBEdzssoigxGGChlQtdWOLD8y00O"; private static final String DECRYPTED_MSG = "encrypted value: {} decrypted value : {}"; private static final String ENCRYPTED_MSG = "original value : {} encrypted value: {}"; @@ -120,4 +120,4 @@ public class CryptoUtilsTest { String decryptedAgain = CryptoUtils.decrypt(decryptedValue, SECRET_KEY); assertEquals(decryptedValue, decryptedAgain); } -}
\ No newline at end of file +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java index 232d3409..d111962e 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java @@ -61,7 +61,7 @@ public class FeatureApiUtilsTest { public void testApplyFeatureFalse() { List<String> lst = Arrays.asList("falseF1", "exceptF2", "falseF3"); - assertFalse(FeatureApiUtils.apply(lst, pred, (str,ex) -> errors.add(str))); + assertFalse(FeatureApiUtils.apply(lst, pred, (str, ex) -> errors.add(str))); assertEquals(lst.toString(), tried.toString()); assertEquals("[exceptF2]", errors.toString()); } diff --git a/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java b/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java index 1a45f9e1..4673233e 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP PAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,7 +22,7 @@ package org.onap.policy.common.utils.validation; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -48,7 +48,7 @@ public class VersionTest { public void testHashCode() { int hash = vers.hashCode(); int hash2 = new Version(MAJOR, MINOR, PATCH + 1).hashCode(); - assertTrue(hash != hash2); + assertNotEquals(hash, hash2); } @Test @@ -72,16 +72,16 @@ public class VersionTest { @Test public void testEquals() { - assertFalse(vers.equals(null)); - assertFalse(vers.equals(new Object())); + assertNotEquals(vers, null); + assertNotEquals(vers, new Object()); - assertTrue(vers.equals(vers)); + assertEquals(vers, vers); - assertTrue(vers.equals(new Version(MAJOR, MINOR, PATCH))); + assertEquals(vers, new Version(MAJOR, MINOR, PATCH)); - assertFalse(vers.equals(new Version(MAJOR + 1, MINOR, PATCH))); - assertFalse(vers.equals(new Version(MAJOR, MINOR + 1, PATCH))); - assertFalse(vers.equals(new Version(MAJOR, MINOR, PATCH + 1))); + assertNotEquals(vers, new Version(MAJOR + 1, MINOR, PATCH)); + assertNotEquals(vers, new Version(MAJOR, MINOR + 1, PATCH)); + assertNotEquals(vers, new Version(MAJOR, MINOR, PATCH + 1)); } @Test @@ -89,7 +89,7 @@ public class VersionTest { vers = new Version(101, 201, 301); // equals case - assertTrue(new Version(101, 201, 301).compareTo(vers) == 0); + assertEquals(0, new Version(101, 201, 301).compareTo(vers)); // major takes precedence assertTrue(new Version(102, 200, 300).compareTo(vers) > 0); @@ -139,4 +139,4 @@ public class VersionTest { public void testVersion() { assertEquals("0.0.0", new Version().toString()); } -}
\ No newline at end of file +} |