diff options
Diffstat (limited to 'utils/src/test/java/org/onap')
14 files changed, 447 insertions, 131 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/PropertyCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java index 47453dfc..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 @@ -33,15 +33,29 @@ 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('\'', '"'); 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 a468f0b4..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-2020 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. @@ -52,6 +52,7 @@ 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; @@ -358,13 +359,9 @@ public class StandardCoderTest { } + @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/StandardYamlCoderTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java index c770cd3b..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 @@ -97,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 b8730a65..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 @@ -3,6 +3,7 @@ * Common Utils * ================================================================================ * 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,7 +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 3981e2af..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 @@ -3,6 +3,7 @@ * Common Utils * ================================================================================ * 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,7 +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 3b6e4955..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-2020 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,7 +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; @@ -55,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(); @@ -72,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 4ae72842..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-2020 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,6 +20,7 @@ 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; @@ -91,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/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 2e122187..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-2020 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,7 +31,6 @@ 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; @@ -78,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()); } /** @@ -183,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); + } } /** @@ -264,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); } @@ -309,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 @@ -323,16 +304,16 @@ public class ResourceUtilsTest { assertEquals("testdir/testfile.xml", normalizePath(resultD0.iterator().next())); Set<String> resultD1 = ResourceUtils.getDirectoryContents("org/onap/policy/common"); - assertTrue(resultD1.size() > 0); + 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", - normalizePath(resultD2.iterator().next())); + normalizePath(resultD2.iterator().next())); Set<String> resultJ0 = ResourceUtils.getDirectoryContents("com"); - assertEquals(189, resultJ0.size()); + assertTrue(resultJ0.contains("com/google/gson/")); assertEquals("com/google/", normalizePath(resultJ0.iterator().next())); Set<String> resultJ1 = ResourceUtils.getDirectoryContents("com/google/gson"); @@ -346,6 +327,7 @@ public class ResourceUtilsTest { /** * Normalizes a path name, replacing OS-specific separators with "/". + * * @param pathName path name to be normalized * @return the normalized path name */ 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 67cdab52..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,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * 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. @@ -21,11 +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 +} |