diff options
Diffstat (limited to 'utils-test')
34 files changed, 772 insertions, 488 deletions
diff --git a/utils-test/pom.xml b/utils-test/pom.xml index 08572ff1..6338cc08 100644 --- a/utils-test/pom.xml +++ b/utils-test/pom.xml @@ -2,7 +2,8 @@ ============LICENSE_START======================================================= ONAP Policy Engine - Common Modules ================================================================================ - Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. + Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. + Modificaitons 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. @@ -24,7 +25,7 @@ <parent> <groupId>org.onap.policy.common</groupId> <artifactId>common-modules</artifactId> - <version>1.7.1-SNAPSHOT</version> + <version>3.0.1-SNAPSHOT</version> </parent> <artifactId>utils-test</artifactId> @@ -33,98 +34,63 @@ <properties> <powermock.version>2.0.4</powermock.version> + <!-- this whole module is testing code --> + <sonar.skip>true</sonar.skip> </properties> <dependencies> <dependency> - <groupId>com.google.re2j</groupId> - <artifactId>re2j</artifactId> + <groupId>org.bouncycastle</groupId> + <artifactId>bcpkix-fips</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-jexl3</artifactId> - <version>3.1</version> - </dependency> - <dependency> - <groupId>org.projectlombok</groupId> - <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> + <groupId>org.onap.policy.common</groupId> + <artifactId>utils</artifactId> + <version>${project.version}</version> <scope>provided</scope> </dependency> - <dependency> - <groupId>org.assertj</groupId> - <artifactId>assertj-core</artifactId> + + <!-- from parent --> + <dependency> + <groupId>org.awaitility</groupId> + <artifactId>awaitility</artifactId> <scope>test</scope> </dependency> <dependency> - <groupId>ch.qos.logback</groupId> - <artifactId>logback-classic</artifactId> + <groupId>com.openpojo</groupId> + <artifactId>openpojo</artifactId> + <scope>compile</scope> </dependency> <dependency> - <groupId>org.onap.policy.common</groupId> - <artifactId>utils</artifactId> - <version>${project.version}</version> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-api</artifactId> + <scope>compile</scope> </dependency> <dependency> - <groupId>org.onap.policy.common</groupId> - <artifactId>gson</artifactId> - <version>${project.version}</version> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <scope>test</scope> </dependency> <dependency> - <groupId>org.powermock</groupId> - <artifactId>powermock-api-mockito2</artifactId> + <groupId>org.mockito</groupId> + <artifactId>mockito-junit-jupiter</artifactId> <scope>test</scope> </dependency> - <dependency> - <groupId>org.awaitility</groupId> - <artifactId>awaitility</artifactId> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> <scope>test</scope> </dependency> <dependency> - <groupId>com.openpojo</groupId> - <artifactId>openpojo</artifactId> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-core</artifactId> + <version>2.2</version> <scope>compile</scope> </dependency> </dependencies> - - <build> - <pluginManagement> - <plugins> - <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven - build itself. --> - <plugin> - <groupId>org.eclipse.m2e</groupId> - <artifactId>lifecycle-mapping</artifactId> - <version>1.0.0</version> - <configuration> - <lifecycleMappingMetadata> - <pluginExecutions> - <pluginExecution> - <pluginExecutionFilter> - <groupId>org.jacoco</groupId> - <artifactId> - jacoco-maven-plugin - </artifactId> - <versionRange> - [0.7.1.201405082137,) - </versionRange> - <goals> - <goal>prepare-agent</goal> - </goals> - </pluginExecutionFilter> - <action> - <ignore /> - </action> - </pluginExecution> - </pluginExecutions> - </lifecycleMappingMetadata> - </configuration> - </plugin> - </plugins> - </pluginManagement> - </build> </project> diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java b/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java index 01206c32..1d131aed 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/gson/GsonTestUtils.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * policy-management * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-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,29 +21,27 @@ package org.onap.policy.common.utils.gson; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; -import com.google.re2j.Matcher; import com.google.re2j.Pattern; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.URL; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Map.Entry; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.apache.commons.jexl3.JexlBuilder; import org.apache.commons.jexl3.JexlContext; import org.apache.commons.jexl3.JexlEngine; -import org.apache.commons.jexl3.JexlException; import org.apache.commons.jexl3.MapContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,6 +49,8 @@ import org.slf4j.LoggerFactory; /** * Utilities used to test encoding and decoding of Policy objects. */ +@Getter +@AllArgsConstructor(access = AccessLevel.PROTECTED) public class GsonTestUtils { private static final Logger logger = LoggerFactory.getLogger(GsonTestUtils.class); @@ -79,19 +80,6 @@ public class GsonTestUtils { } /** - * Constructs the object. - * - * @param gson used to encode via gson - */ - protected GsonTestUtils(Gson gson) { - this.gson = gson; - } - - public Gson getGson() { - return gson; - } - - /** * Serializes and then deserializes an object using gson. * * @param object the object to be serialized @@ -110,7 +98,6 @@ public class GsonTestUtils { * * @param object the object to be encoded * @param expected the expected value - * @throws Exception if the file cannot be read */ public void compareGson(Object object, Class<?> expected) { compareGson(object, new File(expected.getSimpleName() + ".json")); @@ -123,11 +110,10 @@ public class GsonTestUtils { * * @param object the object to be encoded * @param expected the expected value - * @throws Exception if the file cannot be read */ public void compareGson(Object object, File expected) { // file is not required to have a full path - find it via getResource() - URL url = object.getClass().getResource(expected.getName()); + var url = object.getClass().getResource(expected.getName()); if (url == null) { throw new JsonParseException(new FileNotFoundException(expected.getName())); } @@ -169,7 +155,11 @@ public class GsonTestUtils { JsonElement gsonjo = reorder(gson.fromJson(sgson, JsonElement.class)); JsonElement expjo = reorder(expected); - assertEquals(expjo.toString(), gsonjo.toString()); + /* + * As this method is only used within junit tests, it is OK to use assert calls, + * thus sonar is disabled. + */ + assertEquals(expjo.toString(), gsonjo.toString()); // NOSONAR } /** @@ -179,7 +169,7 @@ public class GsonTestUtils { * @throws IOException if an error occurs */ protected String readFile(File file) throws IOException { - return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + return Files.readString(file.toPath()); } @@ -193,7 +183,7 @@ public class GsonTestUtils { * @return the text, after interpolating the script elements */ public String applyScripts(String text, Object object) { - Matcher mat = SCRIPT_PAT.matcher(text); + var mat = SCRIPT_PAT.matcher(text); if (!mat.find()) { // contains no script elements - just return it as is return text; @@ -205,30 +195,25 @@ public class GsonTestUtils { context.set("obj", object); // work our way through the text, interpolating script elements as we go - StringBuilder bldr = new StringBuilder(); - int ilast = 0; + var bldr = new StringBuilder(); + var ilast = 0; mat.reset(); while (mat.find(ilast)) { // append segment that appears between last match and this int inext = mat.start(); - bldr.append(text.substring(ilast, inext)); + bldr.append(text, ilast, inext); // next match begins after the current match ilast = mat.end(); // interpolate the script String script = mat.group(1); - try { - /* - * Note: must use "eng" instead of "engineInstance" to ensure that we use - * the same engine that's associated with the bindings. - */ - Object result = eng.createExpression(script).evaluate(context); - bldr.append(result == null ? "null" : result.toString()); - - } catch (JexlException e) { - throw new JsonParseException("cannot expand element: " + mat.group(), e); - } + /* + * Note: must use "eng" instead of "engineInstance" to ensure that we use + * the same engine that's associated with the bindings. + */ + Object result = eng.createExpression(script).evaluate(context); + bldr.append(result == null ? "null" : result.toString()); } // append final segment @@ -271,11 +256,11 @@ public class GsonTestUtils { * @return a new object, without the null items */ public JsonObject reorder(JsonObject jsonObj) { - JsonObject newjo = new JsonObject(); + var newjo = new JsonObject(); // sort the keys before copying to the new object List<Entry<String, JsonElement>> sortedSet = new ArrayList<>(jsonObj.entrySet()); - Collections.sort(sortedSet, (left, right) -> left.getKey().compareTo(right.getKey())); + sortedSet.sort(Entry.comparingByKey()); for (Entry<String, JsonElement> ent : sortedSet) { JsonElement val = ent.getValue(); @@ -297,7 +282,7 @@ public class GsonTestUtils { * @return a new array, with null items removed from all elements */ public JsonArray reorder(JsonArray jsonArray) { - JsonArray newarr = new JsonArray(); + var newarr = new JsonArray(); for (JsonElement ent : jsonArray) { newarr.add(reorder(ent)); } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java b/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java index 7e09cd96..f3e1418a 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/io/Serializer.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine - Common Modules * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,13 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; /** * Utilities for testing serialization and de-serialization of objects. */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class Serializer { /** @@ -37,13 +40,6 @@ public class Serializer { private static Factory factory = new Factory(); /** - * The constructor. - */ - private Serializer() { - - } - - /** * Serializes an object into a byte array. * * @param object the object to be serialized @@ -51,8 +47,8 @@ public class Serializer { * @throws IOException if an error occurs */ public static <T> byte[] serialize(T object) throws IOException { - try (ByteArrayOutputStream out = factory.makeByteArrayOutputStream()) { - try (ObjectOutputStream oos = factory.makeObjectOutputStream(out)) { + try (var out = factory.makeByteArrayOutputStream()) { + try (var oos = factory.makeObjectOutputStream(out)) { /* * writeObject() is final and mockito can't mock final methods. In * addition, powermock seemed to be having difficulty with the junit test @@ -75,8 +71,8 @@ public class Serializer { */ private static <T> T deserialize(Class<T> clazz, byte[] data) throws IOException { - try (ByteArrayInputStream in = factory.makeByteArrayInputStream(data); - ObjectInputStream ois = factory.makeObjectInputStream(in)) { + try (var in = factory.makeByteArrayInputStream(data); + var ois = factory.makeObjectInputStream(in)) { /* * readObject() is final and mockito can't mock final methods. In addition, * powermock seemed to be having difficulty with the junit test class as well, diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java b/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java new file mode 100644 index 00000000..9fa1067d --- /dev/null +++ b/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java @@ -0,0 +1,159 @@ +/*- + * ============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.security; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.file.Files; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.Arrays; +import java.util.Date; +import java.util.concurrent.TimeUnit; +import lombok.Getter; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * Keystore, containing a self-signed certificate, valid for one day (see the argument to + * the "-valid" flag below). For use in junit tests. + */ +@Getter +public class SelfSignedKeyStore { + public static final String KEYSTORE_PASSWORD = "Pol1cy_0nap"; + public static final String PRIVATE_KEY_PASSWORD = KEYSTORE_PASSWORD; + public static final String RELATIVE_PATH = "target/test-classes/policy-keystore"; + + /** + * File containing subject-alternative names (i.e., list of servers that may use this + * keystore). + */ + private static final String KEYSTORE_SAN = "keystore_san.txt"; + + private final String keystoreName; + + + /** + * Generates the keystore, if it does not exist or if it's more than a few hours old. + * + * @throws IOException if an I/O error occurs + */ + public SelfSignedKeyStore() throws IOException { + this(RELATIVE_PATH); + } + + /** + * Generates the keystore, if it does not exist or if it's more than a few hours old. + * + * @param relativePath path to the keystore, relative to the "user.dir" system + * property + * @throws IOException if an I/O error occurs + */ + public SelfSignedKeyStore(String relativePath) throws IOException { + keystoreName = System.getProperty("user.dir") + "/" + relativePath; + + // use existing file if it isn't too old + var keystoreFile = new File(keystoreName); + if (keystoreFile.exists()) { + if (System.currentTimeMillis() < keystoreFile.lastModified() + + TimeUnit.MILLISECONDS.convert(5, TimeUnit.HOURS)) { + return; + } + + Files.delete(keystoreFile.toPath()); + } + + /* + * Read the list of subject-alternative names, joining the lines with commas, and + * dropping the trailing comma. + */ + String sanFileName = getKeystoreSanName(); + var sanString = ResourceUtils.getResourceAsString(sanFileName); + if (sanString == null) { + throw new FileNotFoundException(sanFileName); + } + + var sanArray = sanString.replace("DNS:", "").replace("\r", "").split("\n"); + GeneralName[] nameArray = Arrays.stream(sanArray).map(name -> new GeneralName(GeneralName.dNSName, name)) + .toList().toArray(new GeneralName[0]); + final var names = new GeneralNames(nameArray); + + try (var ostr = new FileOutputStream(keystoreFile)) { + var keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + final var keyPair = keyPairGenerator.generateKeyPair(); + + final long tcur = System.currentTimeMillis(); + + final var dn = new X500Name("C=US, O=ONAP, OU=OSAAF, OU=policy@policy.onap.org:DEV, CN=policy"); + final var serial = BigInteger.valueOf(new SecureRandom().nextInt()); + final var notBefore = new Date(tcur); + final var notAfter = new Date(tcur + TimeUnit.MILLISECONDS.convert(365, TimeUnit.DAYS)); + final var pubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); + + ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA") + .setProvider(new BouncyCastleFipsProvider()).build(keyPair.getPrivate()); + + X509CertificateHolder holder = new X509v3CertificateBuilder(dn, serial, notBefore, notAfter, dn, pubKeyInfo) + .addExtension(Extension.subjectAlternativeName, false, names).build(signer); + + var cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleFipsProvider()) + .getCertificate(holder); + final Certificate[] chain = {cert}; + + var keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, null); + keystore.setKeyEntry("policy@policy.onap.org", keyPair.getPrivate(), PRIVATE_KEY_PASSWORD.toCharArray(), + chain); + + keystore.store(ostr, KEYSTORE_PASSWORD.toCharArray()); + + } catch (NoSuchAlgorithmException | OperatorCreationException | CertificateException | KeyStoreException e) { + throw new IOException("cannot create certificate", e); + } + } + + // may be overridden by junit tests + + protected String getKeystoreSanName() { + return KEYSTORE_SAN; + } +} diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java index f457dd21..34dc5681 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ExceptionsTester.java @@ -2,7 +2,8 @@ * ============LICENSE_START==================================================== * Common Utils-Test * ============================================================================= - * Copyright (C) 2018 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,9 +21,9 @@ package org.onap.policy.common.utils.test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -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.assertTrue; import java.lang.reflect.Constructor; @@ -70,7 +71,7 @@ public class ExceptionsTester extends ThrowablesTester { * if the constructed objects fail to pass various tests */ public <T extends Exception> int testAllException(final Class<T> claz) { - int ncons = 0; + var ncons = 0; ncons += testAllThrowable(claz); ncons += testException(claz); @@ -111,8 +112,8 @@ public class ExceptionsTester extends ThrowablesTester { return 0; } - Exception cause = new Exception(EXPECTED_EXCEPTION_MSG); - T ex = newInstance(cons, cause); + var cause = new Exception(EXPECTED_EXCEPTION_MSG); + var ex = newInstance(cons, cause); assertNotNull(ex.toString()); assertEquals(ex.getMessage(), ex.getMessage()); @@ -151,8 +152,8 @@ public class ExceptionsTester extends ThrowablesTester { return 0; } - Exception cause = new Exception(EXPECTED_EXCEPTION_MSG); - T ex = newInstance(cons, "world", cause); + var cause = new Exception(EXPECTED_EXCEPTION_MSG); + var ex = newInstance(cons, "world", cause); assertNotNull(ex.toString()); assertEquals("world", ex.getMessage()); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java index fd819b25..62584c76 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ThrowablesTester.java @@ -2,7 +2,8 @@ * ============LICENSE_START==================================================== * Common Utils-Test * ============================================================================= - * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018, 2020-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,10 +21,10 @@ package org.onap.policy.common.utils.test; -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.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -73,7 +74,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> int testAllThrowable( final Class<T> claz) { - int ncons = 0; + var ncons = 0; ncons += testDefault(claz); ncons += testString(claz); @@ -112,7 +113,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons); + var ex = newInstance(cons); assertNotNull(ex.toString()); assertNull(ex.getMessage()); @@ -151,7 +152,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons, "hello"); + var ex = newInstance(cons, "hello"); assertNotNull(ex.toString()); assertEquals("hello", ex.getMessage()); @@ -191,7 +192,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons, CAUSE); + var ex = newInstance(cons, CAUSE); assertEquals(ex.getMessage(), ex.getMessage()); assertNotNull(ex.toString()); @@ -231,7 +232,7 @@ public class ThrowablesTester { return 0; } - T ex = newInstance(cons, "world", CAUSE); + var ex = newInstance(cons, "world", CAUSE); assertNotNull(ex.toString()); assertEquals("world", ex.getMessage()); @@ -382,7 +383,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testSuppressStack( final Constructor<T> cons) { - T ex = newInstance(cons, "yes,yes", CAUSE, true, true); + var ex = newInstance(cons, "yes,yes", CAUSE, true, true); ex.addSuppressed(SUPPRESSED); @@ -420,7 +421,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testSuppressNoStack( final Constructor<T> cons) { - T ex = newInstance(cons, "yes,no", CAUSE, true, false); + var ex = newInstance(cons, "yes,no", CAUSE, true, false); ex.addSuppressed(SUPPRESSED); @@ -458,7 +459,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testNoSuppressStack( final Constructor<T> cons) { - T ex = newInstance(cons, "no,yes", CAUSE, false, true); + var ex = newInstance(cons, "no,yes", CAUSE, false, true); ex.addSuppressed(SUPPRESSED); @@ -494,7 +495,7 @@ public class ThrowablesTester { */ public final <T extends Throwable> void testNoSuppressNoStack( final Constructor<T> cons) { - T ex = newInstance(cons, "no,no", CAUSE, false, false); + var ex = newInstance(cons, "no,no", CAUSE, false, false); ex.addSuppressed(SUPPRESSED); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java index 3890ae95..ab09291c 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/ToStringTester.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,6 +29,7 @@ import com.openpojo.reflection.PojoClass; import com.openpojo.validation.affirm.Affirm; import com.openpojo.validation.test.Tester; import com.openpojo.validation.utils.ValidationHelper; +import lombok.AllArgsConstructor; import org.hamcrest.Matcher; @@ -37,6 +38,7 @@ import org.hamcrest.Matcher; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +@AllArgsConstructor public class ToStringTester implements Tester { private final Matcher<?> matcher; @@ -45,10 +47,6 @@ public class ToStringTester implements Tester { matcher = anything(); } - public ToStringTester(final Matcher<?> matcher) { - this.matcher = matcher; - } - @SuppressWarnings("unchecked") @Override public void run(final PojoClass pojoClass) { diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java b/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java index 19c50968..27d9fcc6 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/test/log/logback/ExtractAppender.java @@ -2,7 +2,7 @@ * ============LICENSE_START==================================================== * Common Utils-Test * ============================================================================= - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights reserved. * ============================================================================= * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,13 @@ package org.onap.policy.common.utils.test.log.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; +import com.google.re2j.Matcher; +import com.google.re2j.Pattern; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Queue; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * This is an appender that is intended for use by JUnit tests that wish to @@ -110,7 +110,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> { } for (Pattern p : patterns.values()) { - Matcher matcher = p.matcher(msg); + var matcher = p.matcher(msg); if (matcher.find()) { addGroupMatch(matcher); @@ -129,7 +129,7 @@ public class ExtractAppender extends AppenderBase<ILoggingEvent> { private void addGroupMatch(final Matcher mat) { int ngroups = mat.groupCount(); - for (int x = 1; x <= ngroups; ++x) { + for (var x = 1; x <= ngroups; ++x) { String txt = mat.group(x); if (txt != null) { diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java index d8b792a8..b29f7421 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoExecutor.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * 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. @@ -61,7 +61,7 @@ public class PseudoExecutor implements Executor { * tasks have been reached before the queue was emptied */ public boolean runAll(int maxTasks) { - for (int count = 0; count < maxTasks && !tasks.isEmpty(); ++count) { + for (var count = 0; count < maxTasks && !tasks.isEmpty(); ++count) { tasks.remove().run(); } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java index 847b058e..71a24528 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; +import lombok.Getter; /** * Scheduled executor service that uses {@link TestTimeMulti} to execute its tasks. Note: @@ -48,6 +49,7 @@ public class PseudoScheduledExecutorService implements ScheduledExecutorService * {@code True} if {@link #shutdown()} or {@link #shutdownNow()} has been called, * {@code false} otherwise. */ + @Getter private boolean shutdown = false; /** @@ -80,11 +82,6 @@ public class PseudoScheduledExecutorService implements ScheduledExecutorService } @Override - public boolean isShutdown() { - return shutdown; - } - - @Override public boolean isTerminated() { return isShutdown(); } diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java index 6ce7bc04..34c756bb 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/PseudoScheduledFuture.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,6 +39,7 @@ class PseudoScheduledFuture<T> extends FutureTask<T> implements RunnableSchedule /** * {@code True} if this task is periodic, {@code false} otherwise. */ + @Getter private final boolean periodic; /** @@ -82,11 +83,6 @@ class PseudoScheduledFuture<T> extends FutureTask<T> implements RunnableSchedule } @Override - public boolean isPeriodic() { - return periodic; - } - - @Override public void run() { if (isPeriodic()) { super.runAndReset(); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java index 420021f3..ace19160 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTime.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Common Utils-Test * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,12 +22,14 @@ package org.onap.policy.common.utils.time; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; +import lombok.NoArgsConstructor; /** * "Current" time, when running junit tests. This is intended to be injected into classes * under test, to replace their {@link CurrentTime} objects. When {@link #sleep(long)} is * invoked, it simply advances the notion of "current" time and returns immediately. */ +@NoArgsConstructor public class TestTime extends CurrentTime { /** @@ -35,14 +37,6 @@ public class TestTime extends CurrentTime { */ private AtomicLong tcur = new AtomicLong(System.currentTimeMillis()); - /** - * Constructor. - * - */ - public TestTime() { - super(); - } - @Override public long getMillis() { return tcur.get(); diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java index f4b36a00..8ffcd36a 100644 --- a/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java +++ b/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * 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,7 +21,7 @@ package org.onap.policy.common.utils.time; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Iterator; import java.util.LinkedList; @@ -189,11 +190,13 @@ public class TestTimeMulti extends TestTime { } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("interrupted while waiting for condition", e); - fail("interrupted while waiting for condition: " + e.getMessage()); + // disabling sonar, as this is only used by junit tests + fail("interrupted while waiting for condition: " + e.getMessage()); // NOSONAR } catch (Exception e) { logger.error("condition evaluator threw an exception", e); - fail("condition evaluator threw an exception: " + e.getMessage()); + // disabling sonar, as this is only used by junit tests + fail("condition evaluator threw an exception: " + e.getMessage()); // NOSONAR } fail(NEVER_SATISFIED); @@ -280,7 +283,7 @@ public class TestTimeMulti extends TestTime { return; } - SleepItem item = new SleepItem(this, sleepMs, Thread.currentThread()); + var item = new SleepItem(this, sleepMs, Thread.currentThread()); enqueue(item); // wait for the item to fire diff --git a/utils-test/src/main/resources/keystore_san.txt b/utils-test/src/main/resources/keystore_san.txt new file mode 100644 index 00000000..38428ea0 --- /dev/null +++ b/utils-test/src/main/resources/keystore_san.txt @@ -0,0 +1,15 @@ +DNS:policy +DNS:drools +DNS:drools.onap +DNS:policy-apex-pdp +DNS:policy-apex-pdp.onap +DNS:policy-api +DNS:policy-api.onap +DNS:policy-distribution +DNS:policy-distribution.onap +DNS:policy-pap +DNS:policy-pap.onap +DNS:policy-xacml-pdp +DNS:policy-xacml-pdp.onap +DNS:policy.api.simpledemo.onap.org +DNS:policy-sim diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonSerializerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonSerializerTest.java index 82f5ede0..aa701435 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonSerializerTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonSerializerTest.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. @@ -26,12 +27,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.StringReader; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GsonSerializerTest { +class GsonSerializerTest { @Test - public void testReadJsonReader() { + void testReadJsonReader() { JsonReader rdr = new JsonReader(new StringReader("10")); GsonSerializer<Object> ser = new GsonSerializer<Object>() { diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java index 466041e3..d85653d9 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsBuilderTest.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,7 +21,7 @@ package org.onap.policy.common.utils.gson; -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.when; @@ -30,20 +31,20 @@ import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class GsonTestUtilsBuilderTest { +class GsonTestUtilsBuilderTest { private GsonTestUtils utils; - @Before + @BeforeEach public void setUp() { utils = new MyBuilder().build(); } @Test - public void testBuilderAddMock() { + void testBuilderAddMock() { PreMock pre = mock(PreMock.class); when(pre.getId()).thenReturn(2000); diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java index f16764c9..d355823c 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/gson/GsonTestUtilsTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * 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. @@ -22,9 +23,9 @@ package org.onap.policy.common.utils.gson; import static org.assertj.core.api.Assertions.assertThatCode; 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.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -34,27 +35,29 @@ import com.google.gson.JsonParseException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import org.apache.commons.jexl3.JexlException; -import org.junit.Before; -import org.junit.Test; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class GsonTestUtilsTest { +class GsonTestUtilsTest { private static final String HELLO = "hello"; private GsonTestUtils utils; - @Before + @BeforeEach public void setUp() { utils = new GsonTestUtils(); } @Test - public void testGetGson() { + void testGetGson() { assertNotNull(utils.getGson()); } @Test - public void testGsonRoundTrip() { + void testGsonRoundTrip() { Data data = new Data(); data.setId(500); @@ -68,7 +71,7 @@ public class GsonTestUtilsTest { } @Test - public void testCompareGsonObjectClass_testCompareGsonObjectFile() { + void testCompareGsonObjectClass_testCompareGsonObjectFile() { Data data = new Data(); data.setId(500); data.setText(HELLO); @@ -95,7 +98,7 @@ public class GsonTestUtilsTest { } @Test - public void testCompareGsonObjectString() { + void testCompareGsonObjectString() { Data data = new Data(); data.setId(600); data.setText(HELLO); @@ -105,7 +108,7 @@ public class GsonTestUtilsTest { } @Test - public void testCompareGsonObjectJsonElement() { + void testCompareGsonObjectJsonElement() { Data data = new Data(); data.setId(650); data.setText(HELLO); @@ -122,7 +125,7 @@ public class GsonTestUtilsTest { } @Test - public void testApplyScripts() { + void testApplyScripts() { Data data = new Data(); data.setId(700); data.setText(HELLO); @@ -137,15 +140,11 @@ public class GsonTestUtilsTest { data.setText(null); result = utils.applyScripts("use ${obj.text} this", data); assertEquals("use null this", result); - - assertThatThrownBy(() -> utils.applyScripts("use ${obj.text} this", null)) - .isInstanceOf(JsonParseException.class) - .hasCauseInstanceOf(JexlException.class) - .hasMessage("cannot expand element: ${obj.text}"); + assertEquals("use null this", utils.applyScripts("use ${obj.text} this", null)); } @Test - public void testReorderJsonObject() { + void testReorderJsonObject() { // insert properties in a non-alphabetical order JsonObject inner = new JsonObject(); inner.addProperty("objBint", 100); @@ -169,7 +168,7 @@ public class GsonTestUtilsTest { } @Test - public void testReorderJsonArray() { + void testReorderJsonArray() { // insert properties in a non-alphabetical order JsonObject inner = new JsonObject(); inner.add("objCNull", JsonNull.INSTANCE); @@ -186,7 +185,7 @@ public class GsonTestUtilsTest { } @Test - public void testReorderJsonElement() { + void testReorderJsonElement() { // null element JsonElement jsonEl = null; assertNull(utils.reorder(jsonEl)); @@ -225,29 +224,12 @@ public class GsonTestUtilsTest { assertEquals("[300,{'objE':true,'objEStr':'obj-e-string'},false]".replace('\'', '"'), jsonEl.toString()); } + @Setter + @Getter + @ToString public static class Data { private int id; private String text; - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - @Override - public String toString() { - return "Data [id=" + id + ", text=" + text + "]"; - } } } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java index b5699fa2..602df359 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java @@ -3,6 +3,7 @@ * ONAP Policy Engine - Common Modules * ================================================================================ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. + * Modificaitons 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. @@ -21,9 +22,9 @@ package org.onap.policy.common.utils.io; 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.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -36,14 +37,14 @@ import java.io.Serializable; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.io.Serializer.Factory; -import org.powermock.reflect.Whitebox; +import org.springframework.test.util.ReflectionTestUtils; -public class SerializerTest { +class SerializerTest { private static final String FACTORY = "factory"; /** @@ -51,28 +52,28 @@ public class SerializerTest { */ private static Factory saveFactory; - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { - saveFactory = Whitebox.getInternalState(Serializer.class, FACTORY); + saveFactory = (Factory) ReflectionTestUtils.getField(Serializer.class, FACTORY); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { - Whitebox.setInternalState(Serializer.class, FACTORY, saveFactory); + ReflectionTestUtils.setField(Serializer.class, FACTORY, saveFactory); } - @Before + @BeforeEach public void setUp() { setFactory(saveFactory); } @Test - public void testFactory() { + void testFactory() { assertNotNull(saveFactory); } @Test - public void testSerialize() throws Exception { + void testSerialize() throws Exception { MyObject obj1 = new MyObject(3); byte[] data = Serializer.serialize(obj1); assertTrue(data.length > 0); @@ -84,13 +85,14 @@ public class SerializerTest { assertEquals(obj1.value, obj2.value); } - @Test(expected = java.io.NotSerializableException.class) - public void testSerialize_Ex() throws Exception { - Serializer.serialize(new NotSerializable()); + @Test + void testSerialize_Ex() { + assertThatThrownBy(() -> Serializer.serialize(new NotSerializable())) + .isInstanceOf(java.io.NotSerializableException.class); } @Test - public void testSerialize_ArrayCloseEx() { + void testSerialize_ArrayCloseEx() { IOException ex = new IOException("testSerialize_ArrayCloseEx"); /* @@ -124,7 +126,7 @@ public class SerializerTest { } @Test - public void testSerialize_ObjectWriteEx() { + void testSerialize_ObjectWriteEx() { IOException ex = new IOException("testSerialize_ObjectWriteEx"); /* @@ -141,7 +143,7 @@ public class SerializerTest { } @Test - public void testSerialize_ObjectCloseEx() throws Exception { + void testSerialize_ObjectCloseEx() throws Exception { IOException ex = new IOException("testSerialize_ObjectCloseEx"); ObjectOutputStream oos = mock(ObjectOutputStream.class); doThrow(ex).when(oos).close(); @@ -167,7 +169,7 @@ public class SerializerTest { } @Test - public void testSerialize_BothCloseEx() throws Exception { + void testSerialize_BothCloseEx() throws Exception { IOException ex = new IOException("testSerialize_BothCloseEx"); IOException ex2 = new IOException("testSerialize_BothCloseEx_2"); ObjectOutputStream oos = mock(ObjectOutputStream.class); @@ -215,14 +217,14 @@ public class SerializerTest { } @Test - public void testDeserialize() throws Exception { + void testDeserialize() throws Exception { MyObject obj1 = new MyObject(3); MyObject obj2 = Serializer.roundTrip(obj1); assertEquals(obj1.value, obj2.value); } @Test - public void testDeserialize_ArrayCloseEx() throws Exception { + void testDeserialize_ArrayCloseEx() { IOException ex = new IOException("testSerialize_ObjectWriteEx"); /* @@ -251,7 +253,7 @@ public class SerializerTest { } @Test - public void testDeserialize_ObjectReadEx() throws Exception { + void testDeserialize_ObjectReadEx() { IOException ex = new IOException("testDeserialize_ObjectReadEx"); /* @@ -268,7 +270,7 @@ public class SerializerTest { } @Test - public void testDeserialize_ObjectRead_ClassEx() throws Exception { + void testDeserialize_ObjectRead_ClassEx() throws Exception { MyObject obj1 = new MyObject(200); // must use binary character set @@ -301,7 +303,7 @@ public class SerializerTest { } @Test - public void testDeserialize_ObjectCloseEx() throws Exception { + void testDeserialize_ObjectCloseEx() { IOException ex = new IOException("testDeserialize_ObjectCloseEx"); /* @@ -324,7 +326,7 @@ public class SerializerTest { } @Test - public void testDeserialize_BothCloseEx() throws Exception { + void testDeserialize_BothCloseEx() { IOException ex = new IOException("testDeserialize_BothCloseEx"); IOException ex2 = new IOException("testDeserialize_BothCloseEx_2"); @@ -358,16 +360,17 @@ public class SerializerTest { } @Test - public void testRoundTrip() throws Exception { - MyObject obj1 = new MyObject(3); + void testRoundTrip() throws Exception { + MyObject obj1 = new MyObject(4); MyObject obj2 = Serializer.roundTrip(obj1); assertEquals(obj1.value, obj2.value); } - @Test(expected = java.io.NotSerializableException.class) - public void testRoundTrip_Ex() throws Exception { - Serializer.roundTrip(new NotSerializable()); + @Test + void testRoundTrip_Ex() { + assertThatThrownBy(() -> Serializer.roundTrip(new NotSerializable())) + .isInstanceOf(java.io.NotSerializableException.class); } /** @@ -376,7 +379,7 @@ public class SerializerTest { * @param factory new factory to be set */ private void setFactory(Factory factory) { - Whitebox.setInternalState(Serializer.class, FACTORY, factory); + ReflectionTestUtils.setField(Serializer.class, FACTORY, factory); } /** diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java new file mode 100644 index 00000000..108dedba --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java @@ -0,0 +1,152 @@ +/*- + * ============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.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class SelfSignedKeyStoreTest { + private static final String USER_DIR_PROP = "user.dir"; + + private static String saveUserDir; + private static String defaultName; + private static File defaultKeystore; + + + /** + * Saves the user.dir property and initializes static fields. + */ + @BeforeAll + public static void setUpBeforeClass() { + saveUserDir = System.getProperty(USER_DIR_PROP); + defaultName = saveUserDir + "/" + SelfSignedKeyStore.RELATIVE_PATH; + defaultKeystore = new File(defaultName); + } + + @BeforeEach + public void setUp() { + System.setProperty(USER_DIR_PROP, saveUserDir); + delete(defaultKeystore); + } + + @Test + void testSelfSignedKeyStore() throws Exception { + SelfSignedKeyStore ks = new SelfSignedKeyStore(); + + assertThat(ks.getKeystoreName()).isEqualTo(defaultName); + assertThat(defaultKeystore).exists(); + } + + @Test + void testSelfSignedKeyStoreString() throws IOException { + String relName = "target/my-keystore"; + String altName = saveUserDir + "/" + relName; + File altFile = new File(altName); + + delete(altFile); + + SelfSignedKeyStore ks = new SelfSignedKeyStore(relName); + + assertThat(ks.getKeystoreName()).isEqualTo(altName); + assertThat(altFile).exists(); + } + + /** + * Tests the constructor, when the keystore already exists. + */ + @Test + void testSelfSignedKeyStoreStringExists() throws Exception { + new SelfSignedKeyStore(); + assertThat(defaultKeystore).exists(); + + // change the timestamp on the keystore so it's a little old, but not too old + defaultKeystore.setLastModified( + System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(10, TimeUnit.MINUTES)); + long tcurrent = defaultKeystore.lastModified(); + + // this should not recreate the keystore, thus the timestamp should be unchanged + new SelfSignedKeyStore(); + assertThat(defaultKeystore.lastModified()).isEqualTo(tcurrent); + + // change the timestamp on the keystore so it's too old + defaultKeystore.setLastModified( + System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(1000, TimeUnit.HOURS)); + tcurrent = defaultKeystore.lastModified(); + + // this should recreate the keystore + new SelfSignedKeyStore(); + assertThat(defaultKeystore.lastModified()).isGreaterThan(tcurrent); + } + + /** + * Tests the constructor, when the SAN file is not found. + */ + @Test + void testSelfSignedKeyStoreStringNoSanFile() { + assertThatThrownBy(() -> new SelfSignedKeyStore() { + @Override + protected String getKeystoreSanName() { + return "unknown/san/file.txt"; + } + }).isInstanceOf(FileNotFoundException.class).hasMessageContaining("file.txt"); + } + + /** + * Tests the constructor, when write fails. + */ + @Test + void testSelfSignedKeyStoreStringWriteFailure() { + assertThatThrownBy(() -> new SelfSignedKeyStore("target/unknown/path/to/keystore")) + .isInstanceOf(IOException.class); + } + + @Test + void testGetKeystoreName() throws Exception { + String relpath = SelfSignedKeyStore.RELATIVE_PATH; + + // append the first part of the relative path to user.dir + System.setProperty(USER_DIR_PROP, saveUserDir + "/" + relpath.substring(0, relpath.indexOf('/'))); + + // create a keystore using the remaining components of the relative path + SelfSignedKeyStore ks = new SelfSignedKeyStore(relpath.substring(relpath.indexOf('/') + 1)); + + assertThat(ks.getKeystoreName()).isEqualTo(defaultName); + assertThat(defaultKeystore).exists(); + + // try again using the original relative path - should fail, as it's now deeper + assertThatThrownBy(() -> new SelfSignedKeyStore(relpath)).isInstanceOf(IOException.class); + } + + private static void delete(File file) { + if (file.exists()) { + assertThat(file.delete()).isTrue(); + } + } +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java index 8a60a5d2..95bba10d 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/ConstructionErrorTest.java @@ -3,6 +3,7 @@ * Common Utils-Test * ================================================================================ * Copyright (C) 2018-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.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ConstructionErrorTest extends ErrorsTester { +class ConstructionErrorTest extends ErrorsTester { @Test - public void test() { + void test() { assertEquals(4, testAllError(ConstructionError.class)); } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/ErrorsTesterTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/ErrorsTesterTest.java index 2009e297..b6d91f07 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/ErrorsTesterTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/ErrorsTesterTest.java @@ -3,6 +3,7 @@ * Common Utils-Test * ================================================================================ * 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.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ErrorsTesterTest { +class ErrorsTesterTest { @Test - public void test() { + void test() { assertEquals(2, new ErrorsTester().testAllError(SimpleError.class)); assertEquals(5, new ErrorsTester().testAllError(StaticError.class)); } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/ExceptionsTesterTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/ExceptionsTesterTest.java index 89ff3ba1..81a85035 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/ExceptionsTesterTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/ExceptionsTesterTest.java @@ -3,6 +3,7 @@ * Common Utils-Test * ================================================================================ * 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,21 +21,24 @@ package org.onap.policy.common.utils.test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ExceptionsTesterTest { +class ExceptionsTesterTest { @Test - public void test() { + void test() { assertEquals(2, new ExceptionsTester().test(SimpleException.class)); assertEquals(8, new ExceptionsTester().test(StaticException.class)); } - @Test(expected = AssertionError.class) - public void testNoConstructorsException() { - new ExceptionsTester().test(NoConstructorsException.class); + @Test + void testNoConstructorsException() { + ExceptionsTester tester = new ExceptionsTester(); + assertThatThrownBy(() -> tester.test(NoConstructorsException.class)) + .isInstanceOf(AssertionError.class); } /** diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java index 3cb53d81..7775ef35 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/ThrowablesTesterTest.java @@ -3,6 +3,7 @@ * Common Utils-Test * ================================================================================ * Copyright (C) 2018-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,58 +21,73 @@ package org.onap.policy.common.utils.test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ThrowablesTesterTest { +class ThrowablesTesterTest { @Test - public void test() { + void test() { assertEquals(2, new ThrowablesTester().testAllThrowable(SimpleThrowable.class)); assertEquals(5, new ThrowablesTester().testAllThrowable(StaticThrowable.class)); } @Test - public void testNoConstructorsThrowable() { + void testNoConstructorsThrowable() { // this will not throw an error, but it should return 0, as there are // no matching constructors assertEquals(0, new ThrowablesTester().testAllThrowable(NoConstructorsThrowable.class)); } - @Test(expected = AssertionError.class) - public void testIgnoreMessageThrowable() { - new ThrowablesTester().testAllThrowable(IgnoreMessageThrowable.class); + @Test + void testIgnoreMessageThrowable() { + ThrowablesTester tester = new ThrowablesTester(); + assertThatThrownBy(() -> tester.testAllThrowable(IgnoreMessageThrowable.class)) + .isInstanceOf(AssertionError.class); } - @Test(expected = AssertionError.class) - public void testIgnoreCauseThrowable() { - new ThrowablesTester().testAllThrowable(IgnoreCauseThrowable.class); + @Test + void testIgnoreCauseThrowable() { + ThrowablesTester tester = new ThrowablesTester(); + assertThatThrownBy(() -> tester.testAllThrowable(IgnoreCauseThrowable.class)) + .isInstanceOf(AssertionError.class); } - @Test(expected = AssertionError.class) - public void testAlwaysSuppressThrowable() { - new ThrowablesTester().testAllThrowable(AlwaysSuppressThrowable.class); + @Test + void testAlwaysSuppressThrowable() { + ThrowablesTester tester = new ThrowablesTester(); + assertThatThrownBy(() -> tester.testAllThrowable(AlwaysSuppressThrowable.class)) + .isInstanceOf(AssertionError.class); } - @Test(expected = AssertionError.class) - public void testNeverSuppressThrowable() { - new ThrowablesTester().testAllThrowable(NeverSuppressThrowable.class); + @Test + void testNeverSuppressThrowable() { + ThrowablesTester tester = new ThrowablesTester(); + assertThatThrownBy(() -> tester.testAllThrowable(NeverSuppressThrowable.class)) + .isInstanceOf(AssertionError.class); } - @Test(expected = AssertionError.class) - public void testAlwaysWritableThrowable() { - new ThrowablesTester().testAllThrowable(AlwaysWritableThrowable.class); + @Test + void testAlwaysWritableThrowable() { + ThrowablesTester tester = new ThrowablesTester(); + assertThatThrownBy(() -> tester.testAllThrowable(AlwaysWritableThrowable.class)) + .isInstanceOf(AssertionError.class); } - @Test(expected = AssertionError.class) - public void testNeverWritableThrowable() { - new ThrowablesTester().testAllThrowable(NeverWritableThrowable.class); + @Test + void testNeverWritableThrowable() { + ThrowablesTester tester = new ThrowablesTester(); + assertThatThrownBy(() -> tester.testAllThrowable(NeverWritableThrowable.class)) + .isInstanceOf(AssertionError.class); } - @Test(expected = ConstructionError.class) - public void testThrowInstantiationException() { - new ThrowablesTester().testAllThrowable(ThrowInstantiationThrowable.class); + @Test + void testThrowInstantiationException() { + ThrowablesTester tester = new ThrowablesTester(); + assertThatThrownBy(() -> tester.testAllThrowable(ThrowInstantiationThrowable.class)) + .isInstanceOf(AssertionError.class); } /** diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java index 4c2237fc..9367209c 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/test/log/logback/ExtractAppenderTest.java @@ -3,6 +3,7 @@ * Common Utils-Test * ================================================================================ * 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,8 +21,8 @@ package org.onap.policy.common.utils.test.log.logback; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; @@ -31,13 +32,13 @@ import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -public class ExtractAppenderTest { +class ExtractAppenderTest { private static final String ABC_DIGIT = "abc[0-9]"; private static final String ABC_DIGIT1 = "abc[1-9]"; private static final String DEF_DIGIT = "def[0-9]"; @@ -58,13 +59,13 @@ public class ExtractAppenderTest { private List<Thread> threads; - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { logger = (Logger) LoggerFactory.getLogger(ExtractAppenderTest.class); logger.setLevel(Level.INFO); } - @Before + @BeforeEach public void setUp() { threads = new LinkedList<>(); } @@ -72,7 +73,7 @@ public class ExtractAppenderTest { /** * Tear down all appenders and threads. */ - @After + @AfterEach public void tearDown() throws Exception { logger.detachAndStopAllAppenders(); @@ -83,7 +84,7 @@ public class ExtractAppenderTest { } @Test - public void testExtractAppender() { + void testExtractAppender() { AtomicInteger count = new AtomicInteger(0); ExtractAppender appender = new ExtractAppender() { @@ -117,7 +118,7 @@ public class ExtractAppenderTest { } @Test - public void testExtractAppenderStringArray() { + void testExtractAppenderStringArray() { AtomicInteger count = new AtomicInteger(0); ExtractAppender appender = new ExtractAppender(ABC_DIGIT, DEF_DIGIT) { @@ -156,7 +157,7 @@ public class ExtractAppenderTest { } @Test - public void testExtractAppenderQueueStringArray() { + void testExtractAppenderQueueStringArray() { // no. of matches allowed in the list int nallowed = 3; @@ -204,7 +205,7 @@ public class ExtractAppenderTest { } @Test - public void testAppendILoggingEvent_NoPatterns() { + void testAppendILoggingEvent_NoPatterns() { ExtractAppender appender = makeAppender(); logger.info(HELLO); @@ -214,7 +215,7 @@ public class ExtractAppenderTest { } @Test - public void testAppendILoggingEvent_Formatted() { + void testAppendILoggingEvent_Formatted() { ExtractAppender appender = makeAppender(); logger.info("hello {} world{}", "there", "!"); @@ -223,7 +224,7 @@ public class ExtractAppenderTest { } @Test - public void testAppendILoggingEvent_MatchFirstPattern() { + void testAppendILoggingEvent_MatchFirstPattern() { ExtractAppender appender = makeAppender(ABC_DIGIT, DEF_DIGIT); logger.info("hello abc1"); @@ -233,7 +234,7 @@ public class ExtractAppenderTest { } @Test - public void testAppendILoggingEvent_MatchLastPattern() { + void testAppendILoggingEvent_MatchLastPattern() { ExtractAppender appender = makeAppender(ABC_DIGIT, DEF_DIGIT); logger.info("hello def1"); @@ -243,7 +244,7 @@ public class ExtractAppenderTest { } @Test - public void testAppendILoggingEvent_Group1() { + void testAppendILoggingEvent_Group1() { ExtractAppender appender = makeAppender("hello (abc)|(xyz)", DEF_DIGIT); logger.info("hello abc, world!"); @@ -253,7 +254,7 @@ public class ExtractAppenderTest { } @Test - public void testAppendILoggingEvent_Group3() { + void testAppendILoggingEvent_Group3() { ExtractAppender appender = makeAppender("hello (abc)|(pdq)|(xyz)", DEF_DIGIT); logger.info("say hello xyz, world!"); @@ -263,7 +264,7 @@ public class ExtractAppenderTest { } @Test - public void testAppendILoggingEvent_NoGroup() { + void testAppendILoggingEvent_NoGroup() { ExtractAppender appender = makeAppender(HELLO_ABC); logger.info("say hello abc, world!"); @@ -273,7 +274,7 @@ public class ExtractAppenderTest { } @Test - public void testGetExtracted() { + void testGetExtracted() { ExtractAppender appender = makeAppender(ABC_DIGIT1); logger.info(HELLO_ABC1_WORLD); @@ -289,7 +290,7 @@ public class ExtractAppenderTest { } @Test - public void testClearExtractions() { + void testClearExtractions() { final ExtractAppender appender = makeAppender(ABC_DIGIT1); logger.info(HELLO_ABC1_WORLD); @@ -312,7 +313,7 @@ public class ExtractAppenderTest { } @Test - public void testSetPattern() { + void testSetPattern() { final ExtractAppender appender = makeAppender(ABC_DIGIT1); logger.info(HELLO_ABC1_WORLD); @@ -334,7 +335,7 @@ public class ExtractAppenderTest { * Launches threads doing everything in parallel to ensure nothing crashes. */ @Test - public void test_MultiThreaded() throws Exception { + void test_MultiThreaded() throws Exception { // when to stop long tend = System.currentTimeMillis() + 250; diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PeriodicItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PeriodicItemTest.java index 3e64edf3..14223b99 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PeriodicItemTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PeriodicItemTest.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,15 +22,15 @@ package org.onap.policy.common.utils.time; 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.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.assertSame; +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 PeriodicItemTest { +class PeriodicItemTest { private static final long DELAY_MS = 100L; private static final long PERIOD_MS = 200L; private static final Object ASSOCIATE = new Object(); @@ -41,7 +42,7 @@ public class PeriodicItemTest { /** * Sets up objects, including {@link #item}. */ - @Before + @BeforeEach public void setUp() { currentTime = new TestTime(); count = 0; @@ -49,18 +50,18 @@ public class PeriodicItemTest { } @Test - public void testBumpNextTime() { + void testBumpNextTime() { assertTrue(item.bumpNextTime()); assertEquals(currentTime.getMillis() + PERIOD_MS, item.getNextMs()); } @Test - public void testToString() { + void testToString() { assertNotNull(item.toString()); } @Test - public void testPeriodicItem() { + void testPeriodicItem() { assertSame(ASSOCIATE, item.getAssociate()); assertNotNull(item.getAction()); assertEquals(currentTime.getMillis() + DELAY_MS, item.getNextMs()); diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java index 0046f791..d3c00da5 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoExecutorTest.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,25 +21,25 @@ package org.onap.policy.common.utils.time; -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 org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class PseudoExecutorTest { +class PseudoExecutorTest { private int invoked; private PseudoExecutor executor; - @Before + @BeforeEach public void setUp() { invoked = 0; executor = new PseudoExecutor(); } @Test - public void test() { + void test() { assertEquals(0, executor.getQueueLength()); assertEquals(0, executor.getTasks().size()); assertTrue(executor.runAll(0)); diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java index 745e989f..5969f1fb 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.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,10 +22,10 @@ package org.onap.policy.common.utils.time; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.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.assertTrue; import java.util.Collections; import java.util.List; @@ -32,10 +33,10 @@ import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class PseudoScheduledExecutorServiceTest { +class PseudoScheduledExecutorServiceTest { private static final long DELAY_MS = 100L; private static final long PERIOD_MS = 200L; private static final List<Callable<Object>> EMPTY_CALLABLES = Collections.emptyList(); @@ -48,7 +49,7 @@ public class PseudoScheduledExecutorServiceTest { /** * Sets up objects, including {@link #svc}. */ - @Before + @BeforeEach public void setUp() { ran = 0; called = 0; @@ -57,7 +58,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testShutdown() { + void testShutdown() { // submit some tasks svc.submit(new MyRun()); svc.schedule(new MyRun(), 1L, TimeUnit.SECONDS); @@ -70,7 +71,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testShutdownNow() { + void testShutdownNow() { // submit some tasks svc.submit(new MyRun()); svc.schedule(new MyRun(), 1L, TimeUnit.SECONDS); @@ -83,7 +84,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testIsShutdown_testIsTerminated() { + void testIsShutdown_testIsTerminated() { assertFalse(svc.isShutdown()); assertFalse(svc.isTerminated()); @@ -93,7 +94,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testAwaitTermination() throws InterruptedException { + void testAwaitTermination() throws InterruptedException { assertFalse(svc.awaitTermination(1L, TimeUnit.SECONDS)); svc.shutdown(); @@ -101,7 +102,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testSubmitCallableOfT() throws Exception { + void testSubmitCallableOfT() throws Exception { Future<Integer> future = svc.submit(new MyCallable()); currentTime.runOneTask(0); @@ -113,7 +114,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testSubmitRunnableT() throws Exception { + void testSubmitRunnableT() throws Exception { Future<Integer> future = svc.submit(new MyRun(), 2); currentTime.runOneTask(0); @@ -125,7 +126,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testSubmitRunnable() throws Exception { + void testSubmitRunnable() throws Exception { assertNotNull(svc.submit(new MyRun())); currentTime.runOneTask(0); @@ -136,31 +137,31 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testInvokeAllCollectionOfQextendsCallableOfT() { + void testInvokeAllCollectionOfQextendsCallableOfT() { assertThatThrownBy(() -> svc.invokeAll(EMPTY_CALLABLES)) .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testInvokeAllCollectionOfQextendsCallableOfTLongTimeUnit() { + void testInvokeAllCollectionOfQextendsCallableOfTLongTimeUnit() { assertThatThrownBy(() -> svc.invokeAll(EMPTY_CALLABLES, 1, TimeUnit.MILLISECONDS)) .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testInvokeAnyCollectionOfQextendsCallableOfT() { + void testInvokeAnyCollectionOfQextendsCallableOfT() { assertThatThrownBy(() -> svc.invokeAny(EMPTY_CALLABLES)) .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testInvokeAnyCollectionOfQextendsCallableOfTLongTimeUnit() { + void testInvokeAnyCollectionOfQextendsCallableOfTLongTimeUnit() { assertThatThrownBy(() -> svc.invokeAny(EMPTY_CALLABLES, 1, TimeUnit.MILLISECONDS)) .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testExecute() throws InterruptedException { + void testExecute() throws InterruptedException { svc.execute(new MyRun()); currentTime.runOneTask(0); @@ -171,7 +172,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testScheduleRunnableLongTimeUnit() throws InterruptedException { + void testScheduleRunnableLongTimeUnit() throws InterruptedException { assertNotNull(svc.schedule(new MyRun(), DELAY_MS, TimeUnit.MILLISECONDS)); assertEquals(DELAY_MS, oneTaskElapsedTime()); @@ -182,7 +183,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testScheduleCallableOfVLongTimeUnit() throws Exception { + void testScheduleCallableOfVLongTimeUnit() throws Exception { ScheduledFuture<Integer> future = svc.schedule(new MyCallable(), DELAY_MS, TimeUnit.MILLISECONDS); assertEquals(DELAY_MS, oneTaskElapsedTime()); @@ -194,7 +195,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testScheduleAtFixedRate() throws InterruptedException { + void testScheduleAtFixedRate() throws InterruptedException { final ScheduledFuture<?> future = svc.scheduleAtFixedRate(new MyRun(), DELAY_MS, PERIOD_MS, TimeUnit.MILLISECONDS); @@ -218,7 +219,7 @@ public class PseudoScheduledExecutorServiceTest { } @Test - public void testScheduleWithFixedDelay() throws InterruptedException { + void testScheduleWithFixedDelay() throws InterruptedException { final ScheduledFuture<?> future = svc.scheduleWithFixedDelay(new MyRun(), DELAY_MS, PERIOD_MS, TimeUnit.MILLISECONDS); diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java index e23bbd29..31156af9 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * 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,21 +21,24 @@ package org.onap.policy.common.utils.time; -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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; -public class PseudoScheduledFutureTest { +@ExtendWith(MockitoExtension.class) +class PseudoScheduledFutureTest { private static final long DELAY_MS = 1000L; private int count; @@ -47,11 +51,9 @@ public class PseudoScheduledFutureTest { /** * Sets up objects, including {@link #future}. */ - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); - - when(work.getDelay()).thenReturn(DELAY_MS); + lenient().when(work.getDelay()).thenReturn(DELAY_MS); count = 0; future = new PseudoScheduledFuture<>(() -> ++count, true); @@ -59,7 +61,7 @@ public class PseudoScheduledFutureTest { } @Test - public void testRun() { + void testRun() { // verify with a periodic task - should execute twice count = 0; future.run(); @@ -75,7 +77,7 @@ public class PseudoScheduledFutureTest { } @Test - public void testPseudoScheduledFutureRunnableTBoolean() throws Exception { + void testPseudoScheduledFutureRunnableTBoolean() throws Exception { final Integer result = 100; future = new PseudoScheduledFuture<>(() -> ++count, result, true); assertTrue(future.isPeriodic()); @@ -94,7 +96,7 @@ public class PseudoScheduledFutureTest { } @Test - public void testPseudoScheduledFutureCallableOfTBoolean() throws Exception { + void testPseudoScheduledFutureCallableOfTBoolean() throws Exception { assertTrue(future.isPeriodic()); future.run(); future.run(); @@ -111,13 +113,13 @@ public class PseudoScheduledFutureTest { } @Test - public void testGetDelay() { + void testGetDelay() { assertEquals(DELAY_MS, future.getDelay(TimeUnit.MILLISECONDS)); assertEquals(TimeUnit.MILLISECONDS.toSeconds(DELAY_MS), future.getDelay(TimeUnit.SECONDS)); } @Test - public void testCompareTo() { + void testCompareTo() { Delayed delayed = mock(Delayed.class); when(delayed.getDelay(TimeUnit.MILLISECONDS)).thenReturn(DELAY_MS + 1); @@ -125,18 +127,18 @@ public class PseudoScheduledFutureTest { } @Test - public void testIsPeriodic() { + void testIsPeriodic() { assertTrue(future.isPeriodic()); assertFalse(new PseudoScheduledFuture<>(() -> ++count, false).isPeriodic()); } @Test - public void testGetWorkItem() { + void testGetWorkItem() { assertSame(work, future.getWorkItem()); } @Test - public void testSetWorkItem() { + void testSetWorkItem() { work = mock(WorkItem.class); future.setWorkItem(work); assertSame(work, future.getWorkItem()); diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java index d7316c1f..69e54524 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.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.time; 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 java.util.Date; import java.util.TimerTask; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class PseudoTimerTest { +class PseudoTimerTest { private static final long DELAY_MS = 1000L; private static final long PERIOD_MS = 2000L; @@ -41,7 +42,7 @@ public class PseudoTimerTest { /** * Sets up objects, including {@link #timer}. */ - @Before + @BeforeEach public void setUp() { count = 0; currentTime = new TestTimeMulti(); @@ -49,7 +50,7 @@ public class PseudoTimerTest { } @Test - public void testCancel() { + void testCancel() { // schedule two tasks timer.scheduleAtFixedRate(new MyTask(), DELAY_MS, PERIOD_MS); timer.schedule(new MyTask(), DELAY_MS); @@ -64,13 +65,13 @@ public class PseudoTimerTest { } @Test - public void testPurge() { + void testPurge() { assertEquals(0, timer.purge()); assertEquals(0, timer.purge()); } @Test - public void testScheduleTimerTaskLong() throws InterruptedException { + void testScheduleTimerTaskLong() throws InterruptedException { timer.schedule(new MyTask(), DELAY_MS); assertFalse(currentTime.isEmpty()); @@ -82,14 +83,14 @@ public class PseudoTimerTest { } @Test - public void testScheduleTimerTaskDate() { + void testScheduleTimerTaskDate() { MyTask task = new MyTask(); Date curdate = new Date(); assertThatThrownBy(() -> timer.schedule(task, curdate)).isInstanceOf(UnsupportedOperationException.class); } @Test - public void testScheduleTimerTaskLongLong() throws InterruptedException { + void testScheduleTimerTaskLongLong() throws InterruptedException { timer.schedule(new MyTask(), DELAY_MS, PERIOD_MS); assertFalse(currentTime.isEmpty()); @@ -105,14 +106,14 @@ public class PseudoTimerTest { } @Test - public void testScheduleTimerTaskDateLong() { + void testScheduleTimerTaskDateLong() { MyTask task = new MyTask(); Date curdate = new Date(); assertThatThrownBy(() -> timer.schedule(task, curdate, 1L)).isInstanceOf(UnsupportedOperationException.class); } @Test - public void testScheduleAtFixedRateTimerTaskLongLong() throws InterruptedException { + void testScheduleAtFixedRateTimerTaskLongLong() throws InterruptedException { timer.scheduleAtFixedRate(new MyTask(), DELAY_MS, PERIOD_MS); assertFalse(currentTime.isEmpty()); @@ -128,7 +129,7 @@ public class PseudoTimerTest { } @Test - public void testScheduleAtFixedRateTimerTaskDateLong() { + void testScheduleAtFixedRateTimerTaskDateLong() { MyTask task = new MyTask(); Date curdate = new Date(); assertThatThrownBy(() -> timer.scheduleAtFixedRate(task, curdate, 1L)) diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/RunnableItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/RunnableItemTest.java index e7bbd018..e35c58fa 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/RunnableItemTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/RunnableItemTest.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,17 +21,17 @@ package org.onap.policy.common.utils.time; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.FutureTask; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class RunnableItemTest { +class RunnableItemTest { private static final long DELAY_MS = 100L; private static final Object ASSOCIATE = new Object(); @@ -41,7 +42,7 @@ public class RunnableItemTest { /** * Sets up objects, including {@link #item}. */ - @Before + @BeforeEach public void setUp() { currentTime = new TestTime(); count = 0; @@ -49,7 +50,7 @@ public class RunnableItemTest { } @Test - public void testWasCancelled() { + void testWasCancelled() { assertFalse(item.wasCancelled()); FutureTask<Object> future = new FutureTask<>(() -> count++); @@ -61,13 +62,13 @@ public class RunnableItemTest { } @Test - public void testIsAssociatedWith() { + void testIsAssociatedWith() { assertFalse(item.isAssociatedWith(this)); assertTrue(item.isAssociatedWith(ASSOCIATE)); } @Test - public void testFire() { + void testFire() { item.fire(); assertEquals(1, count); @@ -78,7 +79,7 @@ public class RunnableItemTest { } @Test - public void testRunnableItem_testGetAssociate_testGetAction() { + void testRunnableItem_testGetAssociate_testGetAction() { assertSame(ASSOCIATE, item.getAssociate()); assertNotNull(item.getAction()); assertEquals(currentTime.getMillis() + DELAY_MS, item.getNextMs()); @@ -96,7 +97,7 @@ public class RunnableItemTest { } @Test - public void testToString() { + void testToString() { assertNotNull(item.toString()); } } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/SleepItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/SleepItemTest.java index dbd54781..ad8f2fbd 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/SleepItemTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/SleepItemTest.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,17 +21,17 @@ package org.onap.policy.common.utils.time; -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.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SleepItemTest { +class SleepItemTest { private static final int SLEEP_MS = 250; private static final long MAX_WAIT_MS = 5000L; @@ -44,7 +45,7 @@ public class SleepItemTest { /** * Sets up objects, including {@link #item}. */ - @Before + @BeforeEach public void setUp() { currentTime = new TestTime(); started = new CountDownLatch(1); @@ -70,7 +71,7 @@ public class SleepItemTest { } @Test - public void testInterrupt() throws InterruptedException { + void testInterrupt() throws InterruptedException { startThread(); item.interrupt(); @@ -80,7 +81,7 @@ public class SleepItemTest { } @Test - public void testFire_testAwait() throws InterruptedException { + void testFire_testAwait() throws InterruptedException { startThread(); // verify that it hasn't finished yet @@ -95,12 +96,12 @@ public class SleepItemTest { } @Test - public void testSleepItem() { + void testSleepItem() { assertEquals(currentTime.getMillis() + SLEEP_MS, item.getNextMs()); } @Test - public void testToString() { + void testToString() { assertNotNull(item.toString()); } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java index 8b6501a7..1b9728d4 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018-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,11 +23,11 @@ package org.onap.policy.common.utils.time; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.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.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -35,23 +36,23 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class TestTimeMultiTest { +class TestTimeMultiTest { private static final long SHORT_WAIT_MS = 100L; private static final long DELAY_MS = 500L; private static final long MAX_WAIT_MS = 5000L; private TestTimeMulti multi; - @Before + @BeforeEach public void setUp() { multi = new TestTimeMulti(); } @Test - public void testSleep() throws InterruptedException { + void testSleep() throws InterruptedException { // negative sleep time final long tbegin = multi.getMillis(); MyThread thread = new MyThread(-5); @@ -81,17 +82,17 @@ public class TestTimeMultiTest { } @Test - public void testTestTimeMulti() { + void testTestTimeMulti() { assertTrue(multi.getMaxWaitMs() > 0); } @Test - public void testTestTimeMultiLong() { + void testTestTimeMultiLong() { assertEquals(200, new TestTimeMulti(200).getMaxWaitMs()); } @Test - public void testIsEmpty_testQueueLength() throws InterruptedException { + void testIsEmpty_testQueueLength() throws InterruptedException { assertTrue(multi.isEmpty()); // queue up two items @@ -114,7 +115,7 @@ public class TestTimeMultiTest { } @Test - public void testDestroy() throws InterruptedException { + void testDestroy() { // this won't interrupt multi.enqueue(new WorkItem(multi, DELAY_MS)); @@ -143,7 +144,7 @@ public class TestTimeMultiTest { } @Test - public void testRunOneTask() throws InterruptedException { + void testRunOneTask() throws InterruptedException { // nothing in the queue yet assertFalse(multi.runOneTask(0)); @@ -163,7 +164,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitFor() throws InterruptedException { + void testWaitFor() throws InterruptedException { // queue up a couple of items multi.enqueue(new WorkItem(multi, DELAY_MS)); multi.enqueue(new WorkItem(multi, DELAY_MS * 2)); @@ -179,7 +180,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitFor_EmptyQueue() throws InterruptedException { + void testWaitFor_EmptyQueue() throws InterruptedException { multi = new TestTimeMulti(SHORT_WAIT_MS); final long realBegin = System.currentTimeMillis(); @@ -192,7 +193,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitUntilCallable() throws InterruptedException { + void testWaitUntilCallable() { multi.enqueue(new WorkItem(multi, DELAY_MS)); multi.enqueue(new WorkItem(multi, DELAY_MS * 2)); multi.enqueue(new WorkItem(multi, DELAY_MS * 3)); @@ -209,7 +210,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitUntilCallable_InterruptEx() throws InterruptedException { + void testWaitUntilCallable_InterruptEx() throws InterruptedException { multi = new TestTimeMulti(); Callable<Boolean> callable = () -> { @@ -237,7 +238,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitUntilCallable_ConditionThrowsEx() throws InterruptedException { + void testWaitUntilCallable_ConditionThrowsEx() { multi = new TestTimeMulti(); Callable<Boolean> callable = () -> { @@ -252,7 +253,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitUntilCallable_NeverSatisfied() throws InterruptedException { + void testWaitUntilCallable_NeverSatisfied() { multi = new TestTimeMulti(SHORT_WAIT_MS); final long realBegin = System.currentTimeMillis(); @@ -262,7 +263,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitUntilLongTimeUnitCallable() throws InterruptedException { + void testWaitUntilLongTimeUnitCallable() { multi.enqueue(new WorkItem(multi, DELAY_MS)); multi.enqueue(new WorkItem(multi, DELAY_MS * 2)); multi.enqueue(new WorkItem(multi, DELAY_MS * 3)); @@ -279,7 +280,7 @@ public class TestTimeMultiTest { } @Test - public void testWaitUntilLongTimeUnitCallable_PseudoTimeExpires() throws InterruptedException { + void testWaitUntilLongTimeUnitCallable_PseudoTimeExpires() { multi.enqueue(new WorkItem(multi, DELAY_MS)); multi.enqueue(new WorkItem(multi, DELAY_MS * 2)); multi.enqueue(new WorkItem(multi, DELAY_MS * 3)); @@ -291,7 +292,7 @@ public class TestTimeMultiTest { } @Test - public void testRunItem() throws InterruptedException { + void testRunItem() throws InterruptedException { AtomicBoolean fired = new AtomicBoolean(false); multi.enqueue(new MyWorkItem(fired)); @@ -305,7 +306,7 @@ public class TestTimeMultiTest { } @Test - public void testRunItem_Rescheduled() throws InterruptedException { + void testRunItem_Rescheduled() throws InterruptedException { AtomicBoolean fired = new AtomicBoolean(false); multi.enqueue(new MyWorkItem(fired) { @@ -326,7 +327,7 @@ public class TestTimeMultiTest { } @Test - public void testRunItem_Canceled() throws InterruptedException { + void testRunItem_Canceled() throws InterruptedException { AtomicBoolean fired = new AtomicBoolean(false); multi.enqueue(new MyWorkItem(fired) { @@ -354,7 +355,7 @@ public class TestTimeMultiTest { } @Test - public void testEnqueue() throws InterruptedException { + void testEnqueue() throws InterruptedException { CountDownLatch started = new CountDownLatch(1); CountDownLatch finished = new CountDownLatch(1); AtomicReference<InterruptedException> ex = new AtomicReference<>(); @@ -390,7 +391,7 @@ public class TestTimeMultiTest { } @Test - public void testCancelItems() throws InterruptedException { + void testCancelItems() throws InterruptedException { AtomicBoolean fired1 = new AtomicBoolean(); multi.enqueue(new MyWorkItem(fired1)); @@ -420,7 +421,7 @@ public class TestTimeMultiTest { } @Test - public void testPurgeItems() throws InterruptedException { + void testPurgeItems() throws InterruptedException { AtomicBoolean fired = new AtomicBoolean(); // queue up two that are canceled, one that is not diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java index d2cf6783..dbf077c5 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java @@ -3,6 +3,7 @@ * Common Utils-Test * ================================================================================ * Copyright (C) 2018-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,15 +21,15 @@ package org.onap.policy.common.utils.time; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TestTimeTest { +class TestTimeTest { @Test - public void test() throws Exception { + void test() throws Exception { TestTime tm = new TestTime(); TestTime tm2 = new TestTime(); diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java index d2fc8d58..a5683a64 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.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. @@ -22,24 +23,24 @@ package org.onap.policy.common.utils.time; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class WorkItemTest { +class WorkItemTest { private TestTime currentTime; private WorkItem item; - @Before + @BeforeEach public void setUp() { currentTime = new TestTime(); item = new WorkItem(currentTime, 0); } @Test - public void testWorkItem() { + void testWorkItem() { assertThatIllegalArgumentException().isThrownBy(() -> new WorkItem(currentTime, -1)); // should not throw an exception @@ -47,22 +48,22 @@ public class WorkItemTest { } @Test - public void testGetDelay() { + void testGetDelay() { assertEquals(1, item.getDelay()); } @Test - public void testWasCancelled() { + void testWasCancelled() { assertFalse(item.wasCancelled()); } @Test - public void testBumpNextTime() { + void testBumpNextTime() { assertFalse(item.bumpNextTime()); } @Test - public void testBumpNextTimeLong() { + void testBumpNextTimeLong() { assertThatIllegalArgumentException().isThrownBy(() -> item.bumpNextTime(-1)); long cur = currentTime.getMillis(); @@ -76,24 +77,24 @@ public class WorkItemTest { } @Test - public void testInterrupt() { + void testInterrupt() { item.interrupt(); assertFalse(Thread.interrupted()); } @Test - public void testIsAssociatedWith() { + void testIsAssociatedWith() { assertFalse(item.isAssociatedWith(this)); } @Test - public void testFire() { + void testFire() { // ensure no exception is thrown assertThatCode(() -> item.fire()).doesNotThrowAnyException(); } @Test - public void testGetNextMs() { + void testGetNextMs() { assertEquals(currentTime.getMillis() + 1, item.getNextMs()); assertEquals(currentTime.getMillis() + 10, new WorkItem(currentTime, 10).getNextMs()); } |