aboutsummaryrefslogtreecommitdiffstats
path: root/utils/src/test/java/org/onap/policy
diff options
context:
space:
mode:
Diffstat (limited to 'utils/src/test/java/org/onap/policy')
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java181
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/CoderExceptionTest.java24
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/CoderTest.java17
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/PropertyCoderTest.java33
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderInstantAsMillisTest.java27
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderObjectTest.java25
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java60
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java165
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java31
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/coder/YamlJsonTranslatorTest.java25
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrCloserTest.java23
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/jpa/EntityMgrFactoryCloserTest.java23
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/jpa/EntityTransCloserTest.java41
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/logging/LoggerMarkerFilterTest.java155
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java54
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/network/NetworkUtilTest.java38
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/BeanConfiguratorTest.java360
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java24
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/SpecPropertiesTest.java38
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAccessExceptionTest.java13
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyAnnotationExceptionTest.java13
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyExceptionTest.java13
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyInvalidExceptionTest.java13
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/PropertyMissingExceptionTest.java7
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/properties/exception/SupportBasicPropertyExceptionTester.java5
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java43
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/resources/PrometheusUtilsTest.java37
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/resources/ResourceUtilsTest.java114
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/resources/TextFileUtilsTest.java85
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java59
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/FeatureApiUtilsTest.java19
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceImplTest.java21
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceTest.java62
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/RegistryTest.java40
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerContainerTest.java21
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerExceptionTest.java21
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java37
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/time/CurrentTimeTest.java13
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java12
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/validation/TestParameterValidationUtils.java15
-rw-r--r--utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java55
41 files changed, 1282 insertions, 780 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..82ae6636
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/cmd/TestCommandLineArguments.java
@@ -0,0 +1,181 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021-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.
+ * 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.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.junit.jupiter.api.Test;
+
+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
+ void testVersion() throws CommandLineException {
+ String[] version = {"-v"};
+ assertThat(testCmd.parse(version)).startsWith("ONAP Version test.");
+ }
+
+ @Test
+ void testHelp() throws CommandLineException {
+ String[] help = {"-h"};
+ assertThat(testCmd.parse(help)).startsWith("usage: org.onap.policy.HelpClass [options...]");
+ }
+
+ @Test
+ void testParse() throws CommandLineException {
+ String[] args = {"-c", TEST_CONFIG_FILE};
+ testCmd.parse(args);
+
+ assertTrue(testCmd.checkSetConfigurationFilePath());
+ assertThat(testCmd.getFullConfigurationFilePath()).contains(TEST_CONFIG_FILE);
+ }
+
+ @Test
+ void testParse_ShouldThrowExceptionWithInvalidArguments() {
+ String[] invalidArgs = {"-a"};
+ assertThatThrownBy(() -> testCmd.parse(invalidArgs)).hasMessage(ERR_MSG_INVALID_ARGS)
+ .hasRootCauseMessage("Unrecognized option: -a");
+ }
+
+ @Test
+ 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
+ void testParse_ShouldThrowExceptionWhenFileNameNull() {
+ String[] nullArgs = {"-c", null};
+ assertThatThrownBy(() -> testCmd.parse(nullArgs)).hasMessage(ERR_MSG_INVALID_ARGS);
+ }
+
+ @Test
+ void testValidate() throws CommandLineException {
+ String[] validConfigArgs = {"-c", TEST_CONFIG_FILE};
+ testCmd.parse(validConfigArgs);
+ assertThatCode(() -> testCmd.validate()).doesNotThrowAnyException();
+ }
+
+ @Test
+ void testValidate_ShouldThrowExceptionWhenConfigFileNotPresent() throws CommandLineException {
+ String[] versionArgs = {"-v"};
+ testCmd.parse(versionArgs);
+ assertValidate(versionArgs, ERR_MSG_POLICY_CONFIG_FILE);
+ }
+
+ @Test
+ void testValidate_ShouldThrowExceptionWhenFileNameEmpty() {
+ String[] argsOnlyKeyNoValue = {"-c", ""};
+ assertValidate(argsOnlyKeyNoValue, ERR_MSG_POLICY_CONFIG_FILE);
+ assertFalse(testCmd.checkSetConfigurationFilePath());
+ }
+
+ @Test
+ void testValidate_ShouldThrowExceptionWhenFileNameEmptySpace() {
+ String[] argsOnlyKeyNoValue = {"-c", " "};
+ assertValidate(argsOnlyKeyNoValue, ERR_MSG_POLICY_CONFIG_FILE);
+ assertFalse(testCmd.checkSetConfigurationFilePath());
+ }
+
+ @Test
+ void testValidate_ShouldThrowExceptionWhenFileNameDoesNotExist() {
+ String[] fileNameNotExistentArgs = {"-c", "someFileName.json"};
+ assertValidate(fileNameNotExistentArgs,
+ "fake policy cpm configuration file \"someFileName.json\" does not exist");
+ }
+
+ @Test
+ 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
+ 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
+ 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/CoderExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/CoderExceptionTest.java
index cecc4265..9e82c5d8 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/coder/CoderExceptionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/CoderExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,30 +21,31 @@
package org.onap.policy.common.utils.coder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class CoderExceptionTest {
+class CoderExceptionTest {
private static final String STRING_VALUE = "My String";
private static final Throwable CAUSE = new Throwable();
private CoderException exc;
@Test
- public void testCoderException() {
+ void testCoderException() {
exc = new CoderException();
- assertEquals(null, exc.getMessage());
+ assertNull(exc.getMessage());
assertSame(null, exc.getCause());
assertNotNull(exc.toString());
}
@Test
- public void testCoderExceptionString() {
+ void testCoderExceptionString() {
exc = new CoderException(STRING_VALUE);
assertEquals(STRING_VALUE, exc.getMessage());
@@ -52,7 +54,7 @@ public class CoderExceptionTest {
}
@Test
- public void testCoderExceptionThrowable() {
+ void testCoderExceptionThrowable() {
exc = new CoderException(CAUSE);
assertEquals(CAUSE.toString(), exc.getMessage());
@@ -61,7 +63,7 @@ public class CoderExceptionTest {
}
@Test
- public void testCoderExceptionStringThrowable() {
+ void testCoderExceptionStringThrowable() {
exc = new CoderException(STRING_VALUE, CAUSE);
assertEquals(STRING_VALUE, exc.getMessage());
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
index 01821504..fe72292a 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,18 +21,18 @@
package org.onap.policy.common.utils.coder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.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;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class CoderTest {
+class CoderTest {
private static final Long LONG = 10L;
private static final Integer INTEGER = 10;
private static final String INT_TEXT = INTEGER.toString();
@@ -41,13 +42,13 @@ public class CoderTest {
private MyCoder coder;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
coder = new MyCoder();
}
@Test
- public void testConvert() throws CoderException {
+ void testConvert() throws CoderException {
assertNull(coder.convert(null, String.class));
// same class of object
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..d45f43b0 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
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,28 +21,42 @@
package org.onap.policy.common.utils.coder;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.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;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class PropertyCoderTest {
+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('\'', '"');
@@ -50,13 +65,13 @@ public class PropertyCoderTest {
*
* @throws Exception if an error occurs
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
propertyCoder = new PropertyCoder();
}
@Test
- public void testPropertyCoder() {
+ void testPropertyCoder() {
MyClass data = propertyCoder.decode(json, AES_ENCRYPTION_KEY, MyClass.class);
assertEquals("alpha", data.getPdpRestPass());
assertEquals("hello", data.servers.get(0).pass);
@@ -66,7 +81,7 @@ public class PropertyCoderTest {
}
@Test
- public void testPropertyCoderReader() {
+ void testPropertyCoderReader() {
Reader reader = new StringReader(json);
MyClass data = propertyCoder.decode(reader, AES_ENCRYPTION_KEY, MyClass.class);
assertEquals("alpha", data.getPdpRestPass());
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
index ec977da6..6db9e66e 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP PAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -22,8 +23,8 @@ 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 static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.google.gson.JsonElement;
import java.io.StringReader;
@@ -32,22 +33,22 @@ import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.ToString;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class StandardCoderInstantAsMillisTest {
+class StandardCoderInstantAsMillisTest {
private static final long INSTANT_MILLIS = 1583249713500L;
private static final String INSTANT_TEXT = String.valueOf(INSTANT_MILLIS);
private StandardCoder coder;
- @Before
+ @BeforeEach
public void setUp() {
coder = new StandardCoderInstantAsMillis();
}
@Test
- public void testConvert() throws CoderException {
+ void testConvert() throws CoderException {
MyObject obj = makeObject();
@SuppressWarnings("unchecked")
@@ -60,7 +61,7 @@ public class StandardCoderInstantAsMillisTest {
}
@Test
- public void testEncodeDecode() throws CoderException {
+ void testEncodeDecode() throws CoderException {
MyObject obj = makeObject();
assertThat(coder.encode(obj, false)).contains(INSTANT_TEXT);
assertThat(coder.encode(obj, true)).contains(INSTANT_TEXT);
@@ -80,13 +81,13 @@ public class StandardCoderInstantAsMillisTest {
}
@Test
- public void testJson() {
+ void testJson() {
MyObject obj = makeObject();
assertThat(coder.toPrettyJson(obj)).contains(INSTANT_TEXT);
}
@Test
- public void testToJsonTree_testFromJsonJsonElementClassT() throws Exception {
+ void testToJsonTree_testFromJsonJsonElementClassT() {
MyMap map = new MyMap();
map.props = new LinkedHashMap<>();
map.props.put("jel keyA", "jel valueA");
@@ -102,7 +103,7 @@ public class StandardCoderInstantAsMillisTest {
}
@Test
- public void testConvertFromDouble() throws Exception {
+ void testConvertFromDouble() throws Exception {
String text = "[listA, {keyA=100}, 200]";
assertEquals(text, coder.decode(text, Object.class).toString());
@@ -111,7 +112,7 @@ public class StandardCoderInstantAsMillisTest {
}
@Test
- public void testToStandard() throws Exception {
+ void testToStandard() throws Exception {
MyObject obj = makeObject();
StandardCoderObject sco = coder.toStandard(obj);
assertNotNull(sco.getData());
@@ -122,7 +123,7 @@ public class StandardCoderInstantAsMillisTest {
}
@Test
- public void testFromStandard() throws Exception {
+ void testFromStandard() throws Exception {
MyObject obj = new MyObject();
obj.abc = "pdq";
StandardCoderObject sco = coder.toStandard(obj);
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 1748aed3..c597b7f6 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
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -21,16 +22,16 @@
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;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class StandardCoderObjectTest {
+class StandardCoderObjectTest {
private static final Gson gson = new Gson();
private static final String PROP1 = "abc";
@@ -48,24 +49,24 @@ public class StandardCoderObjectTest {
*
* @throws Exception if an error occurs
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
sco = new StandardCoderObject(gson.fromJson(JSON, JsonElement.class));
}
@Test
- public void testStandardCoderObject() {
+ void testStandardCoderObject() {
assertNull(new StandardCoderObject().getData());
}
@Test
- public void testStandardCoderObjectJsonElement() {
+ void testStandardCoderObjectJsonElement() {
assertNotNull(sco.getData());
assertEquals(JSON, gson.toJson(sco.getData()));
}
@Test
- public void testGetString() throws Exception {
+ void testGetString() throws Exception {
// one field
assertEquals(VAL1, sco.getString(PROP1));
@@ -93,7 +94,7 @@ public class StandardCoderObjectTest {
}
@Test
- public void testGetFieldFromObject() {
+ void testGetFieldFromObject() {
// not an object
assertNull(sco.getFieldFromObject(fromJson("[]"), PROP1));
@@ -105,7 +106,7 @@ public class StandardCoderObjectTest {
}
@Test
- public void testGetItemFromArray() {
+ void testGetItemFromArray() {
// not an array
assertNull(sco.getItemFromArray(fromJson("{}"), 0));
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..269893e7 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,8 @@
* ============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.
+ * Modifications Copyright (C) 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.
@@ -21,10 +22,10 @@
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.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@@ -52,10 +53,11 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-import org.junit.Before;
-import org.junit.Test;
+import lombok.ToString;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class StandardCoderTest {
+class StandardCoderTest {
private static final String EXPECTED_EXCEPTION = "expected exception";
private static final JsonParseException jpe = new JsonParseException(EXPECTED_EXCEPTION);
@@ -63,13 +65,13 @@ public class StandardCoderTest {
private StandardCoder coder;
- @Before
+ @BeforeEach
public void setUp() {
coder = new StandardCoder();
}
@Test
- public void testConvert() throws CoderException {
+ void testConvert() throws CoderException {
// null source
assertNull(coder.convert(null, StandardCoderObject.class));
@@ -98,7 +100,7 @@ public class StandardCoderTest {
}
@Test
- public void testEncodeObject() throws Exception {
+ void testEncodeObject() throws Exception {
List<Integer> arr = Arrays.asList(1100, 1110);
assertEquals("[1100,1110]", coder.encode(arr));
@@ -109,7 +111,7 @@ public class StandardCoderTest {
}
@Test
- public void testEncodeObjectBoolean() throws Exception {
+ void testEncodeObjectBoolean() throws Exception {
final List<Integer> arr = Arrays.asList(1100, 1110);
/*
@@ -135,7 +137,7 @@ public class StandardCoderTest {
}
@Test
- public void testEncodeWriterObject() throws Exception {
+ void testEncodeWriterObject() throws Exception {
List<Integer> arr = Arrays.asList(1200, 1210);
StringWriter wtr = new StringWriter();
coder.encode(wtr, arr);
@@ -148,7 +150,7 @@ public class StandardCoderTest {
}
@Test
- public void testEncodeOutputStreamObject() throws Exception {
+ void testEncodeOutputStreamObject() throws Exception {
List<Integer> arr = Arrays.asList(1300, 1310);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
coder.encode(stream, arr);
@@ -170,7 +172,7 @@ public class StandardCoderTest {
}
@Test
- public void testEncodeFileObject() throws Exception {
+ void testEncodeFileObject() throws Exception {
File file = new File(getClass().getResource(StandardCoder.class.getSimpleName() + ".json").getFile() + "X");
file.deleteOnExit();
List<Integer> arr = Arrays.asList(1400, 1410);
@@ -194,7 +196,7 @@ public class StandardCoderTest {
}
@Test
- public void testDecodeStringClass() throws Exception {
+ void testDecodeStringClass() throws Exception {
String text = "[2200,2210]";
assertEquals(text, coder.decode(text, JsonElement.class).toString());
@@ -206,7 +208,7 @@ public class StandardCoderTest {
}
@Test
- public void testDecodeReaderClass() throws Exception {
+ void testDecodeReaderClass() throws Exception {
String text = "[2300,2310]";
assertEquals(text, coder.decode(new StringReader(text), JsonElement.class).toString());
@@ -218,7 +220,7 @@ public class StandardCoderTest {
}
@Test
- public void testDecodeInputStreamClass() throws Exception {
+ void testDecodeInputStreamClass() throws Exception {
String text = "[2400,2410]";
assertEquals(text,
coder.decode(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), JsonElement.class)
@@ -235,7 +237,7 @@ public class StandardCoderTest {
}
@Test
- public void testDecodeFileClass() throws Exception {
+ void testDecodeFileClass() throws Exception {
File file = new File(getClass().getResource(StandardCoder.class.getSimpleName() + ".json").getFile());
String text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
assertEquals(text, coder.decode(file, JsonElement.class).toString());
@@ -262,7 +264,7 @@ public class StandardCoderTest {
}
@Test
- public void testToJsonTree_testFromJsonJsonElementClassT() throws Exception {
+ void testToJsonTree_testFromJsonJsonElementClassT() {
MyMap map = new MyMap();
map.props = new LinkedHashMap<>();
map.props.put("jel keyA", "jel valueA");
@@ -278,7 +280,7 @@ public class StandardCoderTest {
}
@Test
- public void testConvertFromDouble() throws Exception {
+ void testConvertFromDouble() throws Exception {
String text = "[listA, {keyA=100}, 200]";
assertEquals(text, coder.decode(text, Object.class).toString());
@@ -287,7 +289,7 @@ public class StandardCoderTest {
}
@Test
- public void testToStandard() throws Exception {
+ void testToStandard() throws Exception {
MyObject obj = new MyObject();
obj.abc = "xyz";
StandardCoderObject sco = coder.toStandard(obj);
@@ -299,7 +301,7 @@ public class StandardCoderTest {
}
@Test
- public void testFromStandard() throws Exception {
+ void testFromStandard() throws Exception {
MyObject obj = new MyObject();
obj.abc = "pdq";
StandardCoderObject sco = coder.toStandard(obj);
@@ -312,7 +314,7 @@ public class StandardCoderTest {
}
@Test
- public void testStandardTypeAdapter() throws Exception {
+ void testStandardTypeAdapter() {
String json = "{'abc':'def'}".replace('\'', '"');
StandardCoderObject sco = coder.fromJson(json, StandardCoderObject.class);
assertNotNull(sco.getData());
@@ -326,7 +328,7 @@ public class StandardCoderTest {
}
@Test
- public void testMapDouble() throws Exception {
+ void testMapDouble() throws Exception {
MyMap map = new MyMap();
map.props = new HashMap<>();
map.props.put("plainString", "def");
@@ -351,20 +353,16 @@ public class StandardCoderTest {
}
@Test
- public void testListDouble() throws Exception {
+ 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
deleted file mode 100644
index 2fcdb0dd..00000000
--- a/utils/src/test/java/org/onap/policy/common/utils/coder/StandardValCoderTest.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * ============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 c770cd3b..d504b82b 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
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -21,8 +22,8 @@
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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@@ -30,25 +31,25 @@ import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.YamlJsonTranslatorTest.Container;
-public class StandardYamlCoderTest {
+class StandardYamlCoderTest {
private static final File YAML_FILE =
new File("src/test/resources/org/onap/policy/common/utils/coder/YamlJsonTranslator.yaml");
private StandardYamlCoder coder;
private Container cont;
- @Before
+ @BeforeEach
public void setUp() throws CoderException {
coder = new StandardYamlCoder();
cont = coder.decode(YAML_FILE, Container.class);
}
@Test
- public void testToPrettyJson() throws CoderException {
+ void testToPrettyJson() throws CoderException {
String expected = coder.encode(cont);
assertEquals(expected, coder.encode(cont, false));
@@ -67,7 +68,7 @@ public class StandardYamlCoderTest {
}
@Test
- public void testToJsonObject() throws CoderException {
+ void testToJsonObject() throws CoderException {
String yaml = coder.encode(cont);
Container cont2 = coder.decode(yaml, Container.class);
@@ -75,7 +76,7 @@ public class StandardYamlCoderTest {
}
@Test
- public void testToJsonWriterObject() throws CoderException {
+ void testToJsonWriterObject() throws CoderException {
StringWriter wtr = new StringWriter();
coder.encode(wtr, cont);
String yaml = wtr.toString();
@@ -85,19 +86,25 @@ public class StandardYamlCoderTest {
}
@Test
- public void testFromJsonStringClassOfT() throws Exception {
+ void testFromJsonStringClassOfT() throws Exception {
String yaml = new String(Files.readAllBytes(YAML_FILE.toPath()), StandardCharsets.UTF_8);
Container cont2 = coder.decode(yaml, Container.class);
assertEquals(cont, cont2);
}
@Test
- public void testFromJsonReaderClassOfT() {
+ void testFromJsonReaderClassOfT() {
YamlJsonTranslatorTest.verify(cont);
}
@Test
- public void testStandardTypeAdapter() throws Exception {
+ void testFromJsonDoubleToInteger() throws Exception {
+ Object value = coder.decode("20", Object.class);
+ assertEquals(Integer.valueOf(20), value);
+ }
+
+ @Test
+ void testStandardTypeAdapter() {
String yaml = "abc: def\n";
StandardCoderObject sco = coder.fromJson(yaml, StandardCoderObject.class);
assertNotNull(sco.getData());
diff --git a/utils/src/test/java/org/onap/policy/common/utils/coder/YamlJsonTranslatorTest.java b/utils/src/test/java/org/onap/policy/common/utils/coder/YamlJsonTranslatorTest.java
index c76b775a..563181c0 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/coder/YamlJsonTranslatorTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/coder/YamlJsonTranslatorTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -21,10 +22,10 @@
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.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileReader;
@@ -35,11 +36,11 @@ import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import lombok.EqualsAndHashCode;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.error.YAMLException;
-public class YamlJsonTranslatorTest {
+class YamlJsonTranslatorTest {
private static final File YAML_FILE =
new File("src/test/resources/org/onap/policy/common/utils/coder/YamlJsonTranslator.yaml");
@@ -51,7 +52,7 @@ public class YamlJsonTranslatorTest {
*
* @throws IOException if an error occurs
*/
- @Before
+ @BeforeEach
public void setUp() throws IOException {
translator = new YamlJsonTranslator();
@@ -61,7 +62,7 @@ public class YamlJsonTranslatorTest {
}
@Test
- public void testToYamlObject() {
+ void testToYamlObject() {
String yaml = translator.toYaml(cont);
Container cont2 = translator.fromYaml(yaml, Container.class);
@@ -69,7 +70,7 @@ public class YamlJsonTranslatorTest {
}
@Test
- public void testToYamlWriterObject() throws IOException {
+ void testToYamlWriterObject() throws IOException {
IOException ex = new IOException("expected exception");
// writer that throws an exception when the write() method is invoked
@@ -96,14 +97,14 @@ public class YamlJsonTranslatorTest {
}
@Test
- public void testFromYamlStringClassOfT() throws IOException {
+ void testFromYamlStringClassOfT() throws IOException {
String yaml = new String(Files.readAllBytes(YAML_FILE.toPath()), StandardCharsets.UTF_8);
Container cont2 = translator.fromYaml(yaml, Container.class);
assertEquals(cont, cont2);
}
@Test
- public void testFromYamlReaderClassOfT() {
+ void testFromYamlReaderClassOfT() {
verify(cont);
}
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..8bd2452d 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-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.
@@ -20,21 +21,21 @@
package org.onap.policy.common.utils.jpa;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import javax.persistence.EntityManager;
-import org.junit.Before;
-import org.junit.Test;
+import jakarta.persistence.EntityManager;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class EntityMgrCloserTest {
+class EntityMgrCloserTest {
private EntityManager mgr;
- @Before
+ @BeforeEach
public void setUp() {
mgr = mock(EntityManager.class);
}
@@ -44,7 +45,7 @@ public class EntityMgrCloserTest {
* Verifies that the constructor does not do anything extra before being closed.
*/
@Test
- public void testEntityMgrCloser() {
+ void testEntityMgrCloser() {
EntityMgrCloser entityMgrCloser = new EntityMgrCloser(mgr);
assertEquals(mgr, entityMgrCloser.getManager());
@@ -58,7 +59,7 @@ public class EntityMgrCloserTest {
}
@Test
- public void testGetManager() {
+ void testGetManager() {
try (EntityMgrCloser c = new EntityMgrCloser(mgr)) {
assertEquals(mgr, c.getManager());
}
@@ -68,7 +69,7 @@ public class EntityMgrCloserTest {
* Verifies that the manager gets closed when close() is invoked.
*/
@Test
- public void testClose() {
+ void testClose() {
EntityMgrCloser entityMgrCloser = new EntityMgrCloser(mgr);
entityMgrCloser.close();
@@ -81,7 +82,7 @@ public class EntityMgrCloserTest {
* Ensures that the manager gets closed when "try" block exits normally.
*/
@Test
- public void testClose_TryWithoutExcept() {
+ void testClose_TryWithoutExcept() {
try (EntityMgrCloser entityMgrCloser = new EntityMgrCloser(mgr)) {
// No need to do anything in the try block
}
@@ -93,7 +94,7 @@ public class EntityMgrCloserTest {
* Ensures that the manager gets closed when "try" block throws an exception.
*/
@Test
- public void testClose_TryWithExcept() {
+ void testClose_TryWithExcept() {
try {
try (EntityMgrCloser c = new EntityMgrCloser(mgr)) {
throw new Exception("expected exception");
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..aed0937c 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-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.
@@ -20,21 +21,21 @@
package org.onap.policy.common.utils.jpa;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import javax.persistence.EntityManagerFactory;
-import org.junit.Before;
-import org.junit.Test;
+import jakarta.persistence.EntityManagerFactory;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class EntityMgrFactoryCloserTest {
+class EntityMgrFactoryCloserTest {
private EntityManagerFactory factory;
- @Before
+ @BeforeEach
public void setUp() {
factory = mock(EntityManagerFactory.class);
}
@@ -44,7 +45,7 @@ public class EntityMgrFactoryCloserTest {
* Verifies that the constructor does not do anything extra before being closed.
*/
@Test
- public void testEntityMgrFactoryCloser() {
+ void testEntityMgrFactoryCloser() {
EntityMgrFactoryCloser entityMgrFactoryCloser = new EntityMgrFactoryCloser(factory);
assertEquals(factory, entityMgrFactoryCloser.getFactory());
@@ -58,7 +59,7 @@ public class EntityMgrFactoryCloserTest {
}
@Test
- public void testgetFactory() {
+ void testGetFactory() {
try (EntityMgrFactoryCloser c = new EntityMgrFactoryCloser(factory)) {
assertEquals(factory, c.getFactory());
}
@@ -68,7 +69,7 @@ public class EntityMgrFactoryCloserTest {
* Verifies that the manager gets closed when close() is invoked.
*/
@Test
- public void testClose() {
+ void testClose() {
EntityMgrFactoryCloser entityMgrFactoryCloser = new EntityMgrFactoryCloser(factory);
entityMgrFactoryCloser.close();
@@ -81,7 +82,7 @@ public class EntityMgrFactoryCloserTest {
* Ensures that the manager gets closed when "try" block exits normally.
*/
@Test
- public void testClose_TryWithoutExcept() {
+ void testClose_TryWithoutExcept() {
try (EntityMgrFactoryCloser entityMgrFactoryCloser = new EntityMgrFactoryCloser(factory)) {
// No need to do anything in the try block
}
@@ -93,7 +94,7 @@ public class EntityMgrFactoryCloserTest {
* Ensures that the manager gets closed when "try" block throws an exception.
*/
@Test
- public void testClose_TryWithExcept() {
+ void testClose_TryWithExcept() {
try {
try (EntityMgrFactoryCloser c = new EntityMgrFactoryCloser(factory)) {
throw new Exception("expected exception");
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..a864c740 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-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.
@@ -20,25 +21,25 @@
package org.onap.policy.common.utils.jpa;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import javax.persistence.EntityTransaction;
-import org.junit.Before;
-import org.junit.Test;
+import jakarta.persistence.EntityTransaction;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class EntityTransCloserTest {
+class EntityTransCloserTest {
private EntityTransaction trans;
/**
* Set up EntityTransaction mock.
*/
- @Before
+ @BeforeEach
public void setUp() {
trans = mock(EntityTransaction.class);
@@ -52,10 +53,10 @@ public class EntityTransCloserTest {
* being closed.
*/
@Test
- public void testEntityTransCloser() {
+ void testEntityTransCloser() {
EntityTransCloser entityTransCloser = new EntityTransCloser(trans);
- assertEquals(trans, entityTransCloser.getTransation());
+ assertEquals(trans, entityTransCloser.getTransaction());
// verify that transaction was started
verify(trans).begin();
@@ -70,9 +71,9 @@ public class EntityTransCloserTest {
}
@Test
- public void testGetTransation() {
+ void testGetTransaction() {
try (EntityTransCloser t = new EntityTransCloser(trans)) {
- assertEquals(trans, t.getTransation());
+ assertEquals(trans, t.getTransaction());
}
}
@@ -81,7 +82,7 @@ public class EntityTransCloserTest {
* is active.
*/
@Test
- public void testClose_Active() {
+ void testClose_Active() {
EntityTransCloser entityTransCloser = new EntityTransCloser(trans);
when(trans.isActive()).thenReturn(true);
@@ -98,7 +99,7 @@ public class EntityTransCloserTest {
* when and no transaction is active.
*/
@Test
- public void testClose_Inactive() {
+ void testClose_Inactive() {
EntityTransCloser entityTransCloser = new EntityTransCloser(trans);
when(trans.isActive()).thenReturn(false);
@@ -115,7 +116,7 @@ public class EntityTransCloserTest {
* normally and a transaction is active.
*/
@Test
- public void testClose_TryWithoutExcept_Active() {
+ void testClose_TryWithoutExcept_Active() {
when(trans.isActive()).thenReturn(true);
try (EntityTransCloser entityTransCloser = new EntityTransCloser(trans)) {
@@ -132,7 +133,7 @@ public class EntityTransCloserTest {
* "try" block exits normally and no transaction is active.
*/
@Test
- public void testClose_TryWithoutExcept_Inactive() {
+ void testClose_TryWithoutExcept_Inactive() {
when(trans.isActive()).thenReturn(false);
try (EntityTransCloser entityTransCloser = new EntityTransCloser(trans)) {
@@ -149,7 +150,7 @@ public class EntityTransCloserTest {
* an exception and a transaction is active.
*/
@Test
- public void testClose_TryWithExcept_Active() {
+ void testClose_TryWithExcept_Active() {
when(trans.isActive()).thenReturn(true);
try {
@@ -171,7 +172,7 @@ public class EntityTransCloserTest {
* "try" block throws an exception and no transaction is active.
*/
@Test
- public void testClose_TryWithExcept_Inactive() {
+ void testClose_TryWithExcept_Inactive() {
when(trans.isActive()).thenReturn(false);
try {
@@ -192,7 +193,7 @@ public class EntityTransCloserTest {
* Verifies that commit() only commits, and that the subsequent close() does not re-commit.
*/
@Test
- public void testCommit() {
+ void testCommit() {
EntityTransCloser entityTransCloser = new EntityTransCloser(trans);
entityTransCloser.commit();
@@ -204,7 +205,7 @@ public class EntityTransCloserTest {
// closed, but not re-committed
entityTransCloser.close();
- verify(trans, times(1)).commit();
+ verify(trans).commit();
}
/**
@@ -212,7 +213,7 @@ public class EntityTransCloserTest {
* back.
*/
@Test
- public void testRollback() {
+ void testRollback() {
EntityTransCloser entityTransCloser = new EntityTransCloser(trans);
entityTransCloser.rollback();
diff --git a/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerMarkerFilterTest.java b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerMarkerFilterTest.java
new file mode 100644
index 00000000..64278a93
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerMarkerFilterTest.java
@@ -0,0 +1,155 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 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.
+ * 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.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.spi.FilterReply;
+import java.util.Collections;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.onap.policy.common.utils.logging.LoggerMarkerFilter.AuditLoggerMarkerFilter;
+import org.onap.policy.common.utils.logging.LoggerMarkerFilter.MetricLoggerMarkerFilter;
+import org.onap.policy.common.utils.logging.LoggerMarkerFilter.SecurityLoggerMarkerFilter;
+import org.onap.policy.common.utils.logging.LoggerMarkerFilter.TransactionLoggerMarkerFilter;
+import org.slf4j.Marker;
+
+class LoggerMarkerFilterTest {
+
+ private ILoggingEvent mockEvent;
+ private Marker mockMarker;
+
+ @BeforeEach
+ void setUp() {
+ mockEvent = mock(ILoggingEvent.class);
+ mockMarker = mock(Marker.class);
+ }
+
+ @Test
+ void testDecideAcceptWithMetricMarker() {
+ MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.METRIC_LOG_MARKER));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the METRIC_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideDenyWithoutMetricMarker() {
+ MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the METRIC_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideAcceptWithSecurityMarker() {
+ SecurityLoggerMarkerFilter filter = new SecurityLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.SECURITY_LOG_MARKER));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the SECURITY_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideDenyWithoutSecurityMarker() {
+ SecurityLoggerMarkerFilter filter = new SecurityLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the SECURITY_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideAcceptWithAuditMarker() {
+ AuditLoggerMarkerFilter filter = new AuditLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.AUDIT_LOG_MARKER));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the AUDIT_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideDenyWithoutAuditMarker() {
+ AuditLoggerMarkerFilter filter = new AuditLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the AUDIT_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideAcceptWithTransactionMarker() {
+ TransactionLoggerMarkerFilter filter = new TransactionLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.TRANSACTION_LOG_MARKER));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the TRANSACTION_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideDenyWithoutTransactionMarker() {
+ TransactionLoggerMarkerFilter filter = new TransactionLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker));
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the TRANSACTION_LOG_MARKER.");
+ }
+
+ @Test
+ void testDecideDenyWhenNotStarted() {
+ MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.METRIC_LOG_MARKER));
+ // Filter is not started
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.DENY, reply, "The filter should deny the event if the filter is not started.");
+ }
+
+ @Test
+ void testDecideDenyWithNullEvent() {
+ MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter();
+ filter.start();
+
+ FilterReply reply = filter.decide(null);
+ assertEquals(FilterReply.DENY, reply, "The filter should deny if the event is null.");
+ }
+
+ @Test
+ void testDecideDenyWithNullMarkerList() {
+ MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter();
+ when(mockEvent.getMarkerList()).thenReturn(null);
+ filter.start();
+
+ FilterReply reply = filter.decide(mockEvent);
+ assertEquals(FilterReply.DENY, reply, "The filter should deny if the marker list is null.");
+ }
+}
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..6c39c210
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerUtilsTest.java
@@ -0,0 +1,54 @@
+/*-
+* ============LICENSE_START=======================================================
+* ONAP Policy
+* ================================================================================
+* Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
+* Modifications Copyright (C) 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.
+* 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.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ExtendWith(MockitoExtension.class)
+class LoggerUtilsTest {
+ protected static final Logger logger = LoggerFactory.getLogger(LoggerUtilsTest.class);
+
+ @Test
+ 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..ccd67fc4 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,8 @@
* ============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.
+ * Modifications Copyright (C) 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.
@@ -20,11 +21,13 @@
package org.onap.policy.common.utils.network;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -32,17 +35,17 @@ import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetworkUtilTest {
+class NetworkUtilTest {
protected static Logger logger = LoggerFactory.getLogger(NetworkUtilTest.class);
private static final String LOCALHOST = "localhost";
@Test
- public void test() throws InterruptedException, IOException {
+ void test() throws InterruptedException, IOException {
assertNotNull(NetworkUtil.IPV4_WILDCARD_ADDRESS);
assertFalse(NetworkUtil.isTcpPortOpen(LOCALHOST, NetworkUtil.allocPort(), 1, 5));
assertNotNull(NetworkUtil.getHostname());
@@ -50,10 +53,10 @@ public class NetworkUtilTest {
}
@Test
- public void testAlwaysTrustManager() throws Exception {
+ void testAlwaysTrustManager() throws Exception {
TrustManager[] mgrarr = NetworkUtil.getAlwaysTrustingManager();
assertEquals(1, mgrarr.length);
- assertTrue(mgrarr[0] instanceof X509TrustManager);
+ assertInstanceOf(X509TrustManager.class, mgrarr[0]);
X509TrustManager mgr = (X509TrustManager) mgrarr[0];
assertNotNull(mgr.getAcceptedIssuers());
@@ -65,7 +68,7 @@ public class NetworkUtilTest {
}
@Test
- public void testAllocPort_testAllocPortString__testAllocPortInetSocketAddress() throws Exception {
+ void testAllocPort_testAllocPortString__testAllocPortInetSocketAddress() throws Exception {
// allocate wild-card port
int wildCardPort = NetworkUtil.allocPort();
assertNotEquals(0, wildCardPort);
@@ -91,6 +94,15 @@ public class NetworkUtilTest {
}
}
+ @Test
+ 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.
*/
@@ -104,7 +116,7 @@ public class NetworkUtilTest {
@Override
public void run() {
- try (Socket server = socket.accept()) {
+ try (Socket server = socket.accept()) { //NOSONAR
// do nothing
} catch (IOException e) {
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..45226b28 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,8 @@
* ============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.
+ * Modifications Copyright (C) 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.
@@ -20,16 +21,17 @@
package org.onap.policy.common.utils.properties;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.properties.exception.PropertyAccessException;
import org.onap.policy.common.utils.properties.exception.PropertyException;
import org.onap.policy.common.utils.properties.exception.PropertyInvalidException;
@@ -38,7 +40,7 @@ import org.onap.policy.common.utils.properties.exception.PropertyMissingExceptio
/**
* Test class for PropertyConfiguration.
*/
-public class BeanConfiguratorTest {
+class BeanConfiguratorTest {
private static final String EXPECTED_EXCEPTION = "expected exception";
private static final String FALSE_STRING = "false";
private static final String A_VALUE = "a.value";
@@ -72,14 +74,18 @@ public class BeanConfiguratorTest {
private BeanConfigurator beancfg;
- @Before
+ @BeforeEach
public void setUp() {
props = new Properties();
beancfg = new BeanConfigurator();
}
@Test
- public void testConfigureFromProperties() throws PropertyException {
+ void testConfigureFromProperties() throws PropertyException {
+ testStringValueNoDefault();
+ }
+
+ private void testStringValueNoDefault() throws PropertyException {
props.setProperty(THE_VALUE, STRING_VALUE);
PlainStringConfig cfg = new PlainStringConfig();
@@ -89,7 +95,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testSetAllFields() throws Exception {
+ void testSetAllFields() throws Exception {
/*
* Implements an extra interface, just to see that it doesn't cause issues.
@@ -155,7 +161,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testSetAllFields_NoProperties() throws Exception {
+ void testSetAllFields_NoProperties() throws Exception {
class Config {
@@ -176,16 +182,12 @@ 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);
+ void testSetValueObjectFieldProperties_FieldSet() throws PropertyException {
+ testStringValueNoDefault();
}
@Test
- public void testSetValueObjectFieldProperties_NoAnnotation() throws PropertyException {
+ void testSetValueObjectFieldProperties_NoAnnotation() throws PropertyException {
class Config {
private String value;
@@ -203,8 +205,8 @@ public class BeanConfiguratorTest {
assertNull(cfg.value);
}
- @Test(expected = PropertyAccessException.class)
- public void testSetValueObjectFieldProperties_WrongFieldType() throws PropertyException {
+ @Test
+ void testSetValueObjectFieldProperties_WrongFieldType() {
class Config {
// Cannot set a property into an "Exception" field
@@ -218,11 +220,12 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, STRING_VALUE);
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyAccessException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
}
- @Test(expected = PropertyAccessException.class)
- public void testGetSetter_NoSetter() throws PropertyException {
+ @Test
+ void testGetSetter_NoSetter() {
class Config {
@Property(name = THE_VALUE)
@@ -230,16 +233,19 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, STRING_VALUE);
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyAccessException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
}
- @Test(expected = PropertyMissingException.class)
- public void testSetValueObjectMethodFieldPropertiesProperty_NoProperty_NoDefault() throws PropertyException {
- beancfg.configureFromProperties(new PlainStringConfig(), props);
+ @Test
+ void testSetValueObjectMethodFieldPropertiesProperty_NoProperty_NoDefault() {
+ assertThrows(PropertyMissingException.class, () -> beancfg.configureFromProperties(
+ new PlainStringConfig(), props));
+
}
- @Test(expected = PropertyInvalidException.class)
- public void testSetValueObjectMethodFieldPropertiesProperty_IllegalArgEx() throws PropertyException {
+ @Test
+ void testSetValueObjectMethodFieldPropertiesProperty_IllegalArgEx() {
props.setProperty(THE_VALUE, STRING_VALUE);
beancfg = new BeanConfigurator() {
@@ -249,11 +255,12 @@ public class BeanConfiguratorTest {
}
};
- beancfg.configureFromProperties(new PlainStringConfig(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new PlainStringConfig(), props));
}
- @Test(expected = PropertyAccessException.class)
- public void testSetValueObjectMethodFieldPropertiesProperty_MethodEx() throws PropertyException {
+ @Test
+ void testSetValueObjectMethodFieldPropertiesProperty_MethodEx() {
class Config extends PlainStringConfig {
@Override
@@ -263,11 +270,12 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, STRING_VALUE);
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyAccessException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
}
@Test
- public void testGetValue() throws PropertyException {
+ void testGetValue() throws PropertyException {
// this class contains all of the supported field types
class Config {
@@ -413,8 +421,8 @@ public class BeanConfiguratorTest {
assertEquals(10001, cfg.primLongValue);
}
- @Test(expected = PropertyAccessException.class)
- public void testGetValue_UnsupportedType() throws PropertyException {
+ @Test
+ void testGetValue_UnsupportedType() {
class Config {
// Cannot set a property into an "Exception" field
@@ -428,12 +436,14 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, STRING_VALUE);
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyAccessException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
+
}
@Test
- public void testCheckModifiable_OtherModifiers() throws PropertyException {
- // this class contains all of the supported field types
+ void testCheckModifiable_OtherModifiers() throws PropertyException {
+ // this class contains all the supported field types
class Config {
@Property(name = "public")
@@ -473,14 +483,16 @@ public class BeanConfiguratorTest {
assertEquals("a protected string", cfg.protectedString);
}
- @Test(expected = PropertyAccessException.class)
- public void testCheckModifiable_Static() throws PropertyException {
+ @Test
+ void testCheckModifiable_Static() {
props.setProperty(THE_VALUE, STRING_VALUE);
- beancfg.configureFromProperties(new StaticPropConfig(), props);
+ assertThrows(PropertyAccessException.class, () -> beancfg.configureFromProperties(
+ new StaticPropConfig(), props));
+
}
- @Test(expected = PropertyAccessException.class)
- public void testCheckModifiable_Final() throws PropertyException {
+ @Test
+ void testCheckModifiable_Final() {
class Config {
// Cannot set a property into an "final" field
@@ -489,26 +501,26 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, STRING_VALUE);
- beancfg.configureFromProperties(new Config(), props);
- }
+ assertThrows(PropertyAccessException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
- @Test(expected = PropertyAccessException.class)
- public void testCheckMethod_Static() throws PropertyException {
- props.setProperty(THE_VALUE, STRING_VALUE);
- beancfg.configureFromProperties(new StaticMethodConfig(), props);
}
@Test
- public void testGetStringValue() throws PropertyException {
+ void testCheckMethod_Static() {
props.setProperty(THE_VALUE, STRING_VALUE);
- PlainStringConfig cfg = new PlainStringConfig();
- beancfg.configureFromProperties(cfg, props);
+ assertThrows(PropertyAccessException.class, () -> beancfg.configureFromProperties(
+ new StaticMethodConfig(), props));
- assertEquals(STRING_VALUE, cfg.value);
}
@Test
- public void testGetBooleanValue_NoDefault() throws PropertyException {
+ void testGetStringValue() throws PropertyException {
+ testStringValueNoDefault();
+ }
+
+ @Test
+ void testGetBooleanValue_NoDefault() throws PropertyException {
props.setProperty(THE_VALUE, "true");
PlainBooleanConfig cfg = new PlainBooleanConfig();
beancfg.configureFromProperties(cfg, props);
@@ -516,8 +528,8 @@ public class BeanConfiguratorTest {
assertEquals(true, cfg.value);
}
- @Test(expected = PropertyInvalidException.class)
- public void testGetBooleanValue_InvalidDefault() throws PropertyException {
+ @Test
+ void testGetBooleanValue_InvalidDefault() {
class Config {
@Property(name = THE_VALUE, defaultValue = INVALID_VALUE)
@@ -530,11 +542,12 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, "true");
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
}
@Test
- public void testGetBooleanValue_ValidDefault_True() throws PropertyException {
+ void testGetBooleanValue_ValidDefault_True() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = "true")
@@ -565,7 +578,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetBooleanValue_ValidDefault_False() throws PropertyException {
+ void testGetBooleanValue_ValidDefault_False() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = FALSE_STRING)
@@ -596,7 +609,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetIntegerValue_NoDefault() throws PropertyException {
+ void testGetIntegerValue_NoDefault() throws PropertyException {
class Config {
@Property(name = THE_VALUE)
@@ -615,8 +628,8 @@ public class BeanConfiguratorTest {
assertEquals(200, cfg.value.intValue());
}
- @Test(expected = PropertyInvalidException.class)
- public void testGetIntegerValue_InvalidDefault() throws PropertyException {
+ @Test
+ void testGetIntegerValue_InvalidDefault() {
class Config {
@Property(name = THE_VALUE, defaultValue = INVALID_VALUE)
@@ -629,11 +642,13 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, NUMBER_STRING);
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
+
}
@Test
- public void testGetIntegerValue_ValidDefault() throws PropertyException {
+ void testGetIntegerValue_ValidDefault() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = "201")
@@ -658,7 +673,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetLongValue_NoDefault() throws PropertyException {
+ void testGetLongValue_NoDefault() throws PropertyException {
class Config {
@Property(name = THE_VALUE)
@@ -677,8 +692,8 @@ public class BeanConfiguratorTest {
assertEquals(20000L, cfg.value.longValue());
}
- @Test(expected = PropertyInvalidException.class)
- public void testGetLongValue_InvalidDefault() throws PropertyException {
+ @Test
+ void testGetLongValue_InvalidDefault() {
class Config {
@Property(name = THE_VALUE, defaultValue = INVALID_VALUE)
@@ -691,11 +706,13 @@ public class BeanConfiguratorTest {
}
props.setProperty(THE_VALUE, NUMBER_STRING_LONG);
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
+
}
@Test
- public void testGetLongValue_ValidDefault() throws PropertyException {
+ void testGetLongValue_ValidDefault() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = "20001")
@@ -720,17 +737,12 @@ 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);
+ void testGetPropValue_Prop_NoDefault() throws PropertyException {
+ testStringValueNoDefault();
}
@Test
- public void testGetPropValue_Prop_Default() throws PropertyException {
+ void testGetPropValue_Prop_Default() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = STRING_VALUE_DEFAULT)
@@ -751,7 +763,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetPropValue_EmptyProp_EmptyOk() throws PropertyException {
+ void testGetPropValue_EmptyProp_EmptyOk() throws PropertyException {
class Config {
@Property(name = THE_VALUE, accept = "empty")
@@ -772,7 +784,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetPropValue_NullProp_EmptyOk() throws PropertyException {
+ void testGetPropValue_NullProp_EmptyOk() throws PropertyException {
class Config {
@Property(name = THE_VALUE, accept = "empty")
@@ -791,7 +803,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetPropValue_EmptyDefault_EmptyOk() throws PropertyException {
+ void testGetPropValue_EmptyDefault_EmptyOk() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = "", accept = "empty")
@@ -810,7 +822,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetPropValue_Default_EmptyOk() throws PropertyException {
+ void testGetPropValue_Default_EmptyOk() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = STRING_VALUE, accept = "empty")
@@ -828,8 +840,8 @@ public class BeanConfiguratorTest {
assertEquals(STRING_VALUE, cfg.value);
}
- @Test(expected = PropertyMissingException.class)
- public void testGetPropValue_EmptyDefault_EmptyNotOk() throws PropertyException {
+ @Test
+ void testGetPropValue_EmptyDefault_EmptyNotOk() {
class Config {
@Property(name = THE_VALUE, defaultValue = "")
@@ -841,11 +853,12 @@ public class BeanConfiguratorTest {
}
}
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyMissingException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
}
@Test
- public void testGetPropValue_Default_EmptyNotOk() throws PropertyException {
+ void testGetPropValue_Default_EmptyNotOk() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = STRING_VALUE, accept = "")
@@ -864,16 +877,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testMakeBoolean_True() throws PropertyException {
- props.setProperty(THE_VALUE, "true");
- PlainBooleanConfig cfg = new PlainBooleanConfig();
- beancfg.configureFromProperties(cfg, props);
-
- assertEquals(true, cfg.value);
- }
-
- @Test
- public void testMakeBoolean_False() throws PropertyException {
+ void testMakeBoolean_False() throws PropertyException {
props.setProperty(THE_VALUE, FALSE_STRING);
PlainBooleanConfig cfg = new PlainBooleanConfig();
beancfg.configureFromProperties(cfg, props);
@@ -881,14 +885,16 @@ public class BeanConfiguratorTest {
assertEquals(false, cfg.value);
}
- @Test(expected = PropertyInvalidException.class)
- public void testMakeBoolean_Invalid() throws PropertyException {
+ @Test
+ void testMakeBoolean_Invalid() {
props.setProperty(THE_VALUE, INVALID_VALUE);
- beancfg.configureFromProperties(new PlainBooleanConfig(), props);
+
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new PlainBooleanConfig(), props));
}
@Test
- public void testMakeInteger_Valid() throws PropertyException {
+ void testMakeInteger_Valid() throws PropertyException {
props.setProperty(THE_VALUE, "300");
PlainPrimIntConfig cfg = new PlainPrimIntConfig();
beancfg.configureFromProperties(cfg, props);
@@ -896,20 +902,23 @@ public class BeanConfiguratorTest {
assertEquals(300, cfg.value);
}
- @Test(expected = PropertyInvalidException.class)
- public void testMakeInteger_Invalid() throws PropertyException {
+ @Test
+ void testMakeInteger_Invalid() {
props.setProperty(THE_VALUE, INVALID_VALUE);
- beancfg.configureFromProperties(new PlainPrimIntConfig(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new PlainPrimIntConfig(), props));
+
}
- @Test(expected = PropertyInvalidException.class)
- public void testMakeInteger_TooBig() throws PropertyException {
+ @Test
+ void testMakeInteger_TooBig() {
props.setProperty(THE_VALUE, String.valueOf(Integer.MAX_VALUE + 10L));
- beancfg.configureFromProperties(new PlainPrimIntConfig(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new PlainPrimIntConfig(), props));
}
@Test
- public void testMakeLong_Valid() throws PropertyException {
+ void testMakeLong_Valid() throws PropertyException {
props.setProperty(THE_VALUE, "30000");
PlainPrimLongConfig cfg = new PlainPrimLongConfig();
beancfg.configureFromProperties(cfg, props);
@@ -917,14 +926,15 @@ public class BeanConfiguratorTest {
assertEquals(30000L, cfg.value);
}
- @Test(expected = PropertyInvalidException.class)
- public void testMakeLong_Invalid() throws PropertyException {
+ @Test
+ void testMakeLong_Invalid() {
props.setProperty(THE_VALUE, INVALID_VALUE);
- beancfg.configureFromProperties(new PlainPrimLongConfig(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new PlainPrimLongConfig(), props));
}
@Test
- public void testCheckDefaultValue_NotEmpty_Valid() throws PropertyException {
+ void testCheckDefaultValue_NotEmpty_Valid() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = "700")
@@ -942,8 +952,8 @@ public class BeanConfiguratorTest {
assertEquals(700L, cfg.value);
}
- @Test(expected = PropertyInvalidException.class)
- public void testCheckDefaultValue_NotEmpty_Invalid() throws PropertyException {
+ @Test
+ void testCheckDefaultValue_NotEmpty_Invalid() {
class Config {
@Property(name = THE_VALUE, defaultValue = INVALID_VALUE)
@@ -955,27 +965,18 @@ public class BeanConfiguratorTest {
}
}
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new Config(), props));
}
- @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);
+ @Test
+ void testCheckDefaultValue_Empty_EmptyOk_Invalid() {
+ assertThrows(PropertyInvalidException.class, () -> beancfg.configureFromProperties(
+ new PrimLongDefaultBlankAcceptEmptyConfig(), props));
}
@Test
- public void testIsEmptyOkPropertyString_True() throws PropertyException {
+ void testIsEmptyOkPropertyString_True() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = "", accept = "empty")
@@ -1003,24 +1004,15 @@ public class BeanConfiguratorTest {
assertEquals(STRING_VALUE, cfg.value);
}
- @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;
- }
- }
+ @Test
+ void testIsEmptyOkPropertyString_False() {
- beancfg.configureFromProperties(new Config(), props);
+ assertThrows(PropertyException.class, () -> beancfg
+ .configureFromProperties(new PrimLongDefaultBlankAcceptBlankConfig(), props));
}
@Test
- public void testIsEmptyOkProperty_True() throws PropertyException {
+ void testIsEmptyOkProperty_True() throws PropertyException {
class Config {
@Property(name = THE_VALUE, defaultValue = "", accept = "empty")
@@ -1038,24 +1030,14 @@ public class BeanConfiguratorTest {
assertEquals("", cfg.value);
}
- @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);
+ @Test
+ void testIsEmptyOkProperty_False() {
+ assertThrows(PropertyMissingException.class, () -> beancfg
+ .configureFromProperties(new PrimLongDefaultBlankAcceptBlankConfig(), props));
}
@Test
- public void testPutToProperties() throws Exception {
+ void testPutToProperties() throws Exception {
/*
* Implements the extra interface, too.
@@ -1121,7 +1103,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testPutProperty() throws Exception {
+ void testPutProperty() throws Exception {
class Config {
// no annotation - should not be copied
@@ -1173,7 +1155,7 @@ public class BeanConfiguratorTest {
}
@Test
- public void testGetGetter() throws Exception {
+ void testGetGetter() throws Exception {
class Config {
// getter method starts with "is" for these
@@ -1244,8 +1226,8 @@ public class BeanConfiguratorTest {
assertEquals(STRING_VALUE, props.getProperty("string"));
}
- @Test(expected = PropertyAccessException.class)
- public void testGetGetter_NoGetter() throws Exception {
+ @Test
+ void testGetGetter_NoGetter() {
class Config {
@Property(name = THE_VALUE)
@@ -1254,11 +1236,12 @@ public class BeanConfiguratorTest {
Config cfg = new Config();
cfg.value = STRING_VALUE;
- beancfg.addToProperties(cfg, props, "", "");
+ assertThrows(PropertyAccessException.class, () -> beancfg
+ .addToProperties(cfg, props, "", ""));
}
- @Test(expected = PropertyAccessException.class)
- public void testGetGetter_NoGetterForBoolean() throws Exception {
+ @Test
+ void testGetGetter_NoGetterForBoolean() {
class Config {
@Property(name = THE_VALUE)
@@ -1267,11 +1250,12 @@ public class BeanConfiguratorTest {
Config cfg = new Config();
cfg.value = true;
- beancfg.addToProperties(cfg, props, "", "");
+ assertThrows(PropertyAccessException.class, () -> beancfg
+ .addToProperties(cfg, props, "", ""));
}
- @Test(expected = PropertyAccessException.class)
- public void testGetGetter_PrivateGetter() throws Exception {
+ @Test
+ void testGetGetter_PrivateGetter() {
class Config {
@Property(name = THE_VALUE)
@@ -1285,11 +1269,12 @@ public class BeanConfiguratorTest {
Config cfg = new Config();
cfg.value = STRING_VALUE;
- beancfg.addToProperties(cfg, props, "", "");
+ assertThrows(PropertyAccessException.class, () -> beancfg
+ .addToProperties(cfg, props, "", ""));
}
- @Test(expected = PropertyAccessException.class)
- public void testGetGetter_SecurityEx() throws Exception {
+ @Test
+ void testGetGetter_SecurityEx() {
class Config {
@Property(name = THE_VALUE)
@@ -1311,11 +1296,12 @@ public class BeanConfiguratorTest {
}
};
- beancfg.addToProperties(cfg, props, "", "");
+ assertThrows(PropertyAccessException.class, () -> beancfg
+ .addToProperties(cfg, props, "", ""));
}
- @Test(expected = PropertyAccessException.class)
- public void testGetBeanValue_Ex() throws Exception {
+ @Test
+ void testGetBeanValue_Ex() {
class Config {
@@ -1332,8 +1318,8 @@ public class BeanConfiguratorTest {
final Config cfg = new Config();
cfg.value = STRING_VALUE;
- beancfg.addToProperties(cfg, props, "the", "a");
-
+ assertThrows(PropertyAccessException.class, () -> beancfg
+ .addToProperties(cfg, props, "the", "a"));
}
/**
@@ -1420,6 +1406,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
index 93b30643..06b4f74f 100644
--- 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
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -18,9 +19,8 @@
package org.onap.policy.common.utils.properties;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.IOException;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Iterator;
@@ -29,14 +29,14 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
-public class PropertyObjectUtilsTest {
+class PropertyObjectUtilsTest {
@Test
- public void testToObject() {
+ void testToObject() {
Map<String, String> map = Map.of("abc", "def", "ghi", "jkl");
Properties props = new Properties();
props.putAll(map);
@@ -48,7 +48,7 @@ public class PropertyObjectUtilsTest {
// 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"));
+ props.putAll(map);
result = PropertyObjectUtils.toObject(props, "pfx.");
map = Map.of("abc", "def", "mno", "pqr");
assertEquals(map, result);
@@ -59,7 +59,7 @@ public class PropertyObjectUtilsTest {
}
@Test
- public void testSetProperty() {
+ 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");
@@ -79,7 +79,7 @@ public class PropertyObjectUtilsTest {
}
@Test
- public void testGetNode() {
+ 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);
@@ -98,7 +98,7 @@ public class PropertyObjectUtilsTest {
}
@Test
- public void testExpand() {
+ void testExpand() {
// add subscripts out of order
Properties props = makeProperties("abc[2]", "expand.def", "abc[1]", "expand.ghi");
@@ -113,7 +113,7 @@ public class PropertyObjectUtilsTest {
}
@Test
- public void testGetObject() {
+ void testGetObject() {
// first value is primitive, while second is a map
Properties props = makeProperties("object.abc", "object.def", "object.abc.ghi", "object.jkl");
@@ -128,7 +128,7 @@ public class PropertyObjectUtilsTest {
}
@Test
- public void testGetArray() {
+ void testGetArray() {
// first value is primitive, while second is an array
Properties props = makeProperties("array.abc", "array.def", "array.abc[0].ghi", "array.jkl");
@@ -145,7 +145,7 @@ public class PropertyObjectUtilsTest {
@Test
@SuppressWarnings("unchecked")
- public void testCompressLists() throws IOException, CoderException {
+ void testCompressLists() throws CoderException {
assertEquals("plain-string", PropertyObjectUtils.compressLists("plain-string").toString());
// @formatter:off
diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/SpecPropertiesTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/SpecPropertiesTest.java
index 0e4216c6..627b79c1 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/properties/SpecPropertiesTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/properties/SpecPropertiesTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,14 +21,15 @@
package org.onap.policy.common.utils.properties;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Properties;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class SpecPropertiesTest {
+class SpecPropertiesTest {
/**
* Property prefix of interest.
@@ -82,7 +84,7 @@ public class SpecPropertiesTest {
/**
* Set up the tests.
*/
- @Before
+ @BeforeEach
public void setUp() {
supportingProps = new Properties();
@@ -96,7 +98,7 @@ public class SpecPropertiesTest {
}
@Test
- public void testSpecPropertiesStringString() {
+ void testSpecPropertiesStringString() {
// no supporting properties
props = new SpecProperties(MY_PREFIX, MY_SPEC);
@@ -112,7 +114,7 @@ public class SpecPropertiesTest {
}
@Test
- public void testSpecPropertiesStringStringProperties() {
+ void testSpecPropertiesStringStringProperties() {
// use supportingProps as default properties
props = new SpecProperties(MY_PREFIX, MY_SPEC, supportingProps);
@@ -127,7 +129,7 @@ public class SpecPropertiesTest {
}
@Test
- public void testSpecPropertiesStringStringProperties_EmptyPrefix() {
+ void testSpecPropertiesStringStringProperties_EmptyPrefix() {
supportingProps = new Properties();
supportingProps.setProperty(PROP_NO_PREFIX, VAL_NO_PREFIX);
@@ -145,7 +147,7 @@ public class SpecPropertiesTest {
}
@Test
- public void testWithTrailingDot() {
+ void testWithTrailingDot() {
// neither has trailing dot
assertEquals(PREFIX_GEN, props.getPrefix());
assertEquals(PREFIX_SPEC, props.getSpecPrefix());
@@ -167,7 +169,7 @@ public class SpecPropertiesTest {
}
@Test
- public void testGetPropertyString() {
+ void testGetPropertyString() {
// the key does contain the prefix
assertEquals(VAL_NO_PREFIX, props.getProperty(gen(PROP_NO_PREFIX)));
assertNull(props.getProperty(gen(PROP_NO_PREFIX + SUFFIX)));
@@ -186,7 +188,7 @@ public class SpecPropertiesTest {
}
@Test
- public void testGetPropertyStringString() {
+ void testGetPropertyStringString() {
// the key does contain the prefix
assertEquals(VAL_NO_PREFIX, props.getProperty(gen(PROP_NO_PREFIX), VAL_DEFAULT));
assertEquals(VAL_DEFAULT, props.getProperty(gen(PROP_NO_PREFIX + SUFFIX), VAL_DEFAULT));
@@ -207,14 +209,14 @@ public class SpecPropertiesTest {
assertNull(props.getProperty(gen(PROP_UNKNOWN), null));
}
- @Test(expected = UnsupportedOperationException.class)
- public void testHashCode() {
- props.hashCode();
+ @Test
+ void testHashCode() {
+ assertThrows(UnsupportedOperationException.class, () -> props.hashCode());
}
- @Test(expected = UnsupportedOperationException.class)
- public void testEquals() {
- props.equals(props);
+ @Test
+ void testEquals() {
+ assertThrows(UnsupportedOperationException.class, () -> props.equals(props));
}
private String gen(String propnm) {
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 ef2051d8..b6bf0c54 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
@@ -3,6 +3,7 @@
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.utils.properties.exception;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test class for PropertyAccessException.
*/
-public class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTester {
+class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTester {
/**
* Test method for
@@ -33,7 +34,7 @@ public class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTe
* (java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyAccessExceptionStringField() {
+ void testPropertyAccessExceptionStringField() {
verifyPropertyExceptionStringField_AllPopulated(new PropertyAccessException(PROPERTY, FIELD));
verifyPropertyExceptionStringField_NullProperty(new PropertyAccessException(null, FIELD));
verifyPropertyExceptionStringField_NullField(new PropertyAccessException(PROPERTY, null));
@@ -46,7 +47,7 @@ public class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTe
* (java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyAccessExceptionStringFieldString() {
+ void testPropertyAccessExceptionStringFieldString() {
verifyPropertyExceptionStringFieldString(new PropertyAccessException(PROPERTY, FIELD, MESSAGE));
}
@@ -56,7 +57,7 @@ public class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTe
* (java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyAccessExceptionStringFieldThrowable() {
+ void testPropertyAccessExceptionStringFieldThrowable() {
verifyPropertyExceptionStringFieldThrowable(new PropertyAccessException(PROPERTY, FIELD, THROWABLE));
}
@@ -66,7 +67,7 @@ public class PropertyAccessExceptionTest extends SupportBasicPropertyExceptionTe
* (java.lang.String, java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyAccessExceptionStringFieldStringThrowable() {
+ void testPropertyAccessExceptionStringFieldStringThrowable() {
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 91879763..aad4491c 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
@@ -3,6 +3,7 @@
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.utils.properties.exception;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test class for PropertyAnnotationException.
*/
-public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExceptionTester {
+class PropertyAnnotationExceptionTest extends SupportBasicPropertyExceptionTester {
/**
* Test method for
@@ -33,7 +34,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
* (java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyExceptionStringField() {
+ void testPropertyExceptionStringField() {
verifyPropertyExceptionStringField_AllPopulated(new PropertyAnnotationException(PROPERTY, FIELD));
verifyPropertyExceptionStringField_NullProperty(new PropertyAnnotationException(null, FIELD));
verifyPropertyExceptionStringField_NullField(new PropertyAnnotationException(PROPERTY, null));
@@ -46,7 +47,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
* (java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyExceptionStringFieldString() {
+ void testPropertyExceptionStringFieldString() {
verifyPropertyExceptionStringFieldString(new PropertyAnnotationException(PROPERTY, FIELD, MESSAGE));
}
@@ -56,7 +57,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
* (java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyExceptionStringFieldThrowable() {
+ void testPropertyExceptionStringFieldThrowable() {
verifyPropertyExceptionStringFieldThrowable(new PropertyAnnotationException(PROPERTY, FIELD, THROWABLE));
}
@@ -66,7 +67,7 @@ public class PropertyAnnotationExceptionTest extends SupportBasicPropertyExcepti
* (java.lang.String, java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyExceptionStringFieldStringThrowable() {
+ void testPropertyExceptionStringFieldStringThrowable() {
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 9166749b..6075b4cd 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
@@ -3,6 +3,7 @@
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.utils.properties.exception;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test class for PropertyException.
*/
-public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
+class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
/**
* Test method for
@@ -33,7 +34,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
* (java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyExceptionStringField() {
+ void testPropertyExceptionStringField() {
verifyPropertyExceptionStringField_AllPopulated(new PropertyException(PROPERTY, FIELD));
verifyPropertyExceptionStringField_NullProperty(new PropertyException(null, FIELD));
verifyPropertyExceptionStringField_NullField(new PropertyException(PROPERTY, null));
@@ -46,7 +47,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
* (java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyExceptionStringFieldString() {
+ void testPropertyExceptionStringFieldString() {
verifyPropertyExceptionStringFieldString(new PropertyException(PROPERTY, FIELD, MESSAGE));
}
@@ -56,7 +57,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
* (java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyExceptionStringFieldThrowable() {
+ void testPropertyExceptionStringFieldThrowable() {
verifyPropertyExceptionStringFieldThrowable(new PropertyException(PROPERTY, FIELD, THROWABLE));
}
@@ -66,7 +67,7 @@ public class PropertyExceptionTest extends SupportBasicPropertyExceptionTester {
* (java.lang.String, java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyExceptionStringFieldStringThrowable() {
+ void testPropertyExceptionStringFieldStringThrowable() {
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 3edd7ff4..3222bbbd 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
@@ -3,6 +3,7 @@
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.utils.properties.exception;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test class for PropertyInvalidException.
*/
-public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionTester {
+class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionTester {
/**
* Test method for
@@ -33,7 +34,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
* (java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyExceptionStringField() {
+ void testPropertyExceptionStringField() {
verifyPropertyExceptionStringField_AllPopulated(new PropertyInvalidException(PROPERTY, FIELD));
verifyPropertyExceptionStringField_NullProperty(new PropertyInvalidException(null, FIELD));
verifyPropertyExceptionStringField_NullField(new PropertyInvalidException(PROPERTY, null));
@@ -46,7 +47,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
* (java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyExceptionStringFieldString() {
+ void testPropertyExceptionStringFieldString() {
verifyPropertyExceptionStringFieldString(new PropertyInvalidException(PROPERTY, FIELD, MESSAGE));
}
@@ -56,7 +57,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
* (java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyExceptionStringFieldThrowable() {
+ void testPropertyExceptionStringFieldThrowable() {
verifyPropertyExceptionStringFieldThrowable(new PropertyInvalidException(PROPERTY, FIELD, THROWABLE));
}
@@ -66,7 +67,7 @@ public class PropertyInvalidExceptionTest extends SupportBasicPropertyExceptionT
* (java.lang.String, java.lang.String, java.lang.String, java.lang.Throwable)}.
*/
@Test
- public void testPropertyExceptionStringFieldStringThrowable() {
+ void testPropertyExceptionStringFieldStringThrowable() {
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 948bc18e..3a2a7a91 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
@@ -3,6 +3,7 @@
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,12 +21,12 @@
package org.onap.policy.common.utils.properties.exception;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test class for PropertyMissingException.
*/
-public class PropertyMissingExceptionTest extends SupportBasicPropertyExceptionTester {
+class PropertyMissingExceptionTest extends SupportBasicPropertyExceptionTester {
/**
* Test method for
@@ -33,7 +34,7 @@ public class PropertyMissingExceptionTest extends SupportBasicPropertyExceptionT
* (java.lang.String, java.lang.String)}.
*/
@Test
- public void testPropertyExceptionStringField() {
+ void testPropertyExceptionStringField() {
verifyPropertyExceptionStringField_AllPopulated(new PropertyMissingException(PROPERTY, FIELD));
verifyPropertyExceptionStringField_NullProperty(new PropertyMissingException(null, FIELD));
verifyPropertyExceptionStringField_NullField(new PropertyMissingException(PROPERTY, 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 be3f8183..653a4efd 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
@@ -3,6 +3,7 @@
* ONAP Policy Engine - Common Modules
* ================================================================================
* Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -21,8 +22,8 @@
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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Superclass used to test subclasses of {@link PropertyException}.
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..40776f52
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/resources/DirectoryUtilsTest.java
@@ -0,0 +1,43 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
+ * 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.jupiter.api.Test;
+
+class DirectoryUtilsTest {
+
+ @Test
+ 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/PrometheusUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/PrometheusUtilsTest.java
new file mode 100644
index 00000000..a60b599e
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/resources/PrometheusUtilsTest.java
@@ -0,0 +1,37 @@
+/*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 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.
+ * 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.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+class PrometheusUtilsTest {
+
+ @Test
+ void test() {
+ PrometheusUtils.PdpType pdpa = PrometheusUtils.PdpType.PDPA;
+ PrometheusUtils.PdpType pdpd = PrometheusUtils.PdpType.PDPD;
+ PrometheusUtils.PdpType pdpx = PrometheusUtils.PdpType.PDPX;
+
+ assertEquals("pdpa", pdpa.getNamespace(), "pdpa constructor");
+ assertEquals("pdpd", pdpd.getNamespace(), "pdpd constructor");
+ assertEquals("pdpx", pdpx.getNamespace(), "pdpx constructor");
+ }
+}
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..d1e891ca 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.
@@ -22,28 +22,28 @@
package org.onap.policy.common.utils.resources;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.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;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* The Class ResourceUtilsTest.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
-public class ResourceUtilsTest {
+class ResourceUtilsTest {
private File tmpDir = null;
private File tmpEmptyFile = null;
private File tmpUsedFile = null;
@@ -63,7 +63,7 @@ public class ResourceUtilsTest {
*
* @throws IOException Signals that an I/O exception has occurred.
*/
- @Before
+ @BeforeEach
public void setupResourceUtilsTest() throws IOException {
tmpDir = new File(System.getProperty("java.io.tmpdir"));
tmpEmptyFile = File.createTempFile(this.getClass().getName(), ".tmp");
@@ -78,19 +78,19 @@ public class ResourceUtilsTest {
}
/**
- * Cleandown resource utils test.
+ * Clean resource utils test.
*/
- @After
- public void cleandownResourceUtilsTest() {
- tmpEmptyFile.delete();
- tmpUsedFile.delete();
+ @AfterEach
+ public void cleanDownResourceUtilsTest() {
+ assertTrue(tmpEmptyFile.delete());
+ assertTrue(tmpUsedFile.delete());
}
/**
* Test get url resource.
*/
@Test
- public void testgetUrlResource() {
+ void testgetUrlResource() {
URL theUrl = ResourceUtils.getUrlResource(tmpDir.getAbsolutePath());
assertNull(theUrl);
@@ -135,7 +135,7 @@ public class ResourceUtilsTest {
* Test get local file.
*/
@Test
- public void testGetLocalFile() {
+ void testGetLocalFile() {
URL theUrl = ResourceUtils.getLocalFile(tmpDir.getAbsolutePath());
assertNotNull(theUrl);
@@ -183,52 +183,33 @@ 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);
+ 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);
+ }
}
/**
* Test get resource as string.
*/
@Test
- public void testGetResourceAsString() {
+ void testGetResourceAsString() {
String theString = ResourceUtils.getResourceAsString(tmpDir.getAbsolutePath());
assertNotNull(theString);
@@ -264,12 +245,12 @@ 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);
}
@Test
- public void testgetUrl4Resource() {
+ void testgetUrl4Resource() {
URL theUrl = ResourceUtils.getUrl4Resource(tmpDir.getAbsolutePath());
assertNotNull(theUrl);
@@ -305,15 +286,15 @@ public class ResourceUtilsTest {
}
@Test
- public void testGetFilePath4Resource() {
+ void testGetFilePath4Resource() {
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
- public void testGetDirectoryContents() throws MalformedURLException {
+ void testGetDirectoryContents() throws MalformedURLException {
assertTrue(ResourceUtils.getDirectoryContents(null).isEmpty());
assertTrue(ResourceUtils.getDirectoryContents("idontexist").isEmpty());
assertTrue(ResourceUtils.getDirectoryContents("logback-test.xml").isEmpty());
@@ -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..ed3be6a3 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.
+ * Copyright (C) 2019-2024 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.
@@ -21,53 +21,100 @@
package org.onap.policy.common.utils.resources;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
-import org.junit.Test;
+import org.apache.commons.io.FileUtils;
+import org.junit.jupiter.api.Test;
/**
* Test text file utilities.
*
* @author Liam Fallon (liam.fallon@est.tech)
*/
-public class TextFileUtilsTest {
+class TextFileUtilsTest {
private static final String FILE_CONTENT = "This is the contents of a text file";
@Test
- public void testPutToFile() throws IOException {
- final File tempTextFile = File.createTempFile("Test", "txt");
+ void testPutToFile() throws IOException {
+ 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 {
+ 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
+ void testCreateTempFile() throws IOException {
+ var file = TextFileUtils.createTempFile("textFileUtilsTest", ".txt");
+ file.deleteOnExit();
+
+ verifyDefaultPermissions(file);
+ }
+
+ @Test
+ 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..5eec8a74 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,8 @@
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,12 +21,15 @@
package org.onap.policy.common.utils.security;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
-import java.security.GeneralSecurityException;
-import org.junit.Test;
+import javax.crypto.spec.SecretKeySpec;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,38 +37,47 @@ import org.slf4j.LoggerFactory;
* Unit test for simple App.
*/
-public class CryptoUtilsTest {
+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: {}";
@Test
- public void testEncrypt() throws GeneralSecurityException {
+ void testConstructor() {
+ SecretKeySpec skspecMock = mock(SecretKeySpec.class);
+ assertThatCode(() -> new CryptoUtils(skspecMock)).doesNotThrowAnyException();
+ }
+
+ @Test
+ void testEncrypt() {
logger.info("testEncrypt:");
CryptoCoder cryptoUtils = new CryptoUtils(SECRET_KEY);
String encryptedValue = cryptoUtils.encrypt(PASS);
logger.info(ENCRYPTED_MSG, PASS, encryptedValue);
assertTrue(encryptedValue.startsWith("enc:"));
+ assertTrue(CryptoUtils.isEncrypted(encryptedValue));
+
String decryptedValue = cryptoUtils.decrypt(encryptedValue);
logger.info(DECRYPTED_MSG, encryptedValue, decryptedValue);
assertEquals(PASS, decryptedValue);
}
@Test
- public void testDecrypt() throws GeneralSecurityException {
+ void testDecrypt() {
logger.info("testDecrypt:");
CryptoCoder cryptoUtils = new CryptoUtils(SECRET_KEY);
String decryptedValue = cryptoUtils.decrypt(ENCRYPTED_PASS);
logger.info(DECRYPTED_MSG, ENCRYPTED_PASS, decryptedValue);
assertEquals(PASS, decryptedValue);
+ assertFalse(CryptoUtils.isEncrypted(decryptedValue));
}
@Test
- public void testStaticEncrypt() {
+ void testStaticEncrypt() {
logger.info("testStaticEncrypt:");
String encryptedValue = CryptoUtils.encrypt(PASS, SECRET_KEY);
logger.info(ENCRYPTED_MSG, PASS, encryptedValue);
@@ -75,7 +88,7 @@ public class CryptoUtilsTest {
}
@Test
- public void testStaticDecrypt() {
+ void testStaticDecrypt() {
logger.info("testStaticDecrypt:");
String decryptedValue = CryptoUtils.decrypt(ENCRYPTED_PASS, SECRET_KEY);
logger.info(DECRYPTED_MSG, ENCRYPTED_PASS, decryptedValue);
@@ -83,7 +96,7 @@ public class CryptoUtilsTest {
}
@Test
- public void testBadInputs() {
+ void testBadInputs() {
String badKey = CryptoUtils.encrypt(PASS, "test");
assertEquals(PASS, badKey);
@@ -104,7 +117,7 @@ public class CryptoUtilsTest {
}
@Test
- public void testAll() {
+ void testAll() {
logger.info("testAll:");
String encryptedValue = CryptoUtils.encrypt(PASS, SECRET_KEY);
logger.info(ENCRYPTED_MSG, PASS, encryptedValue);
@@ -120,4 +133,20 @@ public class CryptoUtilsTest {
String decryptedAgain = CryptoUtils.decrypt(decryptedValue, SECRET_KEY);
assertEquals(decryptedValue, decryptedAgain);
}
-} \ No newline at end of file
+
+ @Test
+ void testMain() {
+ SecretKeySpec skspecMock = mock(SecretKeySpec.class);
+ new CryptoUtils(skspecMock);
+
+ String[] stringsForTesting = new String[1];
+ stringsForTesting[0] = "dec";
+ assertThatCode(() -> CryptoUtils.main(stringsForTesting)).doesNotThrowAnyException();
+
+ stringsForTesting[0] = "enc";
+ assertThatCode(() -> CryptoUtils.main(stringsForTesting)).doesNotThrowAnyException();
+
+ stringsForTesting[0] = "abc";
+ assertThatCode(() -> CryptoUtils.main(stringsForTesting)).doesNotThrowAnyException();
+ }
+}
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 d111962e..3de93779 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
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,18 +21,18 @@
package org.onap.policy.common.utils.services;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Predicate;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class FeatureApiUtilsTest {
+class FeatureApiUtilsTest {
private static final String HANDLED = "handled";
private MyPred pred;
@@ -41,7 +42,7 @@ public class FeatureApiUtilsTest {
/**
* Initializes fields.
*/
- @Before
+ @BeforeEach
public void setUp() {
tried = new LinkedList<>();
errors = new LinkedList<>();
@@ -49,7 +50,7 @@ public class FeatureApiUtilsTest {
}
@Test
- public void testApplyFeatureTrue() {
+ void testApplyFeatureTrue() {
assertTrue(FeatureApiUtils.apply(Arrays.asList("exceptT0", "falseT1", HANDLED, "falseT2", HANDLED), pred,
(str, ex) -> errors.add(str)));
@@ -58,7 +59,7 @@ public class FeatureApiUtilsTest {
}
@Test
- public void testApplyFeatureFalse() {
+ void testApplyFeatureFalse() {
List<String> lst = Arrays.asList("falseF1", "exceptF2", "falseF3");
assertFalse(FeatureApiUtils.apply(lst, pred, (str, ex) -> errors.add(str)));
diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceImplTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceImplTest.java
index 39c8a2be..1508009f 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceImplTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceImplTest.java
@@ -3,6 +3,7 @@
* utils
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,14 +21,14 @@
package org.onap.policy.common.utils.services;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class OrderedServiceImplTest {
+class OrderedServiceImplTest {
private static final int HIGH_PRIORITY_NUM = -1000;
private static final int LOW_PRIORITY_NUM = 1000;
@@ -38,7 +39,7 @@ public class OrderedServiceImplTest {
/**
* Saves the original state of the ordered service list to restore after each test.
*/
- @BeforeClass
+ @BeforeAll
public static void setup() {
List<GenericService> implementers = GenericService.providers.getList();
highPrioService = implementers.get(0);
@@ -48,7 +49,7 @@ public class OrderedServiceImplTest {
/**
* Restores original state after each test.
*/
- @Before
+ @BeforeEach
public void resetOrder() {
highPrioService.setSequenceNumber(HIGH_PRIORITY_NUM);
lowPrioService.setSequenceNumber(LOW_PRIORITY_NUM);
@@ -58,7 +59,7 @@ public class OrderedServiceImplTest {
* Tests obtaining a list of service implementers.
*/
@Test
- public void getListTest() {
+ void getListTest() {
List<GenericService> implementers = GenericService.providers.getList();
assertEquals(2, implementers.size());
@@ -74,7 +75,7 @@ public class OrderedServiceImplTest {
* with the new order.
*/
@Test
- public void rebuildListInvertedPriorityTest() {
+ void rebuildListInvertedPriorityTest() {
List<GenericService> implementers = GenericService.providers.getList();
assertEquals(2, implementers.size());
@@ -104,7 +105,7 @@ public class OrderedServiceImplTest {
* if the priorities are equivalent.
*/
@Test
- public void rebuildListEqualPriorityTest() {
+ void rebuildListEqualPriorityTest() {
List<GenericService> implementers = GenericService.providers.getList();
assertEquals(2, implementers.size());
diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceTest.java
new file mode 100644
index 00000000..adac7cb0
--- /dev/null
+++ b/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceTest.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 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.
+ * 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.services;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+class OrderedServiceTest {
+
+ @Test
+ void testGetSequenceNumber() {
+ // Anonymous class implementation for testing
+ OrderedService service = () -> 5; // Returns 5 as the sequence number
+
+ // Test getSequenceNumber
+ assertEquals(5, service.getSequenceNumber(), "The sequence number should be 5");
+ }
+
+ @Test
+ void testGetName() {
+ // Anonymous class implementation for testing
+ OrderedService service = () -> 5;
+
+ // Test getName
+ assertEquals(service.getClass().getName(), service.getName(), "The name should match the class name");
+ }
+
+ @Test
+ void testGetNameWithCustomImplementation() {
+ // Custom implementation of OrderedService
+ class CustomOrderedService implements OrderedService {
+ @Override
+ public int getSequenceNumber() {
+ return 10;
+ }
+ }
+
+ OrderedService service = new CustomOrderedService();
+
+ // Test getName for custom implementation
+ assertEquals(service.getClass().getName(), service.getName(),
+ "The name should match the custom implementation class name");
+ }
+}
+
diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/RegistryTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/RegistryTest.java
index f4b95089..08799027 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/services/RegistryTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/services/RegistryTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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,16 +24,17 @@ package org.onap.policy.common.utils.services;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
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.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class RegistryTest {
+class RegistryTest {
private static final String UNKNOWN = "unknown";
private static final String NAME_STR = "name-string";
private static final String NAME_OBJ = "name-object";
@@ -45,7 +47,7 @@ public class RegistryTest {
/**
* Set up.
*/
- @Before
+ @BeforeEach
public void setUp() {
Registry.newRegistry();
@@ -57,7 +59,7 @@ public class RegistryTest {
/**
* Ensure the registry is left empty when done.
*/
- @AfterClass
+ @AfterAll
public static void tearDownAfterClass() {
Registry.newRegistry();
}
@@ -66,7 +68,7 @@ public class RegistryTest {
* Sunny day scenario is tested by other tests, so we focus on exceptions here.
*/
@Test
- public void testRegister_Ex() {
+ void testRegister_Ex() {
assertThatIllegalStateException().isThrownBy(() -> Registry.register(NAME_STR, DATA_STR));
assertThatIllegalArgumentException().isThrownBy(() -> Registry.register(null, DATA_STR));
@@ -74,7 +76,7 @@ public class RegistryTest {
}
@Test
- public void testRegisterOrReplace() {
+ void testRegisterOrReplace() {
// should be able to replace
Registry.registerOrReplace(NAME_STR, DATA_STR);
Registry.registerOrReplace(NAME_STR, DATA_STR);
@@ -90,16 +92,16 @@ public class RegistryTest {
}
@Test
- public void testUnregister() {
+ void testUnregister() {
assertTrue(Registry.unregister(NAME_STR));
- assertEquals(null, Registry.getOrDefault(NAME_STR, String.class, null));
+ assertNull(Registry.getOrDefault(NAME_STR, String.class, null));
assertFalse(Registry.unregister(NAME_STR));
}
@Test
- public void testGet() {
+ void testGet() {
assertSame(DATA_STR, Registry.get(NAME_STR, String.class));
assertSame(DATA_OBJ, Registry.get(NAME_OBJ, Object.class));
assertSame(DATA_INT, Registry.get(NAME_INT, Integer.class));
@@ -112,24 +114,24 @@ public class RegistryTest {
}
@Test
- public void testGetOrDefault() {
+ void testGetOrDefault() {
assertSame(DATA_STR, Registry.getOrDefault(NAME_STR, String.class, null));
assertSame(DATA_OBJ, Registry.getOrDefault(NAME_OBJ, Object.class, "xyz"));
assertSame(DATA_INT, Registry.getOrDefault(NAME_INT, Integer.class, 10));
- assertEquals(null, Registry.getOrDefault(UNKNOWN, String.class, null));
+ assertNull(Registry.getOrDefault(UNKNOWN, String.class, null));
assertEquals("abc", Registry.getOrDefault(UNKNOWN, String.class, "abc"));
assertEquals(Integer.valueOf(11), Registry.getOrDefault(UNKNOWN, Integer.class, 11));
}
@Test
- public void testNewRegistry() {
+ void testNewRegistry() {
assertSame(DATA_STR, Registry.get(NAME_STR, String.class));
Registry.newRegistry();
// should not exist
- assertEquals(null, Registry.getOrDefault(NAME_STR, String.class, null));
+ assertNull(Registry.getOrDefault(NAME_STR, String.class, null));
// should be able to register it again now
Registry.register(NAME_STR, DATA_STR);
diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerContainerTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerContainerTest.java
index e57901ac..1bae46cb 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerContainerTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerContainerTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,19 +21,19 @@
package org.onap.policy.common.utils.services;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.capabilities.Startable;
import org.onap.policy.common.utils.services.ServiceManager.RunnableWithEx;
-public class ServiceManagerContainerTest {
+class ServiceManagerContainerTest {
private static final String MY_NAME = "my-name";
private static final String MY_ACTION = "my-action";
private static final String MY_OBJECT = "my-object";
@@ -44,7 +45,7 @@ public class ServiceManagerContainerTest {
/**
* Set up.
*/
- @Before
+ @BeforeEach
public void setUp() {
starter = mock(RunnableWithEx.class);
stopper = mock(RunnableWithEx.class);
@@ -54,7 +55,7 @@ public class ServiceManagerContainerTest {
}
@Test
- public void testServiceManagerContainer() throws Exception {
+ void testServiceManagerContainer() throws Exception {
// use no-arg constructor
cont = new MyCont();
assertEquals("service manager", cont.getName());
@@ -64,7 +65,7 @@ public class ServiceManagerContainerTest {
}
@Test
- public void test() throws Exception {
+ void test() throws Exception {
assertEquals(MY_NAME, cont.getName());
assertFalse(cont.isAlive());
@@ -87,7 +88,7 @@ public class ServiceManagerContainerTest {
}
@Test
- public void testShutdown() throws Exception {
+ void testShutdown() throws Exception {
cont.start();
cont.shutdown();
assertFalse(cont.isAlive());
diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerExceptionTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerExceptionTest.java
index 5fe321e8..8d6c8a28 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerExceptionTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,32 +21,32 @@
package org.onap.policy.common.utils.services;
-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.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class ServiceManagerExceptionTest {
+class ServiceManagerExceptionTest {
private ServiceManagerException sme;
@Test
- public void testServiceManagerException() {
+ void testServiceManagerException() {
sme = new ServiceManagerException();
assertNull(sme.getMessage());
assertNull(sme.getCause());
}
@Test
- public void testServiceManagerExceptionString() {
+ void testServiceManagerExceptionString() {
sme = new ServiceManagerException("hello");
assertEquals("hello", sme.getMessage());
assertNull(sme.getCause());
}
@Test
- public void testServiceManagerExceptionThrowable() {
+ void testServiceManagerExceptionThrowable() {
Throwable thrown = new Throwable("expected exception");
sme = new ServiceManagerException(thrown);
assertNotNull(sme.getMessage());
@@ -53,7 +54,7 @@ public class ServiceManagerExceptionTest {
}
@Test
- public void testServiceManagerExceptionStringThrowable() {
+ void testServiceManagerExceptionStringThrowable() {
Throwable thrown = new Throwable("another expected exception");
sme = new ServiceManagerException("world", thrown);
assertEquals("world", sme.getMessage());
diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java
index 83b2629c..dc555584 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/services/ServiceManagerTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -22,9 +23,9 @@ package org.onap.policy.common.utils.services;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
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.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -32,12 +33,12 @@ import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.LinkedList;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.capabilities.Startable;
import org.onap.policy.common.utils.services.ServiceManager.RunnableWithEx;
-public class ServiceManagerTest {
+class ServiceManagerTest {
private static final String MY_NAME = "my-name";
private static final String ALREADY_RUNNING = MY_NAME + " is already running";
private static final String EXPECTED_EXCEPTION = "expected exception";
@@ -47,23 +48,23 @@ public class ServiceManagerTest {
/**
* Initializes {@link #svcmgr}.
*/
- @Before
+ @BeforeEach
public void setUp() {
svcmgr = new ServiceManager(MY_NAME);
}
@Test
- public void testServiceName() {
+ void testServiceName() {
assertEquals("service manager", new ServiceManager().getName());
}
@Test
- public void testGetName() {
+ void testGetName() {
assertEquals(MY_NAME, svcmgr.getName());
}
@Test
- public void testAddAction() throws Exception {
+ void testAddAction() throws Exception {
RunnableWithEx start1 = mock(RunnableWithEx.class);
RunnableWithEx stop1 = mock(RunnableWithEx.class);
svcmgr.addAction("first action", start1, stop1);
@@ -90,7 +91,7 @@ public class ServiceManagerTest {
}
@Test
- public void testAddStartable() {
+ void testAddStartable() {
Startable start1 = mock(Startable.class);
svcmgr.addService("first startable", start1);
@@ -115,7 +116,7 @@ public class ServiceManagerTest {
}
@Test
- public void testStart() {
+ void testStart() {
Startable start1 = mock(Startable.class);
svcmgr.addService("test start", start1);
@@ -136,7 +137,7 @@ public class ServiceManagerTest {
}
@Test
- public void testStart_Ex() {
+ void testStart_Ex() {
Startable start1 = mock(Startable.class);
svcmgr.addService("test start ex", start1);
@@ -173,7 +174,7 @@ public class ServiceManagerTest {
}
@Test
- public void testStart_RewindEx() {
+ void testStart_RewindEx() {
Startable start1 = mock(Startable.class);
svcmgr.addService("test start rewind", start1);
@@ -201,7 +202,7 @@ public class ServiceManagerTest {
}
@Test
- public void testStop() {
+ void testStop() {
Startable start1 = mock(Startable.class);
svcmgr.addService("first stop", start1);
@@ -221,7 +222,7 @@ public class ServiceManagerTest {
}
@Test
- public void testStop_Ex() throws Exception {
+ void testStop_Ex() throws Exception {
RunnableWithEx start1 = mock(RunnableWithEx.class);
RunnableWithEx stop1 = mock(RunnableWithEx.class);
svcmgr.addAction("first stop ex", start1, stop1);
@@ -245,7 +246,7 @@ public class ServiceManagerTest {
}
@Test
- public void testShutdown() {
+ void testShutdown() {
Startable start1 = mock(Startable.class);
svcmgr.addService("first stop", start1);
@@ -265,7 +266,7 @@ public class ServiceManagerTest {
}
@Test
- public void testRewind() {
+ void testRewind() {
RunnableWithEx starter = mock(RunnableWithEx.class);
LinkedList<String> lst = new LinkedList<>();
diff --git a/utils/src/test/java/org/onap/policy/common/utils/time/CurrentTimeTest.java b/utils/src/test/java/org/onap/policy/common/utils/time/CurrentTimeTest.java
index 499372ab..7b267581 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/time/CurrentTimeTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/time/CurrentTimeTest.java
@@ -3,6 +3,7 @@
* Common Utils
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -20,14 +21,14 @@
package org.onap.policy.common.utils.time;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class CurrentTimeTest {
+class CurrentTimeTest {
@Test
- public void testGetMillis() {
+ void testGetMillis() {
long tcur = System.currentTimeMillis();
long tval = new CurrentTime().getMillis();
long tval2 = new CurrentTime().getMillis();
@@ -38,7 +39,7 @@ public class CurrentTimeTest {
}
@Test
- public void testGetDate() {
+ void testGetDate() {
long tcur = System.currentTimeMillis();
long tval = new CurrentTime().getDate().getTime();
long tval2 = new CurrentTime().getDate().getTime();
@@ -49,7 +50,7 @@ public class CurrentTimeTest {
}
@Test
- public void testSleep() throws Exception {
+ void testSleep() throws Exception {
long tcur = System.currentTimeMillis();
new CurrentTime().sleep(10);
long tend = System.currentTimeMillis();
diff --git a/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java b/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java
index 05d4c5c3..b633425f 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/validation/AssertionsTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2024 Nordix Foundation.
* Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -23,17 +23,17 @@
package org.onap.policy.common.utils.validation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* The Class ResourceUtilsTest.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
-public class AssertionsTest {
+class AssertionsTest {
private static final String HELLO = "Hello";
private static final String IT_IS_OK = "it is OK";
private static final String IT_IS_NULL = "it is null";
@@ -41,7 +41,7 @@ public class AssertionsTest {
private static final String IT_IS_FALSE = "it is false";
@Test
- public void testAssertions() {
+ void testAssertions() {
Assertions.argumentNotFalse(true, IT_IS_TRUE);
assertThatIllegalArgumentException().isThrownBy(() -> Assertions.argumentNotFalse(false, IT_IS_FALSE))
diff --git a/utils/src/test/java/org/onap/policy/common/utils/validation/TestParameterValidationUtils.java b/utils/src/test/java/org/onap/policy/common/utils/validation/TestParameterValidationUtils.java
index 7d46553b..a85e8ec8 100644
--- a/utils/src/test/java/org/onap/policy/common/utils/validation/TestParameterValidationUtils.java
+++ b/utils/src/test/java/org/onap/policy/common/utils/validation/TestParameterValidationUtils.java
@@ -2,6 +2,7 @@
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 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.
@@ -21,27 +22,27 @@
package org.onap.policy.common.utils.validation;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Class to perform unit test of ParameterValidationUtils.
*
* @author Ram Krishna Verma (ram.krishna.verma@ericsson.com)
*/
-public class TestParameterValidationUtils {
+class TestParameterValidationUtils {
@Test
- public void testValidateStringParameter() {
+ void testValidateStringParameter() {
assertTrue(ParameterValidationUtils.validateStringParameter("Policy"));
assertFalse(ParameterValidationUtils.validateStringParameter(null));
assertFalse(ParameterValidationUtils.validateStringParameter(""));
}
@Test
- public void testValidateIntParameter() {
+ void testValidateIntParameter() {
assertTrue(ParameterValidationUtils.validateIntParameter(5555));
assertTrue(ParameterValidationUtils.validateIntParameter(Integer.valueOf(7777)));
assertFalse(ParameterValidationUtils.validateIntParameter(0));
@@ -49,7 +50,7 @@ public class TestParameterValidationUtils {
}
@Test
- public void testValidateLongParameter() {
+ void testValidateLongParameter() {
assertTrue(ParameterValidationUtils.validateLongParameter(5555L));
assertTrue(ParameterValidationUtils.validateLongParameter(Long.valueOf(7777L)));
assertFalse(ParameterValidationUtils.validateLongParameter(0L));
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 4673233e..19023124 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
@@ -3,7 +3,7 @@
* ONAP PAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-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.
@@ -21,15 +21,15 @@
package org.onap.policy.common.utils.validation;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class VersionTest {
+class VersionTest {
private static final String TYPE = "my-type";
private static final String NAME = "my-name";
@@ -39,20 +39,33 @@ public class VersionTest {
private Version vers;
- @Before
+ @BeforeEach
public void setUp() {
vers = new Version(MAJOR, MINOR, PATCH);
}
@Test
- public void testHashCode() {
+ void testHashCode() {
int hash = vers.hashCode();
int hash2 = new Version(MAJOR, MINOR, PATCH + 1).hashCode();
assertNotEquals(hash, hash2);
}
@Test
- public void testMakeVersion() {
+ void testConstructor() {
+ Version versionTest = new Version("1.0.2");
+ assertEquals(1, versionTest.getMajor());
+ assertEquals(0, versionTest.getMinor());
+ assertEquals(2, versionTest.getPatch());
+
+ versionTest = new Version("null");
+ assertEquals(0, versionTest.getMajor());
+ assertEquals(0, versionTest.getMinor());
+ assertEquals(0, versionTest.getPatch());
+ }
+
+ @Test
+ void testMakeVersion() {
assertEquals("9.8.7", Version.makeVersion(TYPE, NAME, "9.8.7").toString());
assertEquals("9.0.0", Version.makeVersion(TYPE, NAME, "9").toString());
@@ -65,14 +78,14 @@ public class VersionTest {
}
@Test
- public void testNewVersion() {
+ void testNewVersion() {
vers = vers.newVersion();
assertEquals("11.0.0", vers.toString());
}
@Test
- public void testEquals() {
- assertNotEquals(vers, null);
+ void testEquals() {
+ assertNotEquals(null, vers);
assertNotEquals(vers, new Object());
assertEquals(vers, vers);
@@ -85,7 +98,7 @@ public class VersionTest {
}
@Test
- public void testCompareTo() {
+ void testCompareTo() {
vers = new Version(101, 201, 301);
// equals case
@@ -111,32 +124,32 @@ public class VersionTest {
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("10.2.3", vers.toString());
}
@Test
- public void testGetMajor() {
+ void testGetMajor() {
assertEquals(MAJOR, vers.getMajor());
}
@Test
- public void testGetMinor() {
+ void testGetMinor() {
assertEquals(MINOR, vers.getMinor());
}
@Test
- public void testGetPatch() {
+ void testGetPatch() {
assertEquals(PATCH, vers.getPatch());
}
@Test
- public void testVersionIntIntInt() {
+ void testVersionIntIntInt() {
assertEquals("5.6.7", new Version(5, 6, 7).toString());
}
@Test
- public void testVersion() {
+ void testVersion() {
assertEquals("0.0.0", new Version().toString());
}
}