aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java19
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java4
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java21
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java64
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java8
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java6
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java8
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java6
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java5
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java4
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java65
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java21
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java21
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java47
-rw-r--r--applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java23
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java73
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java11
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java80
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java25
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java40
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java9
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java82
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java26
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java65
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java44
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java117
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java31
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java56
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java27
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java124
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java100
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java78
-rw-r--r--applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java115
-rw-r--r--applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java52
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java25
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java162
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java13
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java73
-rw-r--r--applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java94
-rw-r--r--applications/match/pom.xml7
-rw-r--r--applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java66
-rw-r--r--applications/monitoring/src/test/java/cucumber/RunCucumberTest.java32
-rw-r--r--applications/monitoring/src/test/java/cucumber/Stepdefs.java223
-rw-r--r--applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java60
-rw-r--r--applications/naming/pom.xml7
-rw-r--r--applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java87
-rw-r--r--applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java56
-rw-r--r--applications/optimization/pom.xml7
-rw-r--r--applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java20
-rw-r--r--applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java105
-rw-r--r--applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java21
-rw-r--r--main/pom.xml5
-rw-r--r--main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java5
-rw-r--r--main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java11
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java18
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java9
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java9
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java44
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java66
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java24
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java87
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java35
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java43
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java148
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java79
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java82
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java75
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java9
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java2
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java37
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java45
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java12
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java44
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java15
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java23
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java33
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java23
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java33
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java38
-rw-r--r--main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java37
-rw-r--r--pom.xml19
-rw-r--r--tutorials/tutorial-xacml-application/src/test/java/org/onap/policy/tutorial/tutorial/TutorialApplicationTest.java41
86 files changed, 1757 insertions, 1965 deletions
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java
index 2ccc694a..b8e1aa67 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCaller.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory;
* Methods to access policy-api via REST service calls.
*/
public class PolicyApiCaller {
- private static Logger logger = LoggerFactory.getLogger(PolicyApiCaller.class);
+ private static final Logger logger = LoggerFactory.getLogger(PolicyApiCaller.class);
private static final String POLICY_TYPE_URI = "/policy/api/v1/policytypes/";
private static final String POLICY_TYPE_VERSION_URI = "/versions/";
@@ -60,18 +60,19 @@ public class PolicyApiCaller {
try {
Response resp = httpClient
- .get(POLICY_TYPE_URI + type.getName() + POLICY_TYPE_VERSION_URI + type.getVersion());
+ .get(POLICY_TYPE_URI + type.getName() + POLICY_TYPE_VERSION_URI + type.getVersion());
- switch (resp.getStatus()) {
- case HttpURLConnection.HTTP_OK:
- return resp.readEntity(ToscaServiceTemplate.class);
- case HttpURLConnection.HTTP_NOT_FOUND:
+ return switch (resp.getStatus()) {
+ case HttpURLConnection.HTTP_OK -> resp.readEntity(ToscaServiceTemplate.class);
+ case HttpURLConnection.HTTP_NOT_FOUND -> {
logger.warn("policy-api not found {}", resp);
throw new NotFoundException(type.toString());
- default:
+ }
+ default -> {
logger.warn("policy-api request error {}", resp);
throw new PolicyApiException(type.toString());
- }
+ }
+ };
} catch (RuntimeException e) {
logger.warn("policy-api connection error, client info: {} ", httpClient);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java
index 071a14e1..bf25707f 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +23,11 @@
package org.onap.policy.pdp.xacml.application.common;
+import java.io.Serial;
+
public class ToscaPolicyConversionException extends Exception {
+ @Serial
private static final long serialVersionUID = 1L;
public ToscaPolicyConversionException() {
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java
index 0d23bc1c..9573a1b3 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtils.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -172,8 +173,8 @@ public final class ToscaPolicyTranslatorUtils {
theInt = Integer.parseInt(strInteger);
} catch (NumberFormatException e) {
try {
- Double dblLimit = Double.parseDouble(strInteger);
- theInt = dblLimit.intValue();
+ double dblLimit = Double.parseDouble(strInteger);
+ theInt = (int) dblLimit;
} catch (NumberFormatException e1) {
return null;
}
@@ -190,18 +191,18 @@ public final class ToscaPolicyTranslatorUtils {
* @return returns the given anyOf or new AnyTypeOf if null
*/
public static AnyOfType buildAndAppendAllof(AnyOfType anyOf, Object type) {
- if (type instanceof MatchType) {
+ if (type instanceof MatchType matchType) {
var allOf = new AllOfType();
- allOf.getMatch().add((MatchType) type);
+ allOf.getMatch().add(matchType);
if (anyOf == null) {
anyOf = new AnyOfType();
}
anyOf.getAllOf().add(allOf);
- } else if (type instanceof AllOfType) {
+ } else if (type instanceof AllOfType allOfType) {
if (anyOf == null) {
anyOf = new AnyOfType();
}
- anyOf.getAllOf().add((AllOfType) type);
+ anyOf.getAllOf().add(allOfType);
}
return anyOf;
@@ -215,11 +216,11 @@ public final class ToscaPolicyTranslatorUtils {
* @return TargetType
*/
public static TargetType buildAndAppendTarget(TargetType target, Object object) {
- if (object instanceof AnyOfType) {
- target.getAnyOf().add((AnyOfType) object);
- } else if (object instanceof MatchType) {
+ if (object instanceof AnyOfType anyOfType) {
+ target.getAnyOf().add(anyOfType);
+ } else if (object instanceof MatchType matchType) {
var allOf = new AllOfType();
- allOf.getMatch().add((MatchType) object);
+ allOf.getMatch().add(matchType);
var anyOf = new AnyOfType();
anyOf.getAllOf().add(allOf);
target.getAnyOf().add(anyOf);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java
index 596a3cc6..ccd4d0de 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtils.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -38,7 +39,6 @@ import java.util.Properties;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.Function;
-import java.util.stream.Collectors;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.IdReferenceType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
@@ -62,9 +62,9 @@ public final class XacmlPolicyUtils {
* file name. Does nothing for other OSs.
*/
private static final Function<String, String> SANITIZE_FILE_NAME =
- System.getProperty("os.name").startsWith("Windows")
- ? filename -> filename.replace(':', '_')
- : filename -> filename;
+ System.getProperty("os.name").startsWith("Windows")
+ ? filename -> filename.replace(':', '_')
+ : filename -> filename;
private XacmlPolicyUtils() {
super();
@@ -74,7 +74,7 @@ public final class XacmlPolicyUtils {
* Creates an empty PolicySetType object given the id and combining algorithm. Note,there
* will also be an empty Target created. You can easily override that if need be.
*
- * @param policyId Policy Id
+ * @param policyId Policy Id
* @param policyCombiningAlgorithm Policy Combining Algorithm
* @return PolicySetType object
*/
@@ -90,7 +90,7 @@ public final class XacmlPolicyUtils {
* Creates an empty PolicySetType object given the id and combining algorithm. Note,there
* will also be an empty Target created. You can easily override that if need be.
*
- * @param policyId Policy Id
+ * @param policyId Policy Id
* @param ruleCombiningAlgorithm Rule Combining Algorithm
* @return PolicyType object
*/
@@ -106,12 +106,12 @@ public final class XacmlPolicyUtils {
* This method adds a list of PolicyType objects to a root PolicySetType as
* referenced policies.
*
- * @param rootPolicy Root PolicySet being updated
+ * @param rootPolicy Root PolicySet being updated
* @param referencedPolicies A list of PolicyType being added as a references
* @return the rootPolicy PolicySet object
*/
public static PolicySetType addPoliciesToXacmlRootPolicy(PolicySetType rootPolicy,
- PolicyType... referencedPolicies) {
+ PolicyType... referencedPolicies) {
var factory = new ObjectFactory();
//
// Iterate each policy
@@ -133,12 +133,12 @@ public final class XacmlPolicyUtils {
/**
* This method updates a root PolicySetType by adding in a PolicyType as a reference.
*
- * @param rootPolicy Root PolicySet being updated
+ * @param rootPolicy Root PolicySet being updated
* @param referencedPolicySets A list of PolicySetType being added as a references
* @return the rootPolicy PolicySet object
*/
public static PolicySetType addPolicySetsToXacmlRootPolicy(PolicySetType rootPolicy,
- PolicySetType... referencedPolicySets) {
+ PolicySetType... referencedPolicySets) {
var factory = new ObjectFactory();
//
// Iterate each policy
@@ -160,7 +160,7 @@ public final class XacmlPolicyUtils {
/**
* Adds in the root policy to the PDP properties object.
*
- * @param properties Input properties
+ * @param properties Input properties
* @param rootPolicyPath Path to the root policy file
* @return Properties object
*/
@@ -187,14 +187,14 @@ public final class XacmlPolicyUtils {
// Set the new comma separated list
//
properties.setProperty(XACMLProperties.PROP_ROOTPOLICIES,
- rootPolicies.stream().collect(Collectors.joining(",")));
+ String.join(",", rootPolicies));
return properties;
}
/**
* Adds in the referenced policy to the PDP properties object.
*
- * @param properties Input properties
+ * @param properties Input properties
* @param refPolicyPath Path to the referenced policy file
* @return Properties object
*/
@@ -221,7 +221,7 @@ public final class XacmlPolicyUtils {
// Set the new comma separated list
//
properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES,
- referencedPolicies.stream().collect(Collectors.joining(",")));
+ String.join(",", referencedPolicies));
return properties;
}
@@ -229,7 +229,7 @@ public final class XacmlPolicyUtils {
* Removes a root policy from the Properties object. Both in the line
* that identifies the policy and the .file property that points to the path.
*
- * @param properties Input Properties object to remove
+ * @param properties Input Properties object to remove
* @param rootPolicyPath The policy file path
* @return Properties object
*/
@@ -273,7 +273,7 @@ public final class XacmlPolicyUtils {
* Removes a referenced policy from the Properties object. Both in the line
* that identifies the policy and the .file property that points to the path.
*
- * @param properties Input Properties object to remove
+ * @param properties Input Properties object to remove
* @param refPolicyPath The policy file path
* @return Properties object
*/
@@ -317,7 +317,7 @@ public final class XacmlPolicyUtils {
* Does a debug dump of referenced and root policy values.
*
* @param properties Input Properties object
- * @param logger Logger object to use
+ * @param logger Logger object to use
*/
public static void debugDumpPolicyProperties(Properties properties, Logger logger) {
//
@@ -356,18 +356,18 @@ public final class XacmlPolicyUtils {
* <P>How do we track that in case we need to know what policies we have loaded?
*
* @param policy PolicyType object
- * @param path Path for policy
+ * @param path Path for policy
* @return Path unique file path for the Policy
*/
public static Path constructUniquePolicyFilename(Object policy, Path path) {
String id;
String version;
- if (policy instanceof PolicyType) {
- id = ((PolicyType) policy).getPolicyId();
- version = ((PolicyType) policy).getVersion();
- } else if (policy instanceof PolicySetType) {
- id = ((PolicySetType) policy).getPolicySetId();
- version = ((PolicySetType) policy).getVersion();
+ if (policy instanceof PolicyType policyType) {
+ id = policyType.getPolicyId();
+ version = policyType.getVersion();
+ } else if (policy instanceof PolicySetType policySetType) {
+ id = policySetType.getPolicySetId();
+ version = policySetType.getVersion();
} else {
throw new IllegalArgumentException("Must pass a PolicyType or PolicySetType");
}
@@ -435,13 +435,13 @@ public final class XacmlPolicyUtils {
* Copies a xacml.properties file to another location and all the policies defined within it.
*
* @param propertiesPath Path to an existing properties file
- * @param properties Properties object
- * @param creator A callback that can create files. Allows JUnit test to pass Temporary folder
+ * @param properties Properties object
+ * @param creator A callback that can create files. Allows JUnit test to pass Temporary folder
* @return File object that points to new Properties file
* @throws IOException Could not read/write files
*/
public static File copyXacmlPropertiesContents(String propertiesPath, Properties properties,
- FileCreator creator) throws IOException {
+ FileCreator creator) throws IOException {
//
// Open the properties file
//
@@ -516,15 +516,15 @@ public final class XacmlPolicyUtils {
/**
* Wraps the call to XACMLPolicyWriter.
*
- * @param path Path to file to be written to.
+ * @param path Path to file to be written to.
* @param policy PolicyType or PolicySetType
* @return Path - the same path passed in most likely from XACMLPolicyWriter. Or NULL if an error occurs.
*/
public static Path writePolicyFile(Path path, Object policy) {
- if (policy instanceof PolicyType) {
- return XACMLPolicyWriter.writePolicyFile(path, (PolicyType) policy);
- } else if (policy instanceof PolicySetType) {
- return XACMLPolicyWriter.writePolicyFile(path, (PolicySetType) policy);
+ if (policy instanceof PolicyType policyType) {
+ return XACMLPolicyWriter.writePolicyFile(path, policyType);
+ } else if (policy instanceof PolicySetType policySetType) {
+ return XACMLPolicyWriter.writePolicyFile(path, policySetType);
} else {
throw new IllegalArgumentException("Expecting PolicyType or PolicySetType");
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java
index ca29c96a..f4011bd0 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyType.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -69,8 +69,8 @@ public class MatchablePolicyType {
);
//@formatter:on
- private ToscaConceptIdentifier policyId;
- private Map<String, MatchableProperty> matchables = new HashMap<>();
+ private final ToscaConceptIdentifier policyId;
+ private final Map<String, MatchableProperty> matchables = new HashMap<>();
public MatchablePolicyType(@NonNull ToscaPolicyType policyType, @NonNull MatchableCallback callback) {
this.policyId = new ToscaConceptIdentifier(policyType.getName(), policyType.getVersion());
@@ -119,7 +119,7 @@ public class MatchablePolicyType {
final String property = entrySet.getKey();
final var toscaProperty = entrySet.getValue();
//
- // Most likely case is its a primitive
+ // Most likely case is it's a primitive
//
if (isPrimitive(toscaProperty.getType())) {
MatchableProperty primitiveProperty = handlePrimitive(property, toscaProperty);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java
index 8ea65307..048d6185 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeBoolean.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 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.
@@ -42,8 +42,8 @@ public class MatchablePropertyTypeBoolean extends MatchablePropertyTypeBase<Bool
@Override
public Boolean validate(Object value) throws ToscaPolicyConversionException {
- if (value instanceof Boolean) {
- return (Boolean) value;
+ if (value instanceof Boolean bolValue) {
+ return bolValue;
}
return Boolean.parseBoolean(value.toString());
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java
index bc702c1c..cac7d041 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeFloat.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 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.
@@ -45,13 +45,13 @@ public class MatchablePropertyTypeFloat extends MatchablePropertyTypeBase<Float>
//
// Most likely it isn't because Gson does not recognize floats
//
- if (value instanceof Float) {
- return (Float) value;
+ if (value instanceof Float floatValue) {
+ return floatValue;
}
try {
return Float.parseFloat(value.toString());
} catch (NumberFormatException e) {
- throw new ToscaPolicyConversionException("Bad float value" + value.toString(), e);
+ throw new ToscaPolicyConversionException("Bad float value" + value, e);
}
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java
index b23d344f..fc5b7fdb 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeInteger.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 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.
@@ -42,8 +42,8 @@ public class MatchablePropertyTypeInteger extends MatchablePropertyTypeBase<Inte
@Override
public Integer validate(Object value) throws ToscaPolicyConversionException {
- if (value instanceof Integer) {
- return (Integer) value;
+ if (value instanceof Integer intValue) {
+ return intValue;
}
try {
return Integer.valueOf(value.toString());
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java
index 0c42d357..24af9973 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeList.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 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.
@@ -33,7 +33,8 @@ import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionExcepti
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
public class MatchablePropertyTypeList extends MatchablePropertyTypeBase<List<MatchablePropertyType<?>>> {
- private MatchableProperty primitiveProperty;
+
+ private final MatchableProperty primitiveProperty;
/**
* constructor.
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java
index 71ea55e8..b79d48ea 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePropertyTypeTimestamp.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 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.
@@ -47,7 +47,7 @@ public class MatchablePropertyTypeTimestamp extends MatchablePropertyTypeBase<IS
try {
return ISO8601DateTime.fromISO8601DateTimeString(value.toString());
} catch (ParseException e) {
- throw new ToscaPolicyConversionException("bad ISO8601 timevalue " + value.toString(), e);
+ throw new ToscaPolicyConversionException("bad ISO8601 time value " + value, e);
}
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java
index d1c6d38c..c1c0f15c 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslator.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -59,16 +60,14 @@ import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@Setter
+@Getter
public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
private static final Logger LOGGER = LoggerFactory.getLogger(StdBaseTranslator.class);
private static final ObjectFactory factory = new ObjectFactory();
- @Getter
- @Setter
protected boolean booleanReturnAttributes = false;
- @Getter
- @Setter
protected boolean booleanReturnSingleValueAttributesAsCollection = false;
public static final String POLICY_ID = "policy-id";
@@ -131,7 +130,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* obligations. This method must be overridden and be implemented for the specific application as
* obligations may have different expected attributes per application.
*
- * @param obligations Collection of obligation objects
+ * @param obligations Collection of obligation objects
* @param decisionResponse DecisionResponse object used to store any results from obligations.
*/
protected abstract void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse);
@@ -141,7 +140,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* can be overridden for each specific application as advice may have different expected attributes per
* application.
*
- * @param advice Collection of Advice objects
+ * @param advice Collection of Advice objects
* @param decisionResponse DecisionResponse object used to store any results from advice.
*/
protected abstract void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse);
@@ -151,10 +150,10 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* DecisionResponse object.
*
* @param attributeCategories Collection of AttributeCategory objects
- * @param decisionResponse DecisionResponse object used to store any attributes
+ * @param decisionResponse DecisionResponse object used to store any attributes
*/
protected void scanAttributes(Collection<AttributeCategory> attributeCategories,
- DecisionResponse decisionResponse) {
+ DecisionResponse decisionResponse) {
var returnedAttributes = new HashMap<String, Object>();
for (AttributeCategory attributeCategory : attributeCategories) {
var mapCategory = new HashMap<String, Object>();
@@ -163,7 +162,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
// Most attributes have a single value, thus the collection is not necessary to
// return. However, we will allow this to be configurable.
//
- if (! booleanReturnSingleValueAttributesAsCollection && attribute.getValues().size() == 1) {
+ if (!booleanReturnSingleValueAttributesAsCollection && attribute.getValues().size() == 1) {
var iterator = attribute.getValues().iterator();
var value = iterator.next();
mapCategory.put(attribute.getAttributeId().stringValue(), value.getValue().toString());
@@ -173,7 +172,7 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
}
returnedAttributes.put(attributeCategory.getCategory().stringValue(), mapCategory);
}
- if (! returnedAttributes.isEmpty()) {
+ if (!returnedAttributes.isEmpty()) {
decisionResponse.setAttributes(returnedAttributes);
}
}
@@ -182,25 +181,25 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* From the TOSCA metadata section, pull in values that are needed into the XACML policy.
*
* @param policy Policy Object to store the metadata
- * @param map The Metadata TOSCA Map
+ * @param map The Metadata TOSCA Map
* @return Same Policy Object
* @throws ToscaPolicyConversionException If there is something missing from the metadata
*/
- protected PolicyType fillMetadataSection(PolicyType policy,
- Map<String, Object> map) throws ToscaPolicyConversionException {
+ protected PolicyType fillMetadataSection(PolicyType policy, Map<String, Object> map)
+ throws ToscaPolicyConversionException {
//
// Ensure the policy-id exists - we don't use it here. It
// is saved in the TOSCA Policy Name field.
//
- if (! map.containsKey(POLICY_ID)) {
+ if (!map.containsKey(POLICY_ID)) {
throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata " + POLICY_ID);
}
//
// Ensure the policy-version exists
//
- if (! map.containsKey(POLICY_VERSION)) {
+ if (!map.containsKey(POLICY_VERSION)) {
throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata "
- + POLICY_VERSION);
+ + POLICY_VERSION);
}
//
// Add in the Policy Version
@@ -214,20 +213,20 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
* return the obligation only instead of adding it directly to a rule/policy/policyset.
* But this is fine for now.
*
- * @param <T> RuleType, PolicyType, PolicySetType object
- * @Param policyId The policy-id
+ * @param <T> RuleType, PolicyType, PolicySetType object
+ * @param policyId The policy-id
* @param ruleOrPolicy Incoming RuleType, PolicyType, PolicySetType object
- * @param jsonPolicy JSON String representation of policy.
- * @param weight Weighting for the policy (optional)
+ * @param jsonPolicy JSON String representation of policy.
+ * @param weight Weighting for the policy (optional)
* @return Return the Incoming RuleType, PolicyType, PolicySetType object for convenience.
*/
protected <T> T addObligation(T ruleOrPolicy, String policyId, String jsonPolicy, Integer weight,
- String policyType) {
+ String policyType) {
//
// Creating obligation for returning policy
//
LOGGER.info("Obligation Policy id: {} type: {} weight: {} policy:{}{}", policyId, policyType, weight,
- XacmlPolicyUtils.LINE_SEPARATOR, jsonPolicy);
+ XacmlPolicyUtils.LINE_SEPARATOR, jsonPolicy);
//
// Create our OnapObligation
//
@@ -241,12 +240,12 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
//
var obligations = new ObligationExpressionsType();
obligations.getObligationExpression().add(obligation);
- if (ruleOrPolicy instanceof RuleType) {
- ((RuleType) ruleOrPolicy).setObligationExpressions(obligations);
- } else if (ruleOrPolicy instanceof PolicyType) {
- ((PolicyType) ruleOrPolicy).setObligationExpressions(obligations);
- } else if (ruleOrPolicy instanceof PolicySetType) {
- ((PolicySetType) ruleOrPolicy).setObligationExpressions(obligations);
+ if (ruleOrPolicy instanceof RuleType ruleType) {
+ ruleType.setObligationExpressions(obligations);
+ } else if (ruleOrPolicy instanceof PolicyType policyType1) {
+ policyType1.setObligationExpressions(obligations);
+ } else if (ruleOrPolicy instanceof PolicySetType policySetType) {
+ policySetType.setObligationExpressions(obligations);
} else {
LOGGER.error("Unsupported class for adding obligation {}", ruleOrPolicy.getClass());
}
@@ -268,11 +267,11 @@ public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
// Create the match for the policy type
//
var match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_STRING_EQUAL,
- type,
- XACML3.ID_DATATYPE_STRING,
- ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
- XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
+ XACML3.ID_FUNCTION_STRING_EQUAL,
+ type,
+ XACML3.ID_DATATYPE_STRING,
+ ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
+ XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
//
// Add it to an AnyOfType object
//
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java
index 3e7c10af..ab32caef 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -52,7 +53,7 @@ public class StdCombinedPolicyRequest {
@XACMLSubject(attributeId = "urn:org:onap:onap-component", includeInResults = true)
private String onapComponent;
- @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
+ @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
private String onapInstance;
@XACMLAction()
@@ -92,18 +93,18 @@ public class StdCombinedPolicyRequest {
Map<String, Object> resources = decisionRequest.getResource();
for (Entry<String, Object> entrySet : resources.entrySet()) {
if (POLICY_ID_KEY.equals(entrySet.getKey())) {
- if (entrySet.getValue() instanceof Collection) {
- addPolicyIds(request, (Collection) entrySet.getValue());
- } else if (entrySet.getValue() instanceof String) {
- request.resource.add(entrySet.getValue().toString());
+ if (entrySet.getValue() instanceof Collection collection) {
+ addPolicyIds(request, collection);
+ } else if (entrySet.getValue() instanceof String stringValue) {
+ request.resource.add(stringValue);
}
continue;
}
if (POLICY_TYPE_KEY.equals(entrySet.getKey())) {
- if (entrySet.getValue() instanceof Collection) {
- addPolicyTypes(request, (Collection) entrySet.getValue());
- } else if (entrySet.getValue() instanceof String) {
- request.resourcePolicyType.add(entrySet.getValue().toString());
+ if (entrySet.getValue() instanceof Collection collection) {
+ addPolicyTypes(request, collection);
+ } else if (entrySet.getValue() instanceof String stringValue) {
+ request.resourcePolicyType.add(stringValue);
}
}
}
@@ -118,7 +119,7 @@ public class StdCombinedPolicyRequest {
}
protected static StdCombinedPolicyRequest addPolicyTypes(StdCombinedPolicyRequest request,
- Collection<Object> types) {
+ Collection<Object> types) {
for (Object type : types) {
request.resourcePolicyType.add(type.toString());
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java
index 42e3d43e..a084ec24 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -38,8 +39,8 @@ import com.att.research.xacml.std.annotations.XACMLRequest;
import com.att.research.xacml.std.annotations.XACMLSubject;
import com.att.research.xacml.util.FactoryException;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import lombok.Getter;
@@ -69,13 +70,13 @@ public class StdMatchablePolicyRequest {
@XACMLSubject(attributeId = "urn:org:onap:onap-component", includeInResults = true)
private String onapComponent;
- @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
+ @XACMLSubject(attributeId = "urn:org:onap:onap-instance", includeInResults = true)
private String onapInstance;
@XACMLAction()
private String action;
- protected static DataTypeFactory dataTypeFactory = null;
+ protected static DataTypeFactory dataTypeFactory = null;
protected static synchronized DataTypeFactory getDataTypeFactory() {
try {
@@ -148,10 +149,11 @@ public class StdMatchablePolicyRequest {
// and use that to validate the fields that are matchable.
//
try {
- if (entrySet.getValue() instanceof Collection) {
- addResources(resourceAttributes, (Collection) entrySet.getValue(), attributeId);
+ if (entrySet.getValue() instanceof Collection collection) {
+ addResources(resourceAttributes, collection, attributeId);
} else {
- addResources(resourceAttributes, Arrays.asList(entrySet.getValue().toString()), attributeId);
+ addResources(resourceAttributes,
+ Collections.singletonList(entrySet.getValue().toString()), attributeId);
}
} catch (DataTypeException e) {
throw new XacmlApplicationException("Failed to add resource ", e);
@@ -162,19 +164,20 @@ public class StdMatchablePolicyRequest {
}
protected static StdMutableRequestAttributes addResources(StdMutableRequestAttributes attributes,
- Collection<Object> values, String id) throws DataTypeException {
+ Collection<Object> values, String id)
+ throws DataTypeException {
var factory = getDataTypeFactory();
if (factory == null) {
return null;
}
for (Object value : values) {
- var mutableAttribute = new StdMutableAttribute();
+ var mutableAttribute = new StdMutableAttribute();
mutableAttribute.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
mutableAttribute.setAttributeId(new IdentifierImpl(id));
mutableAttribute.setIncludeInResults(true);
- DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
+ DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
AttributeValue<?> attributeValue = dataTypeExtended.createAttributeValue(value);
Collection<AttributeValue<?>> attributeValues = new ArrayList<>();
attributeValues.add(attributeValue);
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java
index 732542a2..a58b8c47 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -82,10 +82,9 @@ import org.slf4j.LoggerFactory;
* to translate policies.
*
* @author pameladragosh
- *
*/
@NoArgsConstructor
-public class StdMatchableTranslator extends StdBaseTranslator implements MatchableCallback {
+public class StdMatchableTranslator extends StdBaseTranslator implements MatchableCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
private static final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
@@ -112,7 +111,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* scanObligations - scans the list of obligations and make appropriate method calls to process
* obligations.
*
- * @param obligations Collection of obligation objects
+ * @param obligations Collection of obligation objects
* @param decisionResponse DecisionResponse object used to store any results from obligations.
*/
@Override
@@ -165,10 +164,10 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* contents and their details.
*
* @param closestMatches Map holding the current set of highest weight policy types
- * @param obligation Obligation object
+ * @param obligation Obligation object
*/
protected void scanClosestMatchObligation(
- Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches, Obligation obligation) {
+ Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches, Obligation obligation) {
//
// Create our OnapObligation object
//
@@ -177,7 +176,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// All 4 *should* be there
//
if (onapObligation.getPolicyId() == null || onapObligation.getPolicyContent() == null
- || onapObligation.getPolicyType() == null || onapObligation.getWeight() == null) {
+ || onapObligation.getPolicyType() == null || onapObligation.getWeight() == null) {
LOGGER.error("Missing an expected attribute in obligation.");
return;
}
@@ -197,13 +196,13 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Only need to check first one - as we will ensure there is only one weight
//
Entry<Integer, List<Pair<String, Map<String, Object>>>> firstEntry =
- weightMap.entrySet().iterator().next();
+ weightMap.entrySet().iterator().next();
if (policyWeight < firstEntry.getKey()) {
//
// Existing policies have a greater weight, so we will not add it
//
LOGGER.info("{} is lesser weight {} than current policies, will not return it", policyWeight,
- firstEntry.getKey());
+ firstEntry.getKey());
} else if (firstEntry.getKey().equals(policyWeight)) {
//
// Same weight - we will add it
@@ -246,7 +245,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
//
if (toscaPolicyTypeTemplate == null) {
throw new ToscaPolicyConversionException(
- "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
+ "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
}
//
// Policy name should be at the root
@@ -340,14 +339,8 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
return null;
}
- private class MyMatchableCallback implements MatchableCallback {
- private StdMatchableTranslator translator;
- private ToscaServiceTemplate template;
-
- public MyMatchableCallback(StdMatchableTranslator translator, ToscaServiceTemplate template) {
- this.translator = translator;
- this.template = template;
- }
+ private record MyMatchableCallback(StdMatchableTranslator translator, ToscaServiceTemplate template)
+ implements MatchableCallback {
@Override
public ToscaPolicyType retrievePolicyType(String derivedFrom) {
@@ -369,7 +362,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* For generating target type, we scan for matchable properties
* and use those to build the policy.
*
- * @param policy the policy
+ * @param policy the policy
* @param template template containing the policy
* @return {@code Pair<TargetType, Integer>} Returns a TargetType and a Total Weight of matchables.
*/
@@ -394,7 +387,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Create the matchable
//
matchablePolicyType = new MatchablePolicyType(
- template.getPolicyTypes().get(policy.getType()), myCallback);
+ template.getPolicyTypes().get(policy.getType()), myCallback);
//
// Cache it
//
@@ -422,7 +415,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
@SuppressWarnings("unchecked")
protected void fillTargetTypeWithMatchables(TargetType target, MatchablePolicyType matchablePolicyType,
- Map<String, Object> properties) throws ToscaPolicyConversionException {
+ Map<String, Object> properties) throws ToscaPolicyConversionException {
for (Entry<String, Object> entrySet : properties.entrySet()) {
String propertyName = entrySet.getKey();
Object propertyValue = entrySet.getValue();
@@ -436,7 +429,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Depending on what type it is, add it into the target
//
ToscaPolicyTranslatorUtils.buildAndAppendTarget(target,
- matchable.getType().generate(propertyValue, id));
+ matchable.getType().generate(propertyValue, id));
continue;
}
@@ -480,7 +473,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Is it loaded in memory?
//
ToscaServiceTemplate policyTemplate = this.matchablePolicyTypes.get(policyTypeId);
- if (policyTemplate == null) {
+ if (policyTemplate == null) {
//
// Load the policy
//
@@ -540,7 +533,7 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
// Decode the template
//
ToscaServiceTemplate template = standardYamlCoder.decode(new String(bytes, StandardCharsets.UTF_8),
- ToscaServiceTemplate.class);
+ ToscaServiceTemplate.class);
//
// Ensure all the fields are setup correctly
//
@@ -561,12 +554,12 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
* pullPolicyType - pulls the given ToscaConceptIdentifier from the Policy Lifecycle API.
* If successful, will store it locally given the policyTypePath.
*
- * @param policyTypeId ToscaConceptIdentifier
+ * @param policyTypeId ToscaConceptIdentifier
* @param policyTypePath Path object to store locally
* @return ToscaPolicyType object. Null if failure.
*/
protected synchronized ToscaServiceTemplate pullPolicyType(ToscaConceptIdentifier policyTypeId,
- Path policyTypePath) {
+ Path policyTypePath) {
//
// This is what we return
//
@@ -603,6 +596,6 @@ public class StdMatchableTranslator extends StdBaseTranslator implements Matcha
*/
protected Path constructLocalFilePath(ToscaConceptIdentifier policyTypeId) {
return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
- + policyTypeId.getVersion() + ".yaml");
+ + policyTypeId.getVersion() + ".yaml");
}
}
diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
index 466aae12..5036b5a6 100644
--- a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
+++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProvider.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,7 +30,6 @@ import com.att.research.xacml.api.pdp.PDPEngineFactory;
import com.att.research.xacml.api.pdp.PDPException;
import com.att.research.xacml.util.FactoryException;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -70,7 +69,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
private HttpClient policyApiClient;
private Properties pdpProperties = null;
private PDPEngine pdpEngine = null;
- private Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
+ private final Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
@Override
public String applicationName() {
@@ -84,7 +83,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
@Override
public void initialize(Path pathForData, HttpClient policyApiClient)
- throws XacmlApplicationException {
+ throws XacmlApplicationException {
//
// Save our path
//
@@ -146,7 +145,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR,
- new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
+ Files.readString(refPath));
}
//
// Add root policy to properties object
@@ -156,7 +155,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
// Write the properties to disk
//
XacmlPolicyUtils.storeXacmlProperties(newProperties,
- XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
+ XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
//
// Reload the engine
//
@@ -175,14 +174,14 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
}
@Override
- public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
+ public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) {
//
// Find it in our map
//
Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
if (refPolicy == null) {
LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
- this.mapLoadedPolicies.size());
+ this.mapLoadedPolicies.size());
return false;
}
//
@@ -200,14 +199,14 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
Files.delete(refPolicy);
} catch (IOException e) {
LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
- refPolicy.toAbsolutePath(), e);
+ refPolicy.toAbsolutePath(), e);
}
//
// Write the properties to disk
//
try {
XacmlPolicyUtils.storeXacmlProperties(newProperties,
- XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
+ XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
} catch (IOException e) {
LOGGER.error("Failed to save the properties to disk {}", newProperties, e);
}
@@ -224,7 +223,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
//
if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
- this.mapLoadedPolicies.size());
+ this.mapLoadedPolicies.size());
}
//
// Not sure if any of the errors above warrant returning false
@@ -234,7 +233,7 @@ public abstract class StdXacmlApplicationServiceProvider implements XacmlApplica
@Override
public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request,
- Map<String, String[]> requestQueryParams) {
+ Map<String, String[]> requestQueryParams) {
//
// Convert to a XacmlRequest
//
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java
index 63c6b246..086bfc88 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ExceptionTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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,15 +21,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class ExceptionTest {
+class ExceptionTest {
@Test
- public void test() {
+ void test() {
ExceptionsTester tester = new ExceptionsTester();
assertEquals(3, tester.test(PolicyApiException.class));
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java
index c02d7fb3..8a54da21 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapObligationTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,18 +24,18 @@
package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.att.research.xacml.api.AttributeAssignment;
import com.att.research.xacml.api.Obligation;
import com.att.research.xacml.api.XACML3;
import java.util.Arrays;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.resources.ResourceUtils;
-public class OnapObligationTest {
+class OnapObligationTest {
String policyJson;
String policyBadJson;
@@ -51,55 +52,55 @@ public class OnapObligationTest {
/**
* setup - create test data.
*/
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
policyJson = ResourceUtils.getResourceAsString("test.policy.json");
policyBadJson = ResourceUtils.getResourceAsString("test.policy.bad.json");
assignmentPolicyId = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentBadPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyBadJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyBadJson
+ );
assignmentWeight = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
- 0
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
+ 0
+ );
assignmentPolicyType = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
- "onap.policies.Test"
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
+ "onap.policies.Test"
+ );
assignmentUnknown = TestUtilsCommon.createAttributeAssignment(
- "foo:bar",
- XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
- 10.2
- );
+ "foo:bar",
+ XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
+ 10.2
+ );
obligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType,
- assignmentUnknown));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType,
+ assignmentUnknown));
}
@Test
- public void testObligation() {
+ void testObligation() {
OnapObligation onapObligation = new OnapObligation(obligation);
assertNotNull(onapObligation);
assertThat(onapObligation.getPolicyId()).isEqualTo(assignmentPolicyId.getAttributeValue().getValue());
@@ -109,7 +110,7 @@ public class OnapObligationTest {
}
@Test
- public void testSimplePolicy() {
+ void testSimplePolicy() {
OnapObligation onapObligation = new OnapObligation("my.policy.id", policyJson);
assertNotNull(onapObligation);
assertThat(onapObligation.getPolicyId()).isEqualTo("my.policy.id");
@@ -126,7 +127,7 @@ public class OnapObligationTest {
@Test
- public void testWeightedPolicy() {
+ void testWeightedPolicy() {
OnapObligation onapObligation = new OnapObligation("my.policy.id", policyJson, "onap.policies.Test", 5);
assertNotNull(onapObligation);
assertThat(onapObligation.getPolicyId()).isEqualTo("my.policy.id");
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java
index 86708284..ac6d89b5 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryExceptionTest.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,15 +21,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class OnapPolicyFinderFactoryExceptionTest {
+class OnapPolicyFinderFactoryExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(5, new ExceptionsTester().test(OnapPolicyFinderFactoryException.class));
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java
index 5df2552d..8f7de199 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactoryTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -26,12 +27,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.FileInputStream;
import java.util.Properties;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class OnapPolicyFinderFactoryTest {
+class OnapPolicyFinderFactoryTest {
@Test
- public void testFinder() throws Exception {
+ void testFinder() throws Exception {
//
// Load our test properties to use
//
@@ -47,7 +48,7 @@ public class OnapPolicyFinderFactoryTest {
}
@Test
- public void testFinderWithCombiningAlgorithm() throws Exception {
+ void testFinderWithCombiningAlgorithm() throws Exception {
//
// Load our test properties to use
//
@@ -59,7 +60,7 @@ public class OnapPolicyFinderFactoryTest {
// Set a combining algorithm
//
properties.put("xacml.att.policyFinderFactory.combineRootPolicies",
- "urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides");
+ "urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides");
OnapPolicyFinderFactory finder = new OnapPolicyFinderFactory(properties);
assertThat(finder).isNotNull();
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java
index bd42933c..a5a7b7c1 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/PolicyApiCallerTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021, 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +22,9 @@
package org.onap.policy.pdp.xacml.application.common;
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.mock;
import static org.mockito.Mockito.when;
@@ -38,10 +38,10 @@ import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;
-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.endpoints.http.client.HttpClient;
import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
@@ -55,7 +55,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class PolicyApiCallerTest {
+class PolicyApiCallerTest {
private static final String MY_TYPE = "my-type";
private static final String MY_VERSION = "1.0.0";
@@ -80,8 +80,8 @@ public class PolicyApiCallerTest {
*
* @throws IOException if an error occurs
*/
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
+ @BeforeAll
+ static void setUpBeforeClass() throws Exception {
port = NetworkUtil.allocPort();
clientParams = mock(RestClientParameters.class);
@@ -93,17 +93,17 @@ public class PolicyApiCallerTest {
props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
final String svcpfx =
- PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
+ PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
- Integer.toString(clientParams.getPort()));
+ Integer.toString(clientParams.getPort()));
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
- ApiRestController.class.getName());
+ ApiRestController.class.getName());
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
- GsonMessageBodyHandler.class.getName());
+ GsonMessageBodyHandler.class.getName());
HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
@@ -111,8 +111,8 @@ public class PolicyApiCallerTest {
assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
}
- @AfterClass
- public static void tearDownAfterClass() {
+ @AfterAll
+ static void tearDownAfterClass() {
HttpServletServerFactoryInstance.getServerFactory().destroy();
}
@@ -121,26 +121,26 @@ public class PolicyApiCallerTest {
*
* @throws PolicyApiException if an error occurs
*/
- @Before
- public void setUp() throws PolicyApiException {
+ @BeforeEach
+ void setUp() throws PolicyApiException {
when(clientParams.getPort()).thenReturn(port);
api = new PolicyApiCaller(apiClient);
}
@Test
- public void testGetPolicyType() throws Exception {
+ void testGetPolicyType() throws Exception {
assertNotNull(api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)));
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(INVALID_TYPE, MY_VERSION)))
- .isInstanceOf(PolicyApiException.class);
+ .isInstanceOf(PolicyApiException.class);
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(UNKNOWN_TYPE, MY_VERSION)))
- .isInstanceOf(NotFoundException.class);
+ .isInstanceOf(NotFoundException.class);
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(NOT_A_TYPE, MY_VERSION)))
- .isInstanceOf(PolicyApiException.class);
+ .isInstanceOf(PolicyApiException.class);
// connect to a port that has no server
RestClientParameters params2 = mock(RestClientParameters.class);
@@ -152,7 +152,7 @@ public class PolicyApiCallerTest {
api = new PolicyApiCaller(apiClient2);
assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)))
- .isInstanceOf(PolicyApiException.class);
+ .isInstanceOf(PolicyApiException.class);
}
/**
@@ -168,32 +168,36 @@ public class PolicyApiCallerTest {
* Retrieves the specified version of a particular policy type.
*
* @param policyTypeId ID of desired policy type
- * @param versionId version of desired policy type
- * @param requestId optional request ID
- *
+ * @param versionId version of desired policy type
+ * @param requestId optional request ID
* @return the Response object containing the results of the API operation
*/
@GET
@Path("/policytypes/{policyTypeId}/versions/{versionId}")
public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
- @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
+ @PathParam("versionId") String versionId,
+ @HeaderParam("X-ONAP-RequestID") UUID requestId) {
assertEquals(MY_VERSION, versionId);
- switch (policyTypeId) {
- case UNKNOWN_TYPE:
+ return switch (policyTypeId) {
+ case UNKNOWN_TYPE -> {
logger.info("request for unknown policy type");
- return Response.status(Response.Status.NOT_FOUND).build();
- case INVALID_TYPE:
+ yield Response.status(Response.Status.NOT_FOUND).build();
+ }
+ case INVALID_TYPE -> {
logger.info("invalid request for policy type");
- return Response.status(Response.Status.BAD_REQUEST).build();
- case NOT_A_TYPE:
+ yield Response.status(Response.Status.BAD_REQUEST).build();
+ }
+ case NOT_A_TYPE -> {
logger.info("invalid request for policy type");
- return Response.status(Response.Status.OK).entity("string-type").build();
- default:
+ yield Response.status(Response.Status.OK).entity("string-type").build();
+ }
+ default -> {
logger.info("request for policy type={} version={}", policyTypeId, versionId);
- return Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();
- }
+ yield Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();
+ }
+ };
}
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java
index 026bea9e..884e1cae 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/TestUtilsCommon.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.
@@ -50,10 +51,10 @@ public class TestUtilsCommon {
/**
* createAttributeAssignment.
*
- * @param <T> Object can be String, Integer, Double, Boolean
- * @param id String attribute id
+ * @param <T> Object can be String, Integer, Double, Boolean
+ * @param id String attribute id
* @param category String for the attribute category
- * @param value Object containing a value
+ * @param value Object containing a value
* @return AttributeAssignment object
*/
public static <T> AttributeAssignment createAttributeAssignment(String id, String category, T value) {
@@ -71,13 +72,13 @@ public class TestUtilsCommon {
}
return new StdAttributeAssignment(new IdentifierImpl(category),
- new IdentifierImpl(id), "", attributeValue);
+ new IdentifierImpl(id), "", attributeValue);
}
/**
* createXacmlObligation.
*
- * @param id String obligation id
+ * @param id String obligation id
* @param attributeAssignments Collection of AttributeAssignment objects
* @return Obligation object
*/
@@ -97,7 +98,7 @@ public class TestUtilsCommon {
for (Entry<String, String> entrySet : ids.entrySet()) {
policyIds.add(new StdIdReference(new IdentifierImpl(entrySet.getKey()),
- StdVersion.newInstance(entrySet.getValue())));
+ StdVersion.newInstance(entrySet.getValue())));
}
return policyIds;
@@ -106,15 +107,15 @@ public class TestUtilsCommon {
/**
* createXacmlResponse.
*
- * @param code StatusCode
- * @param decision Decision
+ * @param code StatusCode
+ * @param decision Decision
* @param obligations Collection of Obligation objects
- * @param policyIds Collection of IdReference objects
+ * @param policyIds Collection of IdReference objects
* @return Response object
*/
- public static Response createXacmlResponse(StatusCode code, String message, Decision decision,
- Collection<Obligation> obligations,
- Collection<IdReference> policyIds) {
+ public static Response createXacmlResponse(StatusCode code, String message, Decision decision,
+ Collection<Obligation> obligations,
+ Collection<IdReference> policyIds) {
StdStatus status = new StdStatus(code, message);
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java
index 251c9710..f5c60443 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.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.
@@ -23,16 +24,16 @@
package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class ToscaDictionaryTest {
+class ToscaDictionaryTest {
@Test
- public void testConstructorIsProtected() throws Exception {
+ void testConstructorIsProtected() throws Exception {
//
// Ensure that this is static class
//
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java
index bee4ba3d..f09af12f 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.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,15 +21,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class ToscaPolicyConversionExceptionTest {
+class ToscaPolicyConversionExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(5, new ExceptionsTester().test(ToscaPolicyConversionException.class));
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java
index ef74beae..0542b5b4 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyTranslatorUtilsTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.att.research.xacml.api.XACML3;
import java.lang.reflect.Constructor;
@@ -42,15 +42,15 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.parameters.annotations.NotNull;
import org.onap.policy.common.utils.coder.CoderException;
-public class ToscaPolicyTranslatorUtilsTest {
+class ToscaPolicyTranslatorUtilsTest {
private static final ObjectFactory factory = new ObjectFactory();
@Test
- public void test() throws NoSuchMethodException, SecurityException {
+ void test() throws NoSuchMethodException, SecurityException {
final Constructor<ToscaPolicyTranslatorUtils> constructor
= ToscaPolicyTranslatorUtils.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
@@ -58,35 +58,35 @@ public class ToscaPolicyTranslatorUtilsTest {
}
@Test
- public void testTimeInRange() {
+ void testTimeInRange() {
ApplyType apply = ToscaPolicyTranslatorUtils.generateTimeInRange("00:00:00Z", "08:00:00Z", true);
assertThat(apply).isNotNull();
assertThat(apply.getExpression()).hasSize(3);
}
@Test
- public void testBuildAndAppend() {
+ void testBuildAndAppend() {
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, new MatchType())).isInstanceOf(AnyOfType.class);
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, new AllOfType())).isInstanceOf(AnyOfType.class);
- assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, new String())).isNull();
+ assertThat(ToscaPolicyTranslatorUtils.buildAndAppendAllof(null, "")).isNull();
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendTarget(new TargetType(),
- new AnyOfType()).getAnyOf()).hasSize(1);
+ new AnyOfType()).getAnyOf()).hasSize(1);
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendTarget(new TargetType(),
- new MatchType()).getAnyOf()).hasSize(1);
+ new MatchType()).getAnyOf()).hasSize(1);
assertThat(ToscaPolicyTranslatorUtils.buildAndAppendTarget(new TargetType(),
- new String()).getAnyOf()).isEmpty();
+ "").getAnyOf()).isEmpty();
}
@Test
- public void testInteger() {
+ void testInteger() {
assertThat(ToscaPolicyTranslatorUtils.parseInteger("foo")).isNull();
assertThat(ToscaPolicyTranslatorUtils.parseInteger("1")).isEqualTo(1);
assertThat(ToscaPolicyTranslatorUtils.parseInteger("1.0")).isEqualTo(1);
}
@Test
- public void testAddingVariables() {
+ void testAddingVariables() {
ApplyType applyType = new ApplyType();
applyType.setFunctionId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue());
@@ -109,7 +109,7 @@ public class ToscaPolicyTranslatorUtilsTest {
variable.setVariableId("my-variable-id");
ConditionType newCondition = ToscaPolicyTranslatorUtils.addVariableToCondition(condition, variable,
- XACML3.ID_FUNCTION_AND);
+ XACML3.ID_FUNCTION_AND);
assertThat(newCondition.getExpression().getValue()).isInstanceOf(ApplyType.class);
Object obj = newCondition.getExpression().getValue();
@@ -119,23 +119,23 @@ public class ToscaPolicyTranslatorUtilsTest {
@SuppressWarnings("deprecation")
@Test
- public void testDecodeProperties() throws ToscaPolicyConversionException {
+ void testDecodeProperties() throws ToscaPolicyConversionException {
Data data = ToscaPolicyTranslatorUtils.decodeProperties(Map.of("value", 20), Data.class);
assertThat(data.getValue()).isEqualTo(20);
// null value - invalid
assertThatThrownBy(() -> ToscaPolicyTranslatorUtils.decodeProperties(Map.of(), Data.class))
- .isInstanceOf(ToscaPolicyConversionException.class).hasMessageContaining("item \"value\"");
+ .isInstanceOf(ToscaPolicyConversionException.class).hasMessageContaining("item \"value\"");
// value is not an integer - cannot even decode it
assertThatThrownBy(() -> ToscaPolicyTranslatorUtils.decodeProperties(Map.of("value", "abc"), Data.class))
- .isInstanceOf(ToscaPolicyConversionException.class).getCause()
- .isInstanceOf(CoderException.class);
+ .isInstanceOf(ToscaPolicyConversionException.class).getCause()
+ .isInstanceOf(CoderException.class);
// null properties - cannot even decode
assertThatThrownBy(() -> ToscaPolicyTranslatorUtils.decodeProperties(null, Data.class))
- .isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessage("Cannot decode Data from null properties");
+ .isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessage("Cannot decode Data from null properties");
}
@Getter
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java
index be27b313..25ba6493 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,15 +23,15 @@
package org.onap.policy.pdp.xacml.application.common;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class XacmlApplicationExceptionTest {
+class XacmlApplicationExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(5, new ExceptionsTester().test(XacmlApplicationException.class));
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java
index 30bf232a..d2e23fe4 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlPolicyUtilsTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,13 +26,13 @@ package org.onap.policy.pdp.xacml.application.common;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.att.research.xacml.api.XACML3;
import com.att.research.xacml.util.XACMLPolicyWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
@@ -48,10 +48,9 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,9 +59,8 @@ import org.slf4j.LoggerFactory;
* that reference policies.
*
* @author pameladragosh
- *
*/
-public class XacmlPolicyUtilsTest {
+class XacmlPolicyUtilsTest {
private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPolicyUtilsTest.class);
static Properties properties;
@@ -77,7 +75,7 @@ public class XacmlPolicyUtilsTest {
static PolicyType policy4 = XacmlPolicyUtils.createEmptyPolicy("policy4", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
static PolicySetType policySet5 = XacmlPolicyUtils.createEmptyPolicySet(
- "policyset1", XACML3.ID_POLICY_FIRST_APPLICABLE);
+ "policyset1", XACML3.ID_POLICY_FIRST_APPLICABLE);
static Path path1;
static Path path2;
@@ -89,17 +87,15 @@ public class XacmlPolicyUtilsTest {
/**
* Temporary folder where we will store newly created policies.
*/
- @ClassRule
- public static TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Setup the JUnit tests by finishing creating the policies and
* writing them out to the temporary folder.
- *
- * @throws Exception thrown
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ public static void setUp() {
assertThatCode(() -> {
//
// Load our test property object
@@ -113,7 +109,7 @@ public class XacmlPolicyUtilsTest {
//
if (!"/".equals(File.separator)) {
List<String> fileProps = properties.keySet().stream().map(Object::toString)
- .filter(key -> key.endsWith(".file")).toList();
+ .filter(key -> key.endsWith(".file")).toList();
for (String fileProp : fileProps) {
properties.setProperty(fileProp, properties.getProperty(fileProp).replace("/", File.separator));
}
@@ -121,13 +117,14 @@ public class XacmlPolicyUtilsTest {
//
// Save root policy
//
- Path rootFile = XacmlPolicyUtils.constructUniquePolicyFilename(rootPolicy, policyFolder.getRoot().toPath());
+ Path rootFile = XacmlPolicyUtils.constructUniquePolicyFilename(rootPolicy,
+ policyFolder.toAbsolutePath());
LOGGER.info("Creating Root Policy {}", rootFile.toAbsolutePath());
rootPath = XacmlPolicyUtils.writePolicyFile(rootFile, rootPolicy);
//
// Create policies - Policies 1 and 2 will become references in the
// root policy. While Policies 3 and 4 will become references in the
- // soon to be created PolicySet 5 below.
+ // soon-to-be created PolicySet 5 below.
//
path1 = createPolicyContents(policy1, "resource1");
LOGGER.info(new String(Files.readAllBytes(path1)));
@@ -153,7 +150,7 @@ public class XacmlPolicyUtilsTest {
//
// Save that to disk
//
- File policySetFile = policyFolder.newFile("policySet5.xml");
+ File policySetFile = policyFolder.resolve("policySet5.xml").toFile();
LOGGER.info("Creating PolicySet {}", policySetFile.getAbsolutePath());
policySetPath = XACMLPolicyWriter.writePolicyFile(policySetFile.toPath(), policySet5);
@@ -163,21 +160,20 @@ public class XacmlPolicyUtilsTest {
/**
* Helper method that creates a very simple Policy and Rule and saves it to disk.
*
- * @param policy Policy to store contents in
+ * @param policy Policy to store contents in
* @param resource A simple resource id for the Target
* @return Path object of the policy
- * @throws IOException If unable to write to disk
*/
- private static Path createPolicyContents(PolicyType policy, String resource) throws IOException {
+ private static Path createPolicyContents(PolicyType policy, String resource) {
//
// Create The Match
//
MatchType matchPolicyId = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_STRING_EQUAL,
- resource,
- XACML3.ID_DATATYPE_STRING,
- XACML3.ID_RESOURCE_RESOURCE_ID,
- XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
+ XACML3.ID_FUNCTION_STRING_EQUAL,
+ resource,
+ XACML3.ID_DATATYPE_STRING,
+ XACML3.ID_RESOURCE_RESOURCE_ID,
+ XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
//
// This is our outer AnyOf - which is an OR
//
@@ -200,26 +196,27 @@ public class XacmlPolicyUtilsTest {
//
// Save it to disk
//
- Path policyFile = XacmlPolicyUtils.constructUniquePolicyFilename(policy, policyFolder.getRoot().toPath());
+ Path policyFile = XacmlPolicyUtils.constructUniquePolicyFilename(policy,
+ policyFolder.toAbsolutePath());
LOGGER.info("Creating Policy {}", policyFile.toAbsolutePath());
return XacmlPolicyUtils.writePolicyFile(policyFile, policy);
}
@Test
- public void testUncommonConditions() throws IOException {
- Path fileTemp = policyFolder.newFile().toPath();
+ void testUncommonConditions() {
+ Path fileTemp = policyFolder.toFile().toPath();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() ->
XacmlPolicyUtils.writePolicyFile(fileTemp, "not a policy")
);
- Path rootPath = policyFolder.getRoot().toPath();
+ Path rootPathZ = policyFolder.toAbsolutePath();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() ->
- XacmlPolicyUtils.constructUniquePolicyFilename("not a policy", rootPath)
+ XacmlPolicyUtils.constructUniquePolicyFilename("not a policy", rootPathZ)
);
}
@Test
- public void testUpdatingPolicies() {
+ void testUpdatingPolicies() {
assertThatCode(() -> {
//
// Just update root and policies
@@ -248,7 +245,7 @@ public class XacmlPolicyUtilsTest {
}
@Test
- public void testRemovingReferencedProperties() {
+ void testRemovingReferencedProperties() {
//
// Dump what we are starting with
//
@@ -286,7 +283,7 @@ public class XacmlPolicyUtilsTest {
}
@Test
- public void testRemovingRootProperties() {
+ void testRemovingRootProperties() {
//
// Dump what we are starting with
//
@@ -309,11 +306,12 @@ public class XacmlPolicyUtilsTest {
}
@Test
- public void testCopyingProperties() throws Exception {
+ void testCopyingProperties() throws Exception {
//
// Copy to this folder
//
- File copyFolder = policyFolder.newFolder("copy");
+ File copyFolder = policyFolder.resolve("copy").toFile();
+ assertTrue(copyFolder.mkdirs());
assertThat(copyFolder).exists();
//
// Mock up a properties object
@@ -324,19 +322,19 @@ public class XacmlPolicyUtilsTest {
//
// Write the properties out to a file
//
- Path fileProperties = XacmlPolicyUtils.getPropertiesPath(policyFolder.getRoot().toPath());
+ Path fileProperties = XacmlPolicyUtils.getPropertiesPath(policyFolder.toAbsolutePath());
XacmlPolicyUtils.storeXacmlProperties(mockProperties, fileProperties);
//
// Now we can test the copy method
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile("copy/" + filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve("copy/" + filename).toFile();
File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
- fileProperties.toAbsolutePath().toString(), mockProperties, myCreator);
+ fileProperties.toAbsolutePath().toString(), mockProperties, myCreator);
assertThat(propertiesFile).canRead();
assertThat(Path.of(copyFolder.getAbsolutePath(),
- rootPath.getFileName().toString()).toFile()).canRead();
+ rootPath.getFileName().toString()).toFile()).canRead();
assertThat(Path.of(copyFolder.getAbsolutePath(),
- path1.getFileName().toString()).toFile()).canRead();
+ path1.getFileName().toString()).toFile()).canRead();
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java
index e157f174..dcf788d4 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/matchable/MatchablePolicyTypeTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2020, 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.
@@ -25,8 +25,8 @@ package org.onap.policy.pdp.xacml.application.common.matchable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.att.research.xacml.api.Identifier;
import com.att.research.xacml.api.XACML3;
@@ -42,8 +42,8 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -59,7 +59,7 @@ import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionExcepti
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class MatchablePolicyTypeTest implements MatchableCallback {
+class MatchablePolicyTypeTest implements MatchableCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(MatchablePolicyTypeTest.class);
private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
private static final String TEST_POLICYTYPE_FILE = "src/test/resources/matchable/onap.policies.Test-1.0.0.yaml";
@@ -73,8 +73,8 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
*
* @throws CoderException object
*/
- @BeforeClass
- public static void setupLoadPolicy() throws CoderException {
+ @BeforeAll
+ static void setupLoadPolicy() throws CoderException {
//
// Load our test policy type
//
@@ -116,7 +116,7 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
}
@Test
- public void testAllCodeCoverage() {
+ void testAllCodeCoverage() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
new MatchablePolicyType(null, null));
@@ -162,7 +162,7 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
}
@Test
- public void testPrimitiveValidation() throws Exception {
+ void testPrimitiveValidation() throws Exception {
ToscaProperty property = new ToscaProperty();
MatchablePropertyTypeBoolean booleanValue = new MatchablePropertyTypeBoolean(property);
assertThat(booleanValue.validate(Boolean.TRUE)).isEqualTo(Boolean.TRUE);
@@ -194,12 +194,12 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
}
@Test
- public void testMatchables() throws ToscaPolicyConversionException {
+ void testMatchables() throws ToscaPolicyConversionException {
//
// Step 1: Create matchables from the PolicyType
//
MatchablePolicyType matchablePolicyType = new MatchablePolicyType(testTemplate.getPolicyTypes()
- .get(TEST_POLICYTYPE), this);
+ .get(TEST_POLICYTYPE), this);
assertThat(matchablePolicyType).isNotNull();
assertThat(matchablePolicyType.getPolicyId()).isNotNull();
assertThat(matchablePolicyType.getPolicyId().getName()).isEqualTo(TEST_POLICYTYPE);
@@ -257,7 +257,7 @@ public class MatchablePolicyTypeTest implements MatchableCallback {
@SuppressWarnings("unchecked")
private void generateTargetType(TargetType target, MatchablePolicyType matchablePolicyType,
- Map<String, Object> properties) throws ToscaPolicyConversionException {
+ Map<String, Object> properties) throws ToscaPolicyConversionException {
for (Entry<String, Object> entrySet : properties.entrySet()) {
String propertyName = entrySet.getKey();
Object propertyValue = entrySet.getValue();
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java
index c38ab716..9eb04241 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,8 @@ package org.onap.policy.pdp.xacml.application.common.operationshistory;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
import com.att.research.xacml.api.Attribute;
@@ -44,20 +45,19 @@ import java.util.LinkedList;
import java.util.Properties;
import java.util.Queue;
import java.util.UUID;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.guard.OperationsHistory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@RunWith(MockitoJUnitRunner.class)
-public class CountRecentOperationsPipTest {
+@ExtendWith(MockitoExtension.class)
+class CountRecentOperationsPipTest {
private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class);
private static final String ACTOR = "my-actor";
@@ -95,8 +95,8 @@ public class CountRecentOperationsPipTest {
*
* @throws IOException if properties cannot be loaded
*/
- @BeforeClass
- public static void setUpBeforeClass() throws IOException {
+ @BeforeAll
+ static void setUpBeforeClass() throws IOException {
//
// Load our test properties to use
//
@@ -114,14 +114,17 @@ public class CountRecentOperationsPipTest {
//
//
//
- LOGGER.info("Configured own entity manager {}", em.toString());
+ LOGGER.info("Configured own entity manager {}", em);
}
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() {
+ @AfterAll
+ static void cleanup() {
+ if (emf != null) {
+ emf.close();
+ }
if (em != null) {
em.close();
}
@@ -132,9 +135,9 @@ public class CountRecentOperationsPipTest {
*
* @throws Exception if an error occurs
*/
- @Before
- public void setUp() throws Exception {
- when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
+ @BeforeEach
+ void setUp() throws Exception {
+ lenient().when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
pipEngine = new MyPip();
@@ -148,12 +151,12 @@ public class CountRecentOperationsPipTest {
}
@Test
- public void testAttributesRequired() {
+ void testAttributesRequired() {
assertEquals(3, pipEngine.attributesRequired().size());
}
@Test
- public void testConfigure_DbException() {
+ void testConfigure_DbException() {
properties.put("jakarta.persistence.jdbc.url", "invalid");
assertThatCode(() ->
pipEngine.configure("issuer", properties)
@@ -161,44 +164,44 @@ public class CountRecentOperationsPipTest {
}
@Test
- public void testGetAttributes_NullIssuer() throws PIPException {
+ void testGetAttributes_NullIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn(null);
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_WrongIssuer() throws PIPException {
+ void testGetAttributes_WrongIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_NullActor() throws PIPException {
+ void testGetAttributes_NullActor() throws PIPException {
attributes = new LinkedList<>(Arrays.asList(null, RECIPE, TARGET));
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_NullRecipe() throws PIPException {
+ void testGetAttributes_NullRecipe() throws PIPException {
attributes = new LinkedList<>(Arrays.asList(ACTOR, null, TARGET));
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_NullTarget() throws PIPException {
+ void testGetAttributes_NullTarget() throws PIPException {
attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, null));
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testShutdown() {
+ void testShutdown() {
pipEngine.shutdown();
assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
.withMessageContaining("Engine is shutdown");
}
@Test
- public void testGetCountFromDb() throws Exception {
+ void testGetCountFromDb() throws Exception {
//
// Configure it using properties
//
@@ -231,7 +234,7 @@ public class CountRecentOperationsPipTest {
}
@Test
- public void testStringToChronosUnit() throws PIPException {
+ void testStringToChronosUnit() throws PIPException {
// not configured yet
OperationsHistory newEntry = createEntry();
assertEquals(-1, getCount(newEntry));
@@ -260,8 +263,8 @@ public class CountRecentOperationsPipTest {
private long getCount(OperationsHistory newEntry) throws PIPException {
responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
- attributes = new LinkedList<>(
- Arrays.asList(newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget()));
+ attributes = new LinkedList<>(Arrays.asList(newEntry.getActor(),
+ newEntry.getOperation(), newEntry.getTarget()));
PIPResponse result = pipEngine.getAttributes(pipRequest, pipFinder);
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java
index bd53789f..5bbbd2c1 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/GetOperationOutcomePipTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +22,8 @@ package org.onap.policy.pdp.xacml.application.common.operationshistory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -43,16 +43,16 @@ import java.time.Instant;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
-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.guard.OperationsHistory;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class GetOperationOutcomePipTest {
+class GetOperationOutcomePipTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GetOperationOutcomePipTest.class);
private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
@@ -75,8 +75,8 @@ public class GetOperationOutcomePipTest {
*
* @throws Exception connectivity issues
*/
- @BeforeClass
- public static void setupDatabase() throws Exception {
+ @BeforeAll
+ static void setupDatabase() throws Exception {
LOGGER.info("Setting up PIP Testing");
//
// Load our test properties to use
@@ -95,14 +95,14 @@ public class GetOperationOutcomePipTest {
//
//
//
- LOGGER.info("Configured own entity manager", em.toString());
+ LOGGER.info("Configured own entity manager {}", em);
}
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() {
+ @AfterAll
+ static void cleanup() {
if (em != null) {
em.close();
}
@@ -113,8 +113,8 @@ public class GetOperationOutcomePipTest {
*
* @throws Exception if an error occurs
*/
- @Before
- public void setupEngine() throws Exception {
+ @BeforeEach
+ void setupEngine() throws Exception {
when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
//
// Create instance
@@ -136,12 +136,12 @@ public class GetOperationOutcomePipTest {
}
@Test
- public void testAttributesRequired() {
+ void testAttributesRequired() {
assertEquals(1, pipEngine.attributesRequired().size());
}
@Test
- public void testConfigure_DbException() throws Exception {
+ void testConfigure_DbException() {
properties.put("jakarta.persistence.jdbc.url", "invalid");
assertThatCode(() ->
pipEngine.configure("issuer", properties)
@@ -149,19 +149,19 @@ public class GetOperationOutcomePipTest {
}
@Test
- public void testGetAttributes_NullIssuer() throws PIPException {
+ void testGetAttributes_NullIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn(null);
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes_WrongIssuer() throws PIPException {
+ void testGetAttributes_WrongIssuer() throws PIPException {
when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
}
@Test
- public void testGetAttributes() throws Exception {
+ void testGetAttributes() throws Exception {
//
//
//
@@ -179,12 +179,12 @@ public class GetOperationOutcomePipTest {
}
@Test
- public void testGetOutcomeFromDb() throws Exception {
+ void testGetOutcomeFromDb() throws Exception {
//
// Use reflection to run getCountFromDB
//
Method method = GetOperationOutcomePip.class.getDeclaredMethod("doDatabaseQuery",
- String.class);
+ String.class);
method.setAccessible(true);
//
// Test pipEngine
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java
index 75af4482..a32b89c5 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdBaseTranslatorTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 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.
@@ -24,9 +25,9 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.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.att.research.xacml.api.Advice;
import com.att.research.xacml.api.AttributeAssignment;
@@ -39,13 +40,15 @@ import com.att.research.xacml.std.StdStatusCode;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.models.decisions.concepts.DecisionResponse;
@@ -54,7 +57,7 @@ import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class StdBaseTranslatorTest {
+class StdBaseTranslatorTest {
String policyJson;
String policyBadJson;
@@ -70,57 +73,57 @@ public class StdBaseTranslatorTest {
/**
* beforeSetup - loads and creates objects used later by the tests.
- * @throws CoderException CoderException
*
+ * @throws CoderException CoderException
*/
- @Before
- public void beforeSetup() throws CoderException {
+ @BeforeEach
+ void beforeSetup() throws CoderException {
policyJson = ResourceUtils.getResourceAsString("test.policy.json");
policyBadJson = ResourceUtils.getResourceAsString("test.policy.bad.json");
assignmentPolicyId = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
- "policy.id"
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
+ "policy.id"
+ );
assignmentPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentBadPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyBadJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyBadJson
+ );
assignmentWeight = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
- 0
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_WEIGHT_CATEGORY.stringValue(),
+ 0
+ );
assignmentPolicyType = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
- "onap.policies.Test"
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_TYPE_CATEGORY.stringValue(),
+ "onap.policies.Test"
+ );
assignmentUnknown = TestUtilsCommon.createAttributeAssignment(
- "foo:bar",
- XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
- 10.2
- );
+ "foo:bar",
+ XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(),
+ 10.2
+ );
obligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentPolicyId, assignmentPolicy, assignmentWeight, assignmentPolicyType));
}
@Test
- public void testTranslatorNormalFlow() throws Exception {
+ void testTranslatorNormalFlow() throws Exception {
StdBaseTranslator translator = new MyStdBaseTranslator();
assertNotNull(translator);
assertThatThrownBy(() -> translator.convertPolicy(null)).isInstanceOf(ToscaPolicyConversionException.class);
@@ -141,33 +144,33 @@ public class StdBaseTranslatorTest {
assertThat(policySet.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(policySet.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).hasSize(4);
+ .getAttributeAssignmentExpression()).hasSize(4);
PolicyType policy = new PolicyType();
translator.addObligation(policy, null, policyJson, null, null);
assertThat(policy.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(policy.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).hasSize(1);
+ .getAttributeAssignmentExpression()).hasSize(1);
RuleType rule = new RuleType();
translator.addObligation(rule, "policy.id", null, null, "foo.bar");
assertThat(rule.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(rule.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).hasSize(2);
+ .getAttributeAssignmentExpression()).hasSize(2);
rule = new RuleType();
translator.addObligation(rule, null, null, null, null);
assertThat(rule.getObligationExpressions().getObligationExpression()).hasSize(1);
assertThat(rule.getObligationExpressions().getObligationExpression().get(0)
- .getAttributeAssignmentExpression()).isEmpty();
+ .getAttributeAssignmentExpression()).isEmpty();
//
// Should not throw an exception
//
- translator.addObligation(new String(), "policy.id", policyJson, null, "foo.bar");
+ translator.addObligation("", "policy.id", policyJson, null, "foo.bar");
//
// Test the response conversion
@@ -177,7 +180,7 @@ public class StdBaseTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
Response xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_OK, null,
- Decision.PERMIT, Arrays.asList(obligation), policyIds);
+ Decision.PERMIT, Collections.singletonList(obligation), policyIds);
DecisionResponse decision = translator.convertResponse(xacmlResponse);
@@ -188,18 +191,18 @@ public class StdBaseTranslatorTest {
}
@Test
- public void testBadData() throws ToscaPolicyConversionException, ParseException {
+ void testBadData() throws ToscaPolicyConversionException, ParseException {
TestTranslator translator = new TestTranslator();
assertThatThrownBy(() -> translator.convertPolicy(
- new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("missing metadata");
+ new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessageContaining("missing metadata");
translator.metadata.put(StdBaseTranslator.POLICY_ID, "random.policy.id");
assertThatThrownBy(() -> translator.convertPolicy(
- new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("missing metadata");
+ new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessageContaining("missing metadata");
translator.metadata.put(StdBaseTranslator.POLICY_VERSION, "1.0.0");
@@ -211,7 +214,7 @@ public class StdBaseTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
Response xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_OK, null,
- Decision.PERMIT, Arrays.asList(obligation), policyIds);
+ Decision.PERMIT, Collections.singletonList(obligation), policyIds);
DecisionResponse decision = translator.convertResponse(xacmlResponse);
@@ -221,18 +224,18 @@ public class StdBaseTranslatorTest {
assertThat(decision.getPolicies()).isEmpty();
Obligation badObligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentBadPolicy, assignmentUnknown));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentBadPolicy, assignmentUnknown));
xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_MISSING_ATTRIBUTE, null,
- Decision.PERMIT, Arrays.asList(badObligation), policyIds);
+ Decision.PERMIT, List.of(badObligation), policyIds);
decision = translator.convertResponse(xacmlResponse);
assertNotNull(decision);
xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_PROCESSING_ERROR,
- "Bad obligation", Decision.DENY, Arrays.asList(badObligation), policyIds);
+ "Bad obligation", Decision.DENY, List.of(badObligation), policyIds);
decision = translator.convertResponse(xacmlResponse);
@@ -241,27 +244,31 @@ public class StdBaseTranslatorTest {
assertThat(decision.getMessage()).isEqualTo("Bad obligation");
}
- private class MyStdBaseTranslator extends StdBaseTranslator {
+ private static class MyStdBaseTranslator extends StdBaseTranslator {
@Override
protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
@Override
protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
}
- private class TestTranslator extends StdBaseTranslator {
- public Map<String, Object> metadata = new HashMap<>();
+ private static class TestTranslator extends StdBaseTranslator {
+ Map<String, Object> metadata = new HashMap<>();
@Override
protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
@Override
protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
+ // do nothing for unit test
}
@Override
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java
index be7e0cea..fcb6b91f 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyRequestTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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,25 +21,25 @@
package org.onap.policy.pdp.xacml.application.common.std;
-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 static org.mockito.Mockito.when;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
-@RunWith(MockitoJUnitRunner.class)
-public class StdCombinedPolicyRequestTest {
+@ExtendWith(MockitoExtension.class)
+class StdCombinedPolicyRequestTest {
private static final String ACTION = "my-action";
private static final String ONAP_NAME = "my-name";
private static final String ONAP_INSTANCE = "my-instance";
@@ -56,8 +57,8 @@ public class StdCombinedPolicyRequestTest {
/**
* Initializes objects.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
resources = new TreeMap<>();
when(decreq.getResource()).thenReturn(resources);
@@ -68,7 +69,7 @@ public class StdCombinedPolicyRequestTest {
}
@Test
- public void testCreateInstance() {
+ void testCreateInstance() {
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY, 100);
resources.put(StdCombinedPolicyRequest.POLICY_TYPE_KEY, 101);
@@ -86,7 +87,7 @@ public class StdCombinedPolicyRequestTest {
}
@Test
- public void testCreateInstance_StringValues() {
+ void testCreateInstance_StringValues() {
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY, POLICY_ID);
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY + "-x", "unused value");
resources.put(StdCombinedPolicyRequest.POLICY_TYPE_KEY, POLICY_TYPE);
@@ -103,7 +104,7 @@ public class StdCombinedPolicyRequestTest {
}
@Test
- public void testCreateInstance_Collections() {
+ void testCreateInstance_Collections() {
resources.put(StdCombinedPolicyRequest.POLICY_ID_KEY, Collections.singleton(POLICY_ID));
resources.put(StdCombinedPolicyRequest.POLICY_TYPE_KEY, Collections.singleton(POLICY_TYPE));
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java
index 9f0e0ac9..d379feef 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdCombinedPolicyResultsTranslatorTest.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.
@@ -24,7 +25,7 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.att.research.xacml.api.AttributeAssignment;
import com.att.research.xacml.api.Decision;
@@ -35,10 +36,11 @@ import com.att.research.xacml.std.StdStatusCode;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -51,7 +53,7 @@ import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class StdCombinedPolicyResultsTranslatorTest {
+class StdCombinedPolicyResultsTranslatorTest {
String policyJson;
String policyBadJson;
@@ -65,38 +67,38 @@ public class StdCombinedPolicyResultsTranslatorTest {
/**
* setup - preload policies.
*/
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
policyJson = ResourceUtils.getResourceAsString("test.policy.json");
policyBadJson = ResourceUtils.getResourceAsString("test.policy.bad.json");
assignmentPolicyId = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_ID_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyJson
+ );
assignmentBadPolicy = TestUtilsCommon.createAttributeAssignment(
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
- ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
- policyBadJson
- );
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT.stringValue(),
+ ToscaDictionary.ID_OBLIGATION_POLICY_CONTENT_CATEGORY.stringValue(),
+ policyBadJson
+ );
obligation = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- Arrays.asList(assignmentPolicyId, assignmentPolicy));
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ Arrays.asList(assignmentPolicyId, assignmentPolicy));
}
@Test
- public void test() throws ParseException {
+ void test() throws ParseException {
StdCombinedPolicyResultsTranslator translator = new StdCombinedPolicyResultsTranslator();
assertNotNull(translator);
@@ -109,7 +111,7 @@ public class StdCombinedPolicyResultsTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
Response xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_OK, null,
- Decision.PERMIT, Arrays.asList(obligation), policyIds);
+ Decision.PERMIT, Collections.singletonList(obligation), policyIds);
DecisionResponse decision = translator.convertResponse(xacmlResponse);
@@ -120,16 +122,16 @@ public class StdCombinedPolicyResultsTranslatorTest {
}
@Test
- public void testConvert() throws ToscaPolicyConversionException, CoderException {
+ void testConvert() throws ToscaPolicyConversionException, CoderException {
StdCombinedPolicyResultsTranslator translator = new StdCombinedPolicyResultsTranslator();
assertThatThrownBy(() -> translator.convertPolicy(null)).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("Cannot convert a NULL policy");
+ .hasMessageContaining("Cannot convert a NULL policy");
assertThatThrownBy(() -> translator.convertPolicy(
- new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
- .hasMessageContaining("missing metadata");
+ new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class)
+ .hasMessageContaining("missing metadata");
StandardCoder coder = new StandardCoder();
@@ -148,7 +150,7 @@ public class StdCombinedPolicyResultsTranslatorTest {
}
@Test
- public void testDecision() throws ToscaPolicyConversionException {
+ void testDecision() throws ToscaPolicyConversionException {
StdCombinedPolicyResultsTranslator translator = new StdCombinedPolicyResultsTranslator();
DecisionRequest decision = new DecisionRequest();
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java
index 57ab227a..3dbc613a 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchablePolicyRequestTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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,8 +21,8 @@
package org.onap.policy.pdp.xacml.application.common.std;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.att.research.xacml.api.Request;
@@ -32,17 +33,17 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
-@RunWith(MockitoJUnitRunner.class)
-public class StdMatchablePolicyRequestTest {
+@ExtendWith(MockitoExtension.class)
+class StdMatchablePolicyRequestTest {
private static final String ACTION = "my-action";
private static final String ONAP_NAME = "my-name";
private static final String ONAP_INSTANCE = "my-instance";
@@ -57,13 +58,11 @@ public class StdMatchablePolicyRequestTest {
private Map<String, Object> resources;
- private Request stdreq;
-
/**
* Initializes objects.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
resources = new TreeMap<>();
when(decreq.getResource()).thenReturn(resources);
@@ -74,12 +73,12 @@ public class StdMatchablePolicyRequestTest {
}
@Test
- public void testCreateInstance() throws XacmlApplicationException {
+ void testCreateInstance() throws XacmlApplicationException {
resources.put("resource1", RESOURCE1);
resources.put("resource2", RESOURCE2);
resources.put("resource3", Arrays.asList(RESOURCE3, RESOURCE4));
- stdreq = StdMatchablePolicyRequest.createInstance(decreq);
+ Request stdreq = StdMatchablePolicyRequest.createInstance(decreq);
assertNotNull(stdreq);
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java
new file mode 100644
index 00000000..121f8dec
--- /dev/null
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslator2Test.java
@@ -0,0 +1,124 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2024 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pdp.xacml.application.common.std;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.att.research.xacml.api.Obligation;
+import com.att.research.xacml.api.Request;
+import com.att.research.xacml.std.IdentifierImpl;
+import java.util.HashMap;
+import java.util.HashSet;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.onap.policy.models.decisions.concepts.DecisionRequest;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
+import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
+
+class StdMatchableTranslator2Test {
+
+ @Test
+ void convertRequest() throws ToscaPolicyConversionException {
+ var translator = new StdMatchableTranslator();
+ var returnRequest = Mockito.mock(Request.class);
+ var decisionRequest = Mockito.mock(DecisionRequest.class);
+
+ try (MockedStatic<StdMatchablePolicyRequest> utilities = Mockito.mockStatic(StdMatchablePolicyRequest.class)) {
+ utilities.when(() -> StdMatchablePolicyRequest.createInstance(decisionRequest))
+ .thenReturn(returnRequest);
+
+ assertEquals(returnRequest, translator.convertRequest(decisionRequest));
+ }
+ }
+
+ @Test
+ void convertRequest_Exception() {
+ var translator = new StdMatchableTranslator();
+ var decisionRequest = Mockito.mock(DecisionRequest.class);
+
+ try (MockedStatic<StdMatchablePolicyRequest> utilities = Mockito.mockStatic(StdMatchablePolicyRequest.class)) {
+ utilities.when(() -> StdMatchablePolicyRequest.createInstance(decisionRequest))
+ .thenThrow(new XacmlApplicationException("throwing an exception"));
+
+ assertThrows(ToscaPolicyConversionException.class, () -> translator.convertRequest(decisionRequest));
+ }
+ }
+
+ @Test
+ void scanClosestMatchObligation() {
+ var translator = new StdMatchableTranslator();
+ var obligation = Mockito.mock(Obligation.class);
+ when(obligation.getId()).thenReturn(new IdentifierImpl("id"));
+ when(obligation.getAttributeAssignments()).thenReturn(new HashSet<>());
+
+ assertDoesNotThrow(() -> translator.scanClosestMatchObligation(new HashMap<>(), obligation));
+ }
+
+ @Test
+ void convertPolicy() throws ToscaPolicyConversionException {
+ var translator = mock(StdMatchableTranslator.class);
+ var toscaPolicy = Mockito.mock(ToscaPolicy.class);
+ when(translator.convertPolicy(toscaPolicy)).thenCallRealMethod();
+ when(translator.findPolicyType(toscaPolicy.getTypeIdentifier())).thenReturn(null);
+
+ assertThrows(ToscaPolicyConversionException.class, () -> translator.convertPolicy(toscaPolicy));
+ }
+
+ @Test
+ void retrievePolicyType() {
+ var hashMap = new HashMap<String, ToscaPolicyType>();
+ var toscaPolicyType = new ToscaPolicyType();
+ hashMap.put("someId", toscaPolicyType);
+
+ var toscaTemplate = mock(ToscaServiceTemplate.class);
+ when(toscaTemplate.getPolicyTypes()).thenReturn(hashMap);
+
+ var translator = mock(StdMatchableTranslator.class);
+ when(translator.findPolicyType(any())).thenReturn(toscaTemplate);
+ when(translator.retrievePolicyType("someId")).thenCallRealMethod();
+
+ assertEquals(toscaPolicyType, translator.retrievePolicyType("someId"));
+ }
+
+ @Test
+ void retrievePolicyType_Exception() {
+ var translator = mock(StdMatchableTranslator.class);
+ when(translator.findPolicyType(any())).thenReturn(null);
+ when(translator.retrievePolicyType("someId")).thenCallRealMethod();
+
+ assertNull(translator.retrievePolicyType("someId"));
+ }
+
+ @Test
+ void retrieveDataType() {
+ assertNull(new StdMatchableTranslator().retrieveDataType("dataType"));
+ }
+} \ No newline at end of file
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java
index 95880efe..54c3a1b8 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdMatchableTranslatorTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +22,9 @@
package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.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.mock;
import static org.mockito.Mockito.when;
@@ -54,11 +54,10 @@ import java.util.UUID;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.endpoints.http.client.HttpClient;
import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
@@ -92,8 +91,8 @@ public class StdMatchableTranslatorTest {
private static ToscaServiceTemplate testTemplate;
private static HttpClient apiClient;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static java.nio.file.Path policyFolder;
/**
* Initializes {@link #clientParams} and starts a simple REST server to handle the
@@ -101,8 +100,8 @@ public class StdMatchableTranslatorTest {
*
* @throws IOException if an error occurs
*/
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
+ @BeforeAll
+ static void setUpBeforeClass() throws Exception {
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
//
@@ -115,21 +114,7 @@ public class StdMatchableTranslatorTest {
when(clientParams.getHostname()).thenReturn("localhost");
when(clientParams.getPort()).thenReturn(port);
- Properties props = new Properties();
- props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
-
- final String svcpfx =
- PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
-
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
- Integer.toString(clientParams.getPort()));
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
- ApiRestController.class.getName());
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
- props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
- GsonMessageBodyHandler.class.getName());
+ Properties props = getProperties();
HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
@@ -144,7 +129,7 @@ public class StdMatchableTranslatorTest {
//
ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
//
- // Make sure all the fields are setup properly
+ // Make sure all the fields are set up properly
//
JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
jtst.fromAuthorative(serviceTemplate);
@@ -159,13 +144,32 @@ public class StdMatchableTranslatorTest {
logger.info("Test Policy Type {}{}", XacmlPolicyUtils.LINE_SEPARATOR, testTemplate);
}
- @AfterClass
+ private static Properties getProperties() {
+ Properties props = new Properties();
+ props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
+
+ final String svcpfx =
+ PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
+
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
+ Integer.toString(clientParams.getPort()));
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
+ ApiRestController.class.getName());
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
+ props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
+ GsonMessageBodyHandler.class.getName());
+ return props;
+ }
+
+ @AfterAll
public static void tearDownAfterClass() {
HttpServletServerFactoryInstance.getServerFactory().destroy();
}
@Test
- public void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
+ void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
//
// Create our translator
//
@@ -174,19 +178,19 @@ public class StdMatchableTranslatorTest {
//
// Set it up
//
- translator.setPathForData(policyFolder.getRoot().toPath());
+ translator.setPathForData(policyFolder.getRoot().toAbsolutePath());
translator.setApiClient(apiClient);
//
// Load policies to test
//
String policyYaml = ResourceUtils.getResourceAsString(
- "src/test/resources/matchable/test.policies.input.tosca.yaml");
+ "src/test/resources/matchable/test.policies.input.tosca.yaml");
//
// Serialize it into a class
//
ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
//
- // Make sure all the fields are setup properly
+ // Make sure all the fields are set up properly
//
JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
jtst.fromAuthorative(serviceTemplate);
@@ -209,7 +213,7 @@ public class StdMatchableTranslatorTest {
//
List<AttributeAssignment> listAttributes = new ArrayList<>();
ObligationExpressionType xacmlObligation = translatedPolicy.getObligationExpressions()
- .getObligationExpression().get(0);
+ .getObligationExpression().get(0);
assertThat(xacmlObligation.getAttributeAssignmentExpression()).hasSize(4);
//
// Copy into the list
@@ -217,23 +221,23 @@ public class StdMatchableTranslatorTest {
xacmlObligation.getAttributeAssignmentExpression().forEach(assignment -> {
Object value = ((AttributeValueType) assignment.getExpression().getValue()).getContent().get(0);
listAttributes.add(TestUtilsCommon.createAttributeAssignment(assignment.getAttributeId(),
- assignment.getCategory(), value));
+ assignment.getCategory(), value));
});
//
// Pretend we got multiple policies to match a fictional request
//
Obligation obligation1 = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- listAttributes);
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ listAttributes);
Obligation obligation2 = TestUtilsCommon.createXacmlObligation(
- ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
- listAttributes);
+ ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
+ listAttributes);
//
// Should ignore this obligation
//
Obligation obligation3 = TestUtilsCommon.createXacmlObligation(
- "nobody:cares",
- listAttributes);
+ "nobody:cares",
+ listAttributes);
//
// Create a test XACML Response
//
@@ -242,8 +246,8 @@ public class StdMatchableTranslatorTest {
Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
com.att.research.xacml.api.Response xacmlResponse = TestUtilsCommon.createXacmlResponse(
- StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT,
- Arrays.asList(obligation1, obligation2, obligation3), policyIds);
+ StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT,
+ Arrays.asList(obligation1, obligation2, obligation3), policyIds);
//
// Test the response
//
@@ -280,15 +284,15 @@ public class StdMatchableTranslatorTest {
* Retrieves the specified version of a particular policy type.
*
* @param policyTypeId ID of desired policy type
- * @param versionId version of desired policy type
- * @param requestId optional request ID
- *
+ * @param versionId version of desired policy type
+ * @param requestId optional request ID
* @return the Response object containing the results of the API operation
*/
@GET
@Path("/policytypes/{policyTypeId}/versions/{versionId}")
public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
- @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
+ @PathParam("versionId") String versionId,
+ @HeaderParam("X-ONAP-RequestID") UUID requestId) {
logger.info("request for policy type={} version={}", policyTypeId, versionId);
return Response.status(Response.Status.OK).entity(testTemplate).build();
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java
index 82347474..4bacaf3c 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdOnapPipTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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,10 +23,11 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-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.assertNull;
+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;
@@ -46,15 +48,15 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Properties;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
-@RunWith(MockitoJUnitRunner.class)
-public class StdOnapPipTest {
+@ExtendWith(MockitoExtension.class)
+class StdOnapPipTest {
private static final String EXPECTED_EXCEPTION = "expected exception";
private static final String MY_ID = "my-id";
private static final String ISSUER = "my-issuer";
@@ -81,25 +83,25 @@ public class StdOnapPipTest {
*
* @throws PIPException if an error occurs
*/
- @Before
+ @BeforeEach
public void setUp() throws PIPException {
resp = new StdMutablePIPResponse();
- when(request.getIssuer()).thenReturn(ISSUER);
- when(request.getAttributeId()).thenReturn(ATTRIBUTE_ID);
+ lenient().when(request.getIssuer()).thenReturn(ISSUER);
+ lenient().when(request.getAttributeId()).thenReturn(ATTRIBUTE_ID);
pip = new MyPip();
- when(finder.getMatchingAttributes(request, pip)).thenReturn(resp);
+ lenient().when(finder.getMatchingAttributes(request, pip)).thenReturn(resp);
}
@Test
- public void testAttributesProvided() {
+ void testAttributesProvided() {
assertTrue(pip.attributesProvided().isEmpty());
}
@Test
- public void testConfigureStringProperties() throws PIPException {
+ void testConfigureStringProperties() throws PIPException {
Properties props = new Properties();
pip.configure(MY_ID, props);
@@ -108,19 +110,19 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipFinderPipRequest_NullResponse() {
+ void testGetAttributePipFinderPipRequest_NullResponse() {
assertNull(pip.getAttribute(finder, request));
}
@Test
- public void testGetAttributePipFinderPipRequest() {
+ void testGetAttributePipFinderPipRequest() {
pip.addStringAttribute(resp, CATEGORY, CATEGORY, STRING_VALUE, request);
assertEquals(STRING_VALUE, pip.getAttribute(finder, request));
}
@Test
- public void testGetAttributePipRequestPipFinder_NoStatus() {
+ void testGetAttributePipRequestPipFinder_NoStatus() {
resp.setStatus(null);
pip.addStringAttribute(resp, CATEGORY, CATEGORY, STRING_VALUE, request);
@@ -128,7 +130,7 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipRequestPipFinder_StatusNotOk() {
+ void testGetAttributePipRequestPipFinder_StatusNotOk() {
Status status = mock(Status.class);
when(status.isOk()).thenReturn(false);
resp.setStatus(status);
@@ -139,7 +141,7 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipRequestPipFinder_StatusOk() {
+ void testGetAttributePipRequestPipFinder_StatusOk() {
Status status = mock(Status.class);
when(status.isOk()).thenReturn(true);
resp.setStatus(status);
@@ -150,12 +152,12 @@ public class StdOnapPipTest {
}
@Test
- public void testGetAttributePipRequestPipFinder_NoAttributes() {
+ void testGetAttributePipRequestPipFinder_NoAttributes() {
assertNull(pip.getAttribute(request, finder));
}
@Test
- public void testGetAttributePipRequestPipFinder_Ex() throws PIPException {
+ void testGetAttributePipRequestPipFinder_Ex() throws PIPException {
when(finder.getMatchingAttributes(request, pip)).thenThrow(new PIPException(EXPECTED_EXCEPTION));
pip.addStringAttribute(resp, CATEGORY, CATEGORY, STRING_VALUE, request);
@@ -164,19 +166,19 @@ public class StdOnapPipTest {
}
@Test
- public void testFindFirstAttributeValue_NoAttributes() {
+ void testFindFirstAttributeValue_NoAttributes() {
assertNull(pip.findFirstAttributeValue(resp));
}
@Test
- public void testFindFirstAttributeValue_NullAttributeValue() {
+ void testFindFirstAttributeValue_NullAttributeValue() {
pip.addIntegerAttribute(resp, CATEGORY, ATTRIBUTE_ID, INT_VALUE, request);
assertNull(pip.findFirstAttributeValue(resp));
}
@Test
- public void testFindFirstAttributeValue_NullValues() {
+ void testFindFirstAttributeValue_NullValues() {
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, null, request);
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, STRING_VALUE, request);
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, null, request);
@@ -185,7 +187,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddIntegerAttribute() {
+ void testAddIntegerAttribute() {
pip.addIntegerAttribute(resp, CATEGORY, ATTRIBUTE_ID, INT_VALUE, request);
assertEquals(1, resp.getAttributes().size());
@@ -200,7 +202,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddIntegerAttribute_Ex() {
+ void testAddIntegerAttribute_Ex() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeInteger(int value) throws DataTypeException {
@@ -212,7 +214,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddIntegerAttribute_Null() {
+ void testAddIntegerAttribute_Null() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeInteger(int value) throws DataTypeException {
@@ -224,7 +226,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddLongAttribute() {
+ void testAddLongAttribute() {
pip.addLongAttribute(resp, CATEGORY, ATTRIBUTE_ID, LONG_VALUE, request);
assertEquals(1, resp.getAttributes().size());
@@ -239,7 +241,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddLongAttribute_Ex() {
+ void testAddLongAttribute_Ex() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeLong(long value) throws DataTypeException {
@@ -251,7 +253,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddLongAttribute_NullAttrValue() {
+ void testAddLongAttribute_NullAttrValue() {
pip = new MyPip() {
@Override
protected AttributeValue<BigInteger> makeLong(long value) throws DataTypeException {
@@ -263,7 +265,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddStringAttribute() {
+ void testAddStringAttribute() {
pip.addStringAttribute(resp, CATEGORY, ATTRIBUTE_ID, STRING_VALUE, request);
assertEquals(1, resp.getAttributes().size());
@@ -278,7 +280,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddStringAttribute_Ex() {
+ void testAddStringAttribute_Ex() {
pip = new MyPip() {
@Override
protected AttributeValue<String> makeString(String value) throws DataTypeException {
@@ -290,7 +292,7 @@ public class StdOnapPipTest {
}
@Test
- public void testAddStringAttribute_NullAttrValue() {
+ void testAddStringAttribute_NullAttrValue() {
pip = new MyPip() {
@Override
protected AttributeValue<String> makeString(String value) throws DataTypeException {
@@ -302,13 +304,13 @@ public class StdOnapPipTest {
}
@Test
- public void testShutdown() {
+ void testShutdown() {
assertThatCode(() -> pip.shutdown()).doesNotThrowAnyException();
assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pip.configure("foo", new Properties()))
.withMessageContaining("Engine is shutdown");
}
- private class MyPip extends StdOnapPip {
+ private static class MyPip extends StdOnapPip {
@Override
public Collection<PIPRequest> attributesRequired() {
@@ -316,7 +318,7 @@ public class StdOnapPipTest {
}
@Override
- public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
+ public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) {
return null;
}
}
diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java
index ea1e04d1..54fda276 100644
--- a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java
+++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/std/StdXacmlApplicationServiceProviderTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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,17 +23,17 @@ package org.onap.policy.pdp.xacml.application.common.std;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import com.att.research.xacml.api.Request;
import com.att.research.xacml.api.Response;
@@ -45,17 +46,18 @@ import com.google.common.io.Files;
import java.io.File;
import java.nio.file.Path;
import java.util.HashSet;
+import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.common.endpoints.http.client.HttpClient;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.models.decisions.concepts.DecisionResponse;
@@ -67,15 +69,15 @@ import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@RunWith(MockitoJUnitRunner.class)
-public class StdXacmlApplicationServiceProviderTest {
+@ExtendWith(MockitoExtension.class)
+class StdXacmlApplicationServiceProviderTest {
private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
private static final String TEMP_DIR_NAME = "src/test/resources/temp";
- private static File TEMP_DIR = new File(TEMP_DIR_NAME);
- private static Path TEMP_PATH = TEMP_DIR.toPath();
- private static File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
- private static File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
+ private static final File TEMP_DIR = new File(TEMP_DIR_NAME);
+ private static final Path TEMP_PATH = TEMP_DIR.toPath();
+ private static final File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
+ private static final File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
private static final String EXPECTED_EXCEPTION = "expected exception";
private static final String POLICY_NAME = "my-name";
private static final String POLICY_VERSION = "1.2.3";
@@ -100,24 +102,23 @@ public class StdXacmlApplicationServiceProviderTest {
private Response resp;
private ToscaPolicy policy;
- private PolicyType internalPolicy;
private StdXacmlApplicationServiceProvider prov;
/**
* Creates the temp directory.
*/
- @BeforeClass
- public static void setUpBeforeClass() {
+ @BeforeAll
+ static void setUpBeforeClass() {
assertTrue(TEMP_DIR.mkdir());
}
/**
* Deletes the temp directory and its contents.
*/
- @AfterClass
- public static void tearDownAfterClass() {
- for (File file : TEMP_DIR.listFiles()) {
+ @AfterAll
+ static void tearDownAfterClass() {
+ for (File file : Objects.requireNonNull(TEMP_DIR.listFiles())) {
if (!file.delete()) {
logger.warn("cannot delete: {}", file);
}
@@ -133,22 +134,22 @@ public class StdXacmlApplicationServiceProviderTest {
*
* @throws Exception if an error occurs
*/
- @Before
- public void setUp() throws Exception {
+ @BeforeEach
+ void setUp() throws Exception {
policy = new ToscaPolicy();
policy.setType(POLICY_TYPE);
policy.setName(POLICY_NAME);
policy.setVersion(POLICY_VERSION);
- internalPolicy = new PolicyType();
+ PolicyType internalPolicy = new PolicyType();
internalPolicy.setPolicyId(POLICY_NAME);
internalPolicy.setVersion(POLICY_VERSION);
- when(engineFactory.newEngine(any())).thenReturn(engine);
+ lenient().when(engineFactory.newEngine(any())).thenReturn(engine);
- when(engine.decide(req)).thenReturn(resp);
+ lenient().when(engine.decide(req)).thenReturn(resp);
- when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
+ lenient().when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
prov = new MyProv();
@@ -156,17 +157,17 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testApplicationName() {
+ void testApplicationName() {
assertNotNull(prov.applicationName());
}
@Test
- public void testActionDecisionsSupported() {
+ void testActionDecisionsSupported() {
assertTrue(prov.actionDecisionsSupported().isEmpty());
}
@Test
- public void testInitialize_testGetXxx() throws XacmlApplicationException {
+ void testInitialize_testGetXxx() throws XacmlApplicationException {
prov.initialize(TEMP_PATH, apiClient);
assertEquals(TEMP_PATH, prov.getDataPath());
@@ -177,32 +178,32 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testInitialize_Ex() throws XacmlApplicationException {
+ void testInitialize_Ex() {
assertThatThrownBy(() -> prov.initialize(new File(TEMP_DIR_NAME + "-nonExistent").toPath(), apiClient))
- .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
+ .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
}
@Test
- public void testSupportedPolicyTypes() {
+ void testSupportedPolicyTypes() {
assertThat(prov.supportedPolicyTypes()).isEmpty();
}
@Test
- public void testCanSupportPolicyType() {
+ void testCanSupportPolicyType() {
assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
}
@Test
- public void testLoadPolicy_ConversionError() throws XacmlApplicationException, ToscaPolicyConversionException {
- when(trans.convertPolicy(policy)).thenReturn(null);
+ void testLoadPolicy_ConversionError() throws ToscaPolicyConversionException {
+ lenient().when(trans.convertPolicy(policy)).thenReturn(null);
assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
}
@Test
- public void testLoadPolicy_testUnloadPolicy() throws Exception {
+ void testLoadPolicy_testUnloadPolicy() throws Exception {
prov.initialize(TEMP_PATH, apiClient);
- PROP_FILE.delete();
+ tryDeletePropFile();
final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
@@ -230,7 +231,7 @@ public class StdXacmlApplicationServiceProviderTest {
/*
* Prepare for unload.
*/
- PROP_FILE.delete();
+ tryDeletePropFile();
assertTrue(prov.unloadPolicy(policy));
@@ -248,7 +249,7 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testUnloadPolicy_NotDeployed() throws Exception {
+ void testUnloadPolicy_NotDeployed() throws Exception {
prov.initialize(TEMP_PATH, apiClient);
assertFalse(prov.unloadPolicy(policy));
@@ -258,14 +259,14 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testMakeDecision() throws ToscaPolicyConversionException {
+ void testMakeDecision() throws ToscaPolicyConversionException {
prov.createEngine(null);
DecisionRequest decreq = mock(DecisionRequest.class);
- when(trans.convertRequest(decreq)).thenReturn(req);
+ lenient().when(trans.convertRequest(decreq)).thenReturn(req);
DecisionResponse decresp = mock(DecisionResponse.class);
- when(trans.convertResponse(resp)).thenReturn(decresp);
+ lenient().when(trans.convertResponse(resp)).thenReturn(decresp);
Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
assertSame(decresp, result.getKey());
@@ -276,41 +277,41 @@ public class StdXacmlApplicationServiceProviderTest {
}
@Test
- public void testGetTranslator() {
+ void testGetTranslator() {
assertSame(trans, prov.getTranslator());
}
@Test
- public void testCreateEngine() throws FactoryException {
+ void testCreateEngine() throws FactoryException {
// success
prov.createEngine(null);
assertSame(engine, prov.getEngine());
// null - should be unchanged
- when(engineFactory.newEngine(any())).thenReturn(null);
+ lenient().when(engineFactory.newEngine(any())).thenReturn(null);
prov.createEngine(null);
assertSame(engine, prov.getEngine());
// exception - should be unchanged
- when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
+ lenient().when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
prov.createEngine(null);
assertSame(engine, prov.getEngine());
}
@Test
- public void testXacmlDecision() throws PDPException {
+ void testXacmlDecision() throws PDPException {
prov.createEngine(null);
// success
assertSame(resp, prov.xacmlDecision(req));
// exception
- when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
+ lenient().when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
assertNull(prov.xacmlDecision(req));
}
@Test
- public void testGetPdpEngineFactory() throws XacmlApplicationException {
+ void testGetPdpEngineFactory() throws XacmlApplicationException {
// use the real engine factory
engineFactory = null;
@@ -320,6 +321,12 @@ public class StdXacmlApplicationServiceProviderTest {
assertNotNull(prov.getEngine());
}
+ private void tryDeletePropFile() {
+ if (!PROP_FILE.delete()) {
+ logger.warn("{} not deleted", PROP_FILE);
+ }
+ }
+
private class MyProv extends StdXacmlApplicationServiceProvider {
@Override
diff --git a/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java b/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java
index 184db863..4cea61c6 100644
--- a/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java
+++ b/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020, 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 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.
@@ -75,19 +75,10 @@ public class GuardTranslator implements ToscaPolicyTranslator {
//
// common guard property fields
//
- public static final String FIELD_ACTOR = "actor";
- public static final String FIELD_OPERATION = "operation";
public static final String FIELD_CONTROLLOOP = "id";
public static final String FIELD_TIMERANGE = "timeRange";
//
- // frequency property fields
- //
- public static final String FIELD_TIMEWINDOW = "timeWindow";
- public static final String FIELD_TIMEUNITS = "timeUnits";
- public static final String FIELD_LIMIT = "limit";
-
- //
// minmax property fields
//
public static final String FIELD_TARGET = "target";
@@ -99,17 +90,6 @@ public class GuardTranslator implements ToscaPolicyTranslator {
//
public static final String FIELD_BLACKLIST = "blacklist";
- //
- // filter property fields
- //
- public static final String FIELD_FILTER_WHITELIST = "whitelist";
- public static final String FIELD_FILTER_ALGORITHM = "algorithm";
- public static final String FIELD_FILTER_FILTERS = "filters";
- public static final String FIELD_FILTER_FIELD = "field";
- public static final String FIELD_FILTER_FUNCTION = "function";
- public static final String FIELD_FILTER_FILTER = "filter";
- public static final String FIELD_FILTER_BLACKLIST = "blacklist";
-
public static final String POLICYTYPE_FREQUENCY = "onap.policies.controlloop.guard.common.FrequencyLimiter";
public static final String POLICYTYPE_MINMAX = "onap.policies.controlloop.guard.common.MinMax";
public static final String POLICYTYPE_BLACKLIST = "onap.policies.controlloop.guard.common.Blacklist";
@@ -286,7 +266,7 @@ public class GuardTranslator implements ToscaPolicyTranslator {
}
/**
- * Generate the targetType for the policy. Optional to add MatchType for the target. eg. the
+ * Generate the targetType for the policy. Optional to add MatchType for the target. e.g. the
* blacklist policy type uses the target in a different manner.
*
* @param properties TOSCA properties object
@@ -327,7 +307,6 @@ public class GuardTranslator implements ToscaPolicyTranslator {
return target;
}
- @SuppressWarnings("unchecked")
protected AllOfType addMatch(AllOfType allOf, Object value, Identifier attributeId) {
if (value instanceof String) {
if (".*".equals(value.toString())) {
@@ -350,8 +329,8 @@ public class GuardTranslator implements ToscaPolicyTranslator {
}
return allOf;
}
- if (value instanceof Collection) {
- ((Collection<String>) value).forEach(val -> {
+ if (value instanceof Collection<?> collection) {
+ collection.forEach(val -> {
var match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
XACML3.ID_FUNCTION_STRING_EQUAL,
val,
@@ -365,27 +344,6 @@ public class GuardTranslator implements ToscaPolicyTranslator {
return allOf;
}
- protected void addTimeRangeMatch(AllOfType allOf, TimeRange timeRange) {
-
- var matchStart = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_TIME_GREATER_THAN_OR_EQUAL,
- timeRange.getStartTime(),
- XACML3.ID_DATATYPE_TIME,
- XACML3.ID_ENVIRONMENT_CURRENT_TIME,
- XACML3.ID_ATTRIBUTE_CATEGORY_ENVIRONMENT);
-
- allOf.getMatch().add(matchStart);
-
- var matchEnd = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
- XACML3.ID_FUNCTION_TIME_LESS_THAN_OR_EQUAL,
- timeRange.getEndTime(),
- XACML3.ID_DATATYPE_TIME,
- XACML3.ID_ENVIRONMENT_CURRENT_TIME,
- XACML3.ID_ATTRIBUTE_CATEGORY_ENVIRONMENT);
-
- allOf.getMatch().add(matchEnd);
- }
-
protected VariableReferenceType createTimeRangeVariable(Map<String, Object> properties, PolicyType newPolicyType)
throws ToscaPolicyConversionException {
//
@@ -456,7 +414,7 @@ public class GuardTranslator implements ToscaPolicyTranslator {
FrequencyDefinition frequencyDef = ToscaPolicyTranslatorUtils.decodeProperties(toscaPolicy.getProperties(),
FrequencyDefinition.class);
//
- // See if its possible to generate a count
+ // See if it's possible to generate a count
//
String timeWindow = null;
if (frequencyDef.getTimeWindow() != null) {
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java
index d0541e2a..c1c072db 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/CoordinationGuardTranslatorTest.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.
@@ -25,30 +26,30 @@ package org.onap.policy.xacml.pdp.application.guard;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class CoordinationGuardTranslatorTest {
+class CoordinationGuardTranslatorTest {
@Test
- public void testUnsupportedMethods() {
+ void testUnsupportedMethods() {
CoordinationGuardTranslator translator = new CoordinationGuardTranslator();
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> translator.convertRequest(null))
- .withMessageContaining("this convertRequest shouldn't be used");
+ .isThrownBy(() -> translator.convertRequest(null))
+ .withMessageContaining("this convertRequest shouldn't be used");
assertThat(translator.convertResponse(null)).isNull();
}
@Test
- public void testLoadingDirectives() {
+ void testLoadingDirectives() {
assertThat(CoordinationGuardTranslator.loadCoordinationDirectiveFromFile(null)).isNull();
assertThat(CoordinationGuardTranslator.loadCoordinationDirectiveFromFile("nonexistent.yaml")).isNull();
CoordinationDirective directive = CoordinationGuardTranslator
- .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
+ .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
assertThat(directive).isNotNull();
assertThat(directive.getCoordinationFunction()).isEqualTo("whatisthisvaluesupposedtobe");
assertThat(directive.getControlLoop()).hasSize(2);
@@ -56,14 +57,14 @@ public class CoordinationGuardTranslatorTest {
}
@Test
- public void testGeneratingXacml() {
+ void testGeneratingXacml() {
CoordinationDirective directive = CoordinationGuardTranslator
- .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
+ .loadCoordinationDirectiveFromFile("src/test/resources/test-directive.yaml");
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> CoordinationGuardTranslator
- .generateXacmlFromCoordinationDirective(directive, "idontexist.yaml"))
- .withMessageContaining("Unable to find prototype ");
+ .isThrownBy(() -> CoordinationGuardTranslator
+ .generateXacmlFromCoordinationDirective(directive, "idontexist.yaml"))
+ .withMessageContaining("Unable to find prototype ");
}
}
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java
index 31e576ff..a11f19d8 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,28 +28,26 @@ import static org.assertj.core.api.Assertions.assertThatCode;
import com.att.research.xacml.api.Response;
import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
+import java.nio.file.Path;
import java.sql.Date;
import java.time.Instant;
import java.time.OffsetDateTime;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.UUID;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -66,47 +64,46 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class GuardPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class GuardPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
private static DecisionRequest requestVfCount;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static EntityManager em;
+ private static EntityManagerFactory emf;
private static final String DENY = "Deny";
private static final String PERMIT = "Permit";
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
LOGGER.info("Setting up class");
//
- // Setup our temporary folder
+ // Set up our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties", properties,
- myCreator);
+ myCreator);
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Find the guard service application and save for use in all the tests
//
StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -132,33 +129,35 @@ public class GuardPdpApplicationTest {
// Load Decision Requests
//
requestVfCount =
- gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
- DecisionRequest.class);
+ gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
+ DecisionRequest.class);
//
// Create EntityManager for manipulating DB
//
String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
- em = Persistence
- .createEntityManagerFactory(GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties)
- .createEntityManager();
+ emf = Persistence.createEntityManagerFactory(
+ GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties);
+ em = emf.createEntityManager();
}
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() throws Exception {
+ @AfterAll
+ static void cleanup() {
if (em != null) {
em.close();
}
+ if (emf != null) {
+ emf.close();
+ }
}
/**
* Clears the database before each test so there are no operations in it.
- *
*/
- @Before
- public void startClean() throws Exception {
+ @BeforeEach
+ void startClean() {
em.getTransaction().begin();
em.createQuery("DELETE FROM OperationsHistory").executeUpdate();
em.getTransaction().commit();
@@ -169,9 +168,8 @@ public class GuardPdpApplicationTest {
*
* @param expected from the response
* @param response received
- *
**/
- public void checkDecision(String expected, DecisionResponse response) throws CoderException {
+ void checkDecision(String expected, DecisionResponse response) throws CoderException {
LOGGER.info("Looking for {} Decision", expected);
assertThat(response).isNotNull();
assertThat(response.getStatus()).isNotNull();
@@ -191,11 +189,10 @@ public class GuardPdpApplicationTest {
/**
* Request a decision and check that it matches expectation.
*
- * @param request to send to Xacml PDP
+ * @param request to send to Xacml PDP
* @param expected from the response
- *
**/
- public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
+ void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
//
// Ask for a decision
//
@@ -207,7 +204,7 @@ public class GuardPdpApplicationTest {
}
@Test
- public void test1Basics() throws CoderException, IOException {
+ void test1Basics() {
LOGGER.info("**************** Running test1Basics ****************");
//
// Make sure there's an application name
@@ -225,37 +222,36 @@ public class GuardPdpApplicationTest {
assertThat(service.supportedPolicyTypes()).isNotEmpty();
assertThat(service.supportedPolicyTypes()).hasSize(5);
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.0")))
- .isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.0")))
+ .isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.1")))
- .isFalse();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.1")))
+ .isFalse();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.1"))).isFalse();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.1"))).isFalse();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
+ "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
+ "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier("onap.foo", "1.0.1"))).isFalse();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Filter", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Filter", "1.0.0"))).isTrue();
}
@Test
- public void test2NoPolicies() throws CoderException {
+ void test2NoPolicies() {
LOGGER.info("**************** Running test2NoPolicies ****************");
assertThatCode(() -> requestAndCheckDecision(requestVfCount, PERMIT)).doesNotThrowAnyException();
}
@Test
- public void test3FrequencyLimiter()
- throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
+ void test3FrequencyLimiter() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running test3FrequencyLimiter ****************");
//
// Now load the vDNS frequency limiter Policy - make sure
@@ -263,7 +259,7 @@ public class GuardPdpApplicationTest {
// into the PDP.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("policies/vDNS.policy.guard.frequencylimiter.input.tosca.yaml", service);
+ TestUtils.loadPolicies("policies/vDNS.policy.guard.frequencylimiter.input.tosca.yaml", service);
assertThat(loadedPolicies).hasSize(1);
assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.frequency.scaleout");
//
@@ -282,7 +278,7 @@ public class GuardPdpApplicationTest {
@SuppressWarnings("unchecked")
@Test
- public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
+ void test4MinMax() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running test4MinMax ****************");
//
// Now load the vDNS min max Policy - make sure
@@ -290,7 +286,7 @@ public class GuardPdpApplicationTest {
// into the PDP.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("policies/vDNS.policy.guard.minmaxvnfs.input.tosca.yaml", service);
+ TestUtils.loadPolicies("policies/vDNS.policy.guard.minmaxvnfs.input.tosca.yaml", service);
assertThat(loadedPolicies).hasSize(1);
assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.minmax.scaleout");
//
@@ -327,13 +323,13 @@ public class GuardPdpApplicationTest {
@SuppressWarnings("unchecked")
@Test
- public void test5Blacklist() throws CoderException, XacmlApplicationException {
+ void test5Blacklist() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running test5Blacklist ****************");
//
// Load the blacklist policy in with the others.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("policies/vDNS.policy.guard.blacklist.input.tosca.yaml", service);
+ TestUtils.loadPolicies("policies/vDNS.policy.guard.blacklist.input.tosca.yaml", service);
assertThat(loadedPolicies).hasSize(1);
assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.blacklist.scaleout");
//
@@ -344,7 +340,7 @@ public class GuardPdpApplicationTest {
// vfcount=1 between min of 1 and max of 2: change the
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("target",
- "the-vfmodule-where-root-is-true");
+ "the-vfmodule-where-root-is-true");
//
// vfcount=0 below min of 1: should get a Deny because target IS blacklisted
//
@@ -353,7 +349,7 @@ public class GuardPdpApplicationTest {
// vfcount=1 between min of 1 and max of 2: change the
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("target",
- "another-vfmodule-where-root-is-true");
+ "another-vfmodule-where-root-is-true");
//
// vfcount=0 below min of 1: should get a Deny because target IS blacklisted
//
@@ -362,14 +358,14 @@ public class GuardPdpApplicationTest {
@SuppressWarnings("unchecked")
@Test
- public void test6Filters() throws Exception {
+ void test6Filters() throws Exception {
LOGGER.info("**************** Running test6Filters ****************");
//
// Re-Load Decision Request - so we can start from scratch
//
requestVfCount =
- gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
- DecisionRequest.class);
+ gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
+ DecisionRequest.class);
//
// Ensure we are a permit to start
//
@@ -378,7 +374,7 @@ public class GuardPdpApplicationTest {
// Load the filter policy in with the others.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("src/test/resources/test.policy.guard.filters.yaml", service);
+ TestUtils.loadPolicies("src/test/resources/test.policy.guard.filters.yaml", service);
assertThat(loadedPolicies).hasSize(2);
//
// Although the region is blacklisted, the id is not
@@ -388,7 +384,7 @@ public class GuardPdpApplicationTest {
// Put in a different vnf id
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
- "different-vnf-id-should-be-denied");
+ "different-vnf-id-should-be-denied");
//
// The region is blacklisted, and the id is not allowed
//
@@ -397,7 +393,7 @@ public class GuardPdpApplicationTest {
// Let's switch to a different region
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("cloud-region.cloud-region-id",
- "RegionTwo");
+ "RegionTwo");
//
// The region is whitelisted, and the id is also allowed
//
@@ -406,7 +402,7 @@ public class GuardPdpApplicationTest {
// Put in a blacklisted vnf id
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
- "f17face5-69cb-4c88-9e0b-7426db7edddd");
+ "f17face5-69cb-4c88-9e0b-7426db7edddd");
//
// Although region is whitelisted, the id is blacklisted
//
@@ -415,7 +411,7 @@ public class GuardPdpApplicationTest {
// Let's switch to a different region
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("cloud-region.cloud-region-id",
- "RegionThree");
+ "RegionThree");
//
// There is no filter for this region, but the id is still blacklisted
//
@@ -424,7 +420,7 @@ public class GuardPdpApplicationTest {
// Put in a different vnf id
//
((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
- "different-vnf-id-should-be-permitted");
+ "different-vnf-id-should-be-permitted");
//
// There is no filter for this region, and the id is not blacklisted
//
@@ -432,19 +428,19 @@ public class GuardPdpApplicationTest {
}
@Test
- public void test7TimeInRange() throws Exception {
+ void test7TimeInRange() throws Exception {
LOGGER.info("**************** Running test7TimeInRange ****************");
//
// Re-Load Decision Request - so we can start from scratch
//
DecisionRequest requestInRange =
- gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.timeinrange.json"),
- DecisionRequest.class);
+ gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.timeinrange.json"),
+ DecisionRequest.class);
//
// Load the test policy in with the others.
//
List<ToscaPolicy> loadedPolicies =
- TestUtils.loadPolicies("src/test/resources/test-time-in-range.yaml", service);
+ TestUtils.loadPolicies("src/test/resources/test-time-in-range.yaml", service);
assertThat(loadedPolicies).hasSize(1);
//
// Mock what the current date and time is. Set to 12 Noon
@@ -497,20 +493,20 @@ public class GuardPdpApplicationTest {
//
// Get the properties
//
- Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
- assertThat(properties).isNotNull();
+ Map<String, Object> localProps = (Map<String, Object>) request.getResource().get("guard");
+ assertThat(localProps).isNotNull();
//
// Add an entry
//
OperationsHistory newEntry = new OperationsHistory();
- newEntry.setActor(properties.get("actor").toString());
- newEntry.setOperation(properties.get("operation").toString());
- newEntry.setClosedLoopName(properties.get("clname").toString());
+ newEntry.setActor(localProps.get("actor").toString());
+ newEntry.setOperation(localProps.get("operation").toString());
+ newEntry.setClosedLoopName(localProps.get("clname").toString());
newEntry.setOutcome("SUCCESS");
newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
newEntry.setEndtime(Date.from(Instant.now()));
newEntry.setRequestId(UUID.randomUUID().toString());
- newEntry.setTarget(properties.get("target").toString());
+ newEntry.setTarget(localProps.get("target").toString());
LOGGER.info("Inserting {}", newEntry);
em.getTransaction().begin();
em.persist(newEntry);
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java
index 1c925ce2..4b21bf38 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardPolicyRequestTest.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.
@@ -27,16 +28,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
-public class GuardPolicyRequestTest {
+class GuardPolicyRequestTest {
@Test
- public void testAnomalies() throws ToscaPolicyConversionException {
+ void testAnomalies() throws ToscaPolicyConversionException {
DecisionRequest decisionRequest = new DecisionRequest();
assertThat(GuardPolicyRequest.createInstance(decisionRequest)).isNotNull();
@@ -95,12 +96,12 @@ public class GuardPolicyRequestTest {
}
@Test
- public void testFilterResources() throws Exception {
+ void testFilterResources() throws Exception {
StandardCoder gson = new StandardCoder();
DecisionRequest request = gson.decode(
- TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.filter.json"),
- DecisionRequest.class);
+ TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.filter.json"),
+ DecisionRequest.class);
GuardPolicyRequest guardRequest = GuardPolicyRequest.createInstance(request);
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java
index ac36ec72..d80d85b1 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
+ * Modifications Copyright (C) 2020, 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.
@@ -43,7 +43,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -58,26 +58,26 @@ import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionExcepti
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class GuardTranslatorTest {
+class GuardTranslatorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GuardTranslatorTest.class);
private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
- private GuardTranslator translator = new GuardTranslator();
+ private final GuardTranslator translator = new GuardTranslator();
@Test
- public void testRequest() throws Exception {
+ void testRequest() throws Exception {
DecisionRequest decisionRequest = gson.decode(
- TextFileUtils.getTextFileAsString(
- "src/test/resources/requests/guard.vfCount.json"),
- DecisionRequest.class);
+ TextFileUtils.getTextFileAsString(
+ "src/test/resources/requests/guard.vfCount.json"),
+ DecisionRequest.class);
Request xacmlRequest = translator.convertRequest(decisionRequest);
assertThat(xacmlRequest).isNotNull();
}
@Test
- public void testResponse() {
+ void testResponse() {
StdStatus status = new StdStatus(StdStatusCode.STATUS_CODE_OK);
StdMutableResult result = new StdMutableResult(Decision.PERMIT, status);
StdMutableResponse response = new StdMutableResponse(result);
@@ -101,7 +101,7 @@ public class GuardTranslatorTest {
@Test
- public void testBadPolicies() throws Exception {
+ void testBadPolicies() throws Exception {
String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/test-bad-policies.yaml");
//
// Serialize it into a class
@@ -127,7 +127,7 @@ public class GuardTranslatorTest {
name2message.put("blacklist-noblacklist", "item \"blacklist\"");
name2message.put("filter-noalgorithm", "item \"algorithm\"");
name2message.put("filter-badalgorithm",
- "Unexpected value for algorithm, should be whitelist-overrides or blacklist-overrides");
+ "Unexpected value for algorithm, should be whitelist-overrides or blacklist-overrides");
name2message.put("filter-nofilter", "item \"filters\"");
name2message.put("filter-nocollection", "Cannot decode FilterDefinition");
name2message.put("filter-noarray", "Cannot decode FilterDefinition");
@@ -142,7 +142,7 @@ public class GuardTranslatorTest {
//
for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
for (ToscaPolicy policy : policies.values()) {
- LOGGER.info("Testing policy " + policy.getName());
+ LOGGER.info("Testing policy {}", policy.getName());
String expectedMsg = name2message.get(policy.getName());
assertThat(expectedMsg).as(policy.getName()).isNotNull();
@@ -154,7 +154,7 @@ public class GuardTranslatorTest {
}
@Test
- public void testPolicyConversion() throws Exception {
+ void testPolicyConversion() throws Exception {
String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/test-policies.yaml");
//
// Serialize it into a class
@@ -198,13 +198,13 @@ public class GuardTranslatorTest {
// Validate each policy type
//
if (GuardTranslator.POLICYTYPE_FREQUENCY.equals(policy.getType())) {
- validateFrequency(policy, xacmlPolicy);
+ validateFrequency(xacmlPolicy);
} else if (GuardTranslator.POLICYTYPE_MINMAX.equals(policy.getType())) {
validateMinMax(policy, xacmlPolicy);
} else if (GuardTranslator.POLICYTYPE_BLACKLIST.equals(policy.getType())) {
validateBlacklist(policy, xacmlPolicy);
} else if (GuardTranslator.POLICYTYPE_FILTER.equals(policy.getType())) {
- validateFilter(policy, xacmlPolicy);
+ validateFilter(xacmlPolicy);
}
}
}
@@ -213,11 +213,11 @@ public class GuardTranslatorTest {
testPol.setProperties(new LinkedHashMap<>());
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> translator.convertPolicy(testPol));
+ .isThrownBy(() -> translator.convertPolicy(testPol));
testPol.setProperties(null);
assertThatExceptionOfType(ToscaPolicyConversionException.class)
- .isThrownBy(() -> translator.convertPolicy(testPol));
+ .isThrownBy(() -> translator.convertPolicy(testPol));
}
private void validateCommon(ToscaPolicy policy, PolicyType xacmlPolicy) {
@@ -225,7 +225,6 @@ public class GuardTranslatorTest {
boolean foundOperation = false;
boolean foundTarget = false;
boolean foundControlLoop = false;
- //boolean foundTimeRange = false;
assertThat(xacmlPolicy.getTarget()).isNotNull();
assertThat(xacmlPolicy.getTarget().getAnyOf()).isNotEmpty();
@@ -238,11 +237,11 @@ public class GuardTranslatorTest {
// These fields are required
//
if (ToscaDictionary.ID_RESOURCE_GUARD_ACTOR.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(match.getAttributeValue().getContent()).isNotNull();
foundActor = true;
} else if (ToscaDictionary.ID_RESOURCE_GUARD_RECIPE.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(match.getAttributeValue().getContent()).isNotNull();
foundOperation = true;
} else {
@@ -250,22 +249,16 @@ public class GuardTranslatorTest {
// These fields are optional
//
if (ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties()).containsKey("target");
foundTarget = true;
}
if (ToscaDictionary.ID_RESOURCE_GUARD_CLNAME.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_CONTROLLOOP);
foundControlLoop = true;
}
- /*
- if (XACML3.ID_ENVIRONMENT_CURRENT_TIME.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
- assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_TIMERANGE);
- foundTimeRange = true;
- }
- */
+
}
}
}
@@ -283,9 +276,9 @@ public class GuardTranslatorTest {
}
}
- private void validateFrequency(ToscaPolicy policy, PolicyType xacmlPolicy) {
+ private void validateFrequency(PolicyType xacmlPolicy) {
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
assertThat(((RuleType) rule).getCondition()).isNotNull();
@@ -297,7 +290,7 @@ public class GuardTranslatorTest {
boolean foundTarget = false;
boolean foundMinOrMax = false;
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
for (AnyOfType anyOf : ((RuleType) rule).getTarget().getAnyOf()) {
@@ -306,13 +299,13 @@ public class GuardTranslatorTest {
assertThat(allOf.getMatch()).isNotEmpty();
for (MatchType match : allOf.getMatch()) {
if (ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties()).containsKey(GuardTranslator.FIELD_TARGET);
foundTarget = true;
} else if (ToscaDictionary.ID_RESOURCE_GUARD_VFCOUNT.toString().equals(
- match.getAttributeDesignator().getAttributeId())) {
+ match.getAttributeDesignator().getAttributeId())) {
assertThat(policy.getProperties().keySet()).containsAnyOf(GuardTranslator.FIELD_MIN,
- GuardTranslator.FIELD_MAX);
+ GuardTranslator.FIELD_MAX);
foundMinOrMax = true;
}
}
@@ -325,7 +318,7 @@ public class GuardTranslatorTest {
private void validateBlacklist(ToscaPolicy policy, PolicyType xacmlPolicy) {
boolean foundBlacklist = false;
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
assertThat(((RuleType) rule).getTarget()).isNotNull();
@@ -337,7 +330,7 @@ public class GuardTranslatorTest {
assertThat(allOf.getMatch()).hasSize(1);
for (MatchType match : allOf.getMatch()) {
assertThat(match.getAttributeDesignator().getAttributeId())
- .isEqualTo(ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString());
+ .isEqualTo(ToscaDictionary.ID_RESOURCE_GUARD_TARGETID.toString());
assertThat(match.getAttributeValue().getContent()).containsAnyOf("vnf1", "vnf2");
//
// This just checks that policy did have a blacklist in it.
@@ -351,10 +344,10 @@ public class GuardTranslatorTest {
assertThat(foundBlacklist).isTrue();
}
- private void validateFilter(ToscaPolicy policy, PolicyType xacmlPolicy) {
+ private void validateFilter(PolicyType xacmlPolicy) {
assertThat(xacmlPolicy.getRuleCombiningAlgId()).endsWith("-overrides");
for (Object rule : xacmlPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) {
- if (! (rule instanceof RuleType)) {
+ if (!(rule instanceof RuleType)) {
continue;
}
assertThat(((RuleType) rule).getTarget()).isNotNull();
diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java
index 4e7bb12f..5d19a905 100644
--- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java
+++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/SonCoordinationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,25 +27,24 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.io.File;
-import java.io.IOException;
+import java.nio.file.Path;
import java.time.Instant;
import java.util.Date;
-import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.UUID;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -60,36 +59,37 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class SonCoordinationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class SonCoordinationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SonCoordinationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
private static DecisionRequest requestVpciNode1;
private static DecisionRequest requestVsonhNode1;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static EntityManager em;
+ private static EntityManagerFactory emf;
private static final String DENY = "Deny";
private static final String PERMIT = "Permit";
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
LOGGER.info("Setting up class");
//
- // Setup our temporary folder
+ // Set up our temporary folder
//
XacmlPolicyUtils.FileCreator myCreator =
- (String filename) -> policyFolder.newFile(filename);
+ (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
"src/test/resources/xacml.properties", properties, myCreator);
//
@@ -102,9 +102,7 @@ public class SonCoordinationTest {
//
StringBuilder strDump =
new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -138,18 +136,16 @@ public class SonCoordinationTest {
"src/test/resources/requests/coordination.cl.vSonh.node.1.json"),
DecisionRequest.class);
String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
- em = Persistence
- .createEntityManagerFactory(SonCoordinationTest.properties.getProperty(persistenceUnit),
- properties)
- .createEntityManager();
+ emf = Persistence.createEntityManagerFactory(
+ SonCoordinationTest.properties.getProperty(persistenceUnit), properties);
+ em = emf.createEntityManager();
}
/**
* Clears the database before each test.
- *
*/
- @Before
- public void startClean() throws Exception {
+ @BeforeEach
+ void startClean() {
em.getTransaction().begin();
em.createQuery("DELETE FROM OperationsHistory").executeUpdate();
em.getTransaction().commit();
@@ -158,11 +154,14 @@ public class SonCoordinationTest {
/**
* Close the entity manager.
*/
- @AfterClass
- public static void cleanup() throws Exception {
+ @AfterAll
+ static void cleanup() {
if (em != null) {
em.close();
}
+ if (emf != null) {
+ emf.close();
+ }
}
/**
@@ -170,9 +169,8 @@ public class SonCoordinationTest {
*
* @param expected from the response
* @param response received
- *
**/
- public void checkDecision(String expected, DecisionResponse response) throws CoderException {
+ void checkDecision(String expected, DecisionResponse response) throws CoderException {
LOGGER.info("Looking for {} Decision", expected);
assertThat(response).isNotNull();
assertThat(response.getStatus()).isNotNull();
@@ -186,11 +184,10 @@ public class SonCoordinationTest {
/**
* Request a decision and check that it matches expectation.
*
- * @param request to send to Xacml PDP
+ * @param request to send to Xacml PDP
* @param expected from the response
- *
**/
- public void requestAndCheckDecision(DecisionRequest request, String expected)
+ void requestAndCheckDecision(DecisionRequest request, String expected)
throws CoderException {
//
@@ -204,7 +201,7 @@ public class SonCoordinationTest {
}
@Test
- public void test1() throws CoderException, IOException, XacmlApplicationException {
+ void test1() throws CoderException, XacmlApplicationException {
LOGGER.info("**************** Running vPci and vSonh Control Loops ****************");
//
// Now load the test coordination policy - make sure
@@ -228,7 +225,7 @@ public class SonCoordinationTest {
//
// Open vSonh on node1
//
- long vsonhId = insertOperationEvent(requestVsonhNode1, "Started");
+ long vsonhId = insertOperationEvent(requestVsonhNode1);
//
// Under current coordination policy vPci should get a deny
//
@@ -244,7 +241,7 @@ public class SonCoordinationTest {
//
// Open vPci on node1
//
- long vpciId = insertOperationEvent(requestVpciNode1, "Started");
+ long vpciId = insertOperationEvent(requestVpciNode1);
//
// Under current coordination policy vSonh should get a deny
//
@@ -260,23 +257,23 @@ public class SonCoordinationTest {
}
@SuppressWarnings("unchecked")
- private long insertOperationEvent(DecisionRequest request, String outcome) {
+ private long insertOperationEvent(DecisionRequest request) {
//
// Get the properties
//
- Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
+ Map<String, Object> localProps = (Map<String, Object>) request.getResource().get("guard");
//
// Add an entry
//
OperationsHistory newEntry = new OperationsHistory();
- newEntry.setActor(properties.get("actor").toString());
- newEntry.setOperation(properties.get("operation").toString());
- newEntry.setClosedLoopName(properties.get("clname").toString());
- newEntry.setOutcome(outcome);
+ newEntry.setActor(localProps.get("actor").toString());
+ newEntry.setOperation(localProps.get("operation").toString());
+ newEntry.setClosedLoopName(localProps.get("clname").toString());
+ newEntry.setOutcome("Started");
newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
newEntry.setEndtime(Date.from(Instant.now()));
newEntry.setRequestId(UUID.randomUUID().toString());
- newEntry.setTarget(properties.get("target").toString());
+ newEntry.setTarget(localProps.get("target").toString());
em.getTransaction().begin();
em.persist(newEntry);
em.getTransaction().commit();
@@ -284,7 +281,6 @@ public class SonCoordinationTest {
}
private void updateOperationEvent(long id, String outcome) {
-
OperationsHistory updateEntry = em.find(OperationsHistory.class, id);
updateEntry.setOutcome(outcome);
updateEntry.setEndtime(Date.from(Instant.now()));
diff --git a/applications/match/pom.xml b/applications/match/pom.xml
index 396236d8..5c8d40e9 100644
--- a/applications/match/pom.xml
+++ b/applications/match/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy Engine - XACML PDP
================================================================================
Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -35,11 +35,6 @@
<dependencies>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
diff --git a/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java b/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java
index b022bca1..904cc252 100644
--- a/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java
+++ b/applications/match/src/test/java/org/onap/policy/xacml/pdp/application/match/MatchPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,21 +27,19 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -56,52 +54,52 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class MatchPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class MatchPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(MatchPdpApplicationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static DecisionRequest baseRequest;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ static void setUp() throws Exception {
//
// Load Single Decision Request
//
baseRequest = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.match.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.match.input.json"),
+ DecisionRequest.class);
//
// Setup our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ properties, myCreator);
//
// Copy the test policy types into data area
//
String policy = "onap.policies.match.Test";
String policyType = ResourceUtils.getResourceAsString("src/test/resources/" + policy + ".yaml");
LOGGER.info("Copying {}", policyType);
- Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
- policyType.getBytes());
+ Files.write(Paths.get(policyFolder.toFile().getAbsolutePath(), policy + "-1.0.0.yaml"),
+ policyType.getBytes());
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Iterate through Xacml application services and find
// the optimization service. Save it for use throughout
@@ -134,7 +132,7 @@ public class MatchPdpApplicationTest {
}
@Test
- public void test01Basics() {
+ void test01Basics() {
//
// Make sure there's an application name
//
@@ -149,13 +147,13 @@ public class MatchPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.match.Test", "1.0.0"))).isTrue();
+ "onap.policies.match.Test", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.foobar", "1.0.0"))).isFalse();
+ "onap.foobar", "1.0.0"))).isFalse();
}
@Test
- public void test02NoPolicies() throws CoderException {
+ void test02NoPolicies() throws CoderException {
//
// Ask for a decision when there are no policies loaded
//
@@ -168,7 +166,7 @@ public class MatchPdpApplicationTest {
}
@Test
- public void test03Match() throws CoderException, FileNotFoundException, IOException,
+ void test03Match() throws
XacmlApplicationException {
//
// Now load all the test match policies
@@ -208,7 +206,7 @@ public class MatchPdpApplicationTest {
//
// Validate it
//
- validateDecision(response, baseRequest, "value1");
+ validateDecision(response, "value1");
//
// Ask for bar
//
@@ -222,7 +220,7 @@ public class MatchPdpApplicationTest {
//
// Validate it
//
- validateDecision(response, baseRequest, "value2");
+ validateDecision(response, "value2");
//
// Ask for hello (should return nothing)
//
@@ -246,7 +244,7 @@ public class MatchPdpApplicationTest {
}
@SuppressWarnings("unchecked")
- private void validateDecision(DecisionResponse decision, DecisionRequest request, String value) {
+ private void validateDecision(DecisionResponse decision, String value) {
for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
assertThat(entrySet.getValue()).isInstanceOf(Map.class);
diff --git a/applications/monitoring/src/test/java/cucumber/RunCucumberTest.java b/applications/monitoring/src/test/java/cucumber/RunCucumberTest.java
deleted file mode 100644
index f0b9d7f5..00000000
--- a/applications/monitoring/src/test/java/cucumber/RunCucumberTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package cucumber;
-
-import io.cucumber.junit.Cucumber;
-import io.cucumber.junit.CucumberOptions;
-import org.junit.runner.RunWith;
-
-@RunWith(Cucumber.class)
-@CucumberOptions()
-public class RunCucumberTest {
-} \ No newline at end of file
diff --git a/applications/monitoring/src/test/java/cucumber/Stepdefs.java b/applications/monitoring/src/test/java/cucumber/Stepdefs.java
deleted file mode 100644
index 0a1d333a..00000000
--- a/applications/monitoring/src/test/java/cucumber/Stepdefs.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package cucumber;
-
-import com.att.research.xacml.std.annotations.XACMLAction;
-import com.att.research.xacml.std.annotations.XACMLRequest;
-import com.att.research.xacml.std.annotations.XACMLResource;
-import com.att.research.xacml.std.annotations.XACMLSubject;
-import io.cucumber.java.en.Given;
-import io.cucumber.java.en.Then;
-import io.cucumber.java.en.When;
-import org.junit.ClassRule;
-import org.junit.rules.TemporaryFolder;
-
-public class Stepdefs {
-
- /*
-
- private static final Logger logger = LoggerFactory.getLogger(Stepdefs.class);
-
- public static OnapXacmlPdpEngine onapPdpEngine;
- public static Properties properties;
- public static Map<String, Object> tcaPolicy;
- public static Request request;
- public static File pathProperties;
- public static File pathRootPolicy;
-
- /**
- * Temporary folder where we will store newly created policies.
- */
- @ClassRule
- public TemporaryFolder policyFolder = new TemporaryFolder();
-
- /**
- * This is a simple annotation class to simulate
- * requests coming in.
- */
- @XACMLRequest(ReturnPolicyIdList = true)
- public class MyXacmlRequest {
-
- @XACMLSubject(includeInResults = true)
- String onapName = "DCAE";
-
- @XACMLResource(includeInResults = true)
- String resource = "onap.policies.Monitoring";
-
- @XACMLAction()
- String action = "configure";
- }
-
- /**
- * Initialization.
- */
- @Given("Initialization")
- public void initialization() {
- /*
- //
- // Everything initializes upon startup
- //
- assertThatCode(() -> {
- //
- // Assume XACML REST Controller loads PDP engine
- //
- onapPdpEngine = new OnapXacmlPdpEngine();
- //
- // Come up with defaults
- //
- File path = Paths.get("src/test/resources").toFile();
- /*
- // try (InputStream is = new FileInputStream("src/test/resources/xacml.properties")) {
- // properties = new Properties();
- // properties.load(is);
- // onapPdpEngine.initializeEngine(properties);
-// }
- onapPdpEngine.initialize(path.toPath());
- //
- // Store the properties in new path
- //
- // JUNIT IS CRASHING - THE TEMP FOLDER NOT CREATED -->
- //pathProperties = policyFolder.newFile("xacml.properties");
- //
- // Store the root policies
- //
- for (String rootPolicyId : XACMLProperties.getRootPolicyIDs(properties)) {
- logger.debug("Root policy id: " + rootPolicyId);
- }
-
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @When("Decision Requested")
- public void decision_Requested() {
- /*
- //
- // Simulate a request coming in from Xacml REST server
- //
- assertThatCode(() -> {
- request = RequestParser.parseRequest(new MyXacmlRequest());
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @Then("Decision Permit {int} Obligations")
- public void decision_Permit_Obligations(Integer int1) {
- /*
- Response response = onapPdpEngine.decision(request);
- for (Result result : response.getResults()) {
- logger.debug(result.getDecision().toString());
- assertEquals(Decision.PERMIT, result.getDecision());
- assertThat(result.getObligations().size()).isEqualTo(int1);
- }
- */
- }
-
- /**
- * Initialization.
- */
- @When("The application gets new Tosca Policy")
- public void the_application_gets_new_Tosca_Policy() {
- /*
- //
- // The Xacml PDP REST controller Would receive this from the PAP
- //
- // And then parse it looking for Policy Types
- //
- assertThatCode(() -> {
- try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.input.yaml")) {
- Yaml yaml = new Yaml();
- tcaPolicy = yaml.load(is);
- //
- // Do we test iterating and determining if supported?
- //
-
- }
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @Then("Load Policy")
- public void load_Policy() {
- /*
- assertThatCode(() -> {
- //
- // Load the policies
- //
- List<PolicyType> convertedPolicies = onapPdpEngine.convertPolicies(tcaPolicy);
- //
- // Store these in temporary folder
- //
- int id = 1;
- List<Path> newReferencedPolicies = new ArrayList<>();
- for (PolicyType convertedPolicy : convertedPolicies) {
- //
- // I don't think we should use the policy id as the filename - there could
- // possibly be duplicates. eg. Not guaranteed to be unique.
- //
- File file = policyFolder.newFile("policy." + id + convertedPolicy.getPolicyId() + ".xml");
- logger.info("Creating Policy {}", file.getAbsolutePath());
- Path path = XACMLPolicyWriter.writePolicyFile(file.toPath(), convertedPolicy);
- //
- // Add it to our list
- //
- newReferencedPolicies.add(path);
- }
- //
- // Now updated the properties
- //
- Path[] args = new Path[newReferencedPolicies.size()];
- newReferencedPolicies.toArray(args);
- XACMLProperties.setXacmlReferencedProperties(properties, args);
- //
- // Reload the PDP engine
- //
- onapPdpEngine.initializeEngine(properties);
- }).doesNotThrowAnyException();
- */
- }
-
- /**
- * Initialization.
- */
- @Then("Save Configuration")
- public void save_Configuration() {
- /*
- assertThatCode(() -> {
- //
- // Save the configuration
- //
- onapPdpEngine.storeXacmlProperties(pathProperties.getAbsolutePath());
- }).doesNotThrowAnyException();
- */
- }
-}
diff --git a/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java b/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java
index b4a5579e..9debb6b1 100644
--- a/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java
+++ b/applications/monitoring/src/test/java/org/onap/policy/xacml/pdp/application/monitoring/MonitoringPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,18 +27,18 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import java.io.File;
+import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -53,8 +53,8 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class MonitoringPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class MonitoringPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
private static final Properties properties = new Properties();
@@ -64,40 +64,40 @@ public class MonitoringPdpApplicationTest {
private static final StandardCoder gson = new StandardCoder();
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
//
// Load Single Decision Request
//
requestSinglePolicy = gson.decode(
- TextFileUtils
- .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
+ DecisionRequest.class);
// Load Single Decision Request
//
requestPolicyType = gson.decode(
- TextFileUtils
+ TextFileUtils
.getTextFileAsString("../../main/src/test/resources/decisions/decision.policytype.input.json"),
- DecisionRequest.class);
+ DecisionRequest.class);
//
- // Setup our temporary folder
+ // Set up our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = policyFolder::newFile;
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
properties, myCreator);
//
// Load XacmlApplicationServiceProvider service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Look for our class instance and save it
//
@@ -127,7 +127,7 @@ public class MonitoringPdpApplicationTest {
}
@Test
- public void test1Basics() {
+ void test1Basics() {
//
// Make sure there's an application name
//
@@ -137,17 +137,17 @@ public class MonitoringPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
+ new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "2.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier(
+ new ToscaConceptIdentifier(
"onap.policies.monitoring.foobar", "1.0.1"))).isTrue();
assertThat(service.canSupportPolicyType(
new ToscaConceptIdentifier(
"onap.policies.monitoring.foobar", "2.0.1"))).isTrue();
assertThat(service.canSupportPolicyType(
- new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
+ new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
//
// Ensure it supports decisions
//
@@ -155,7 +155,7 @@ public class MonitoringPdpApplicationTest {
}
@Test
- public void test2NoPolicies() {
+ void test2NoPolicies() {
//
// Ask for a decision
//
@@ -189,28 +189,28 @@ public class MonitoringPdpApplicationTest {
}
@Test
- public void tes3AddvDnsPolicy() throws CoderException, XacmlApplicationException {
+ void tes3AddvDnsPolicy() throws CoderException, XacmlApplicationException {
testAddPolicy("src/test/resources/vDNS.policy.input.yaml",
"onap.policies.monitoring.cdap.tca.hi.lo.app",
"onap.scaleout.tca");
}
@Test
- public void tes4AddvFirewall1Policy() throws CoderException, XacmlApplicationException {
+ void tes4AddvFirewall1Policy() throws CoderException, XacmlApplicationException {
testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.yaml",
"onap.policies.monitoring.tcagen2",
"onap.vfirewall.tca");
}
@Test
- public void tes5AddvFirewall2Policy() throws CoderException, XacmlApplicationException {
+ void tes5AddvFirewall2Policy() throws CoderException, XacmlApplicationException {
testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.v2.yaml",
"onap.policies.monitoring.tcagen2",
"onap.vfirewall.tca");
}
@SuppressWarnings("unchecked")
- public void testAddPolicy(String policyResource, String policyType, String policyId)
+ void testAddPolicy(String policyResource, String policyType, String policyId)
throws CoderException, XacmlApplicationException {
//
// Now load the vDNS Policy - make sure
diff --git a/applications/naming/pom.xml b/applications/naming/pom.xml
index a7409019..61fdd2dc 100644
--- a/applications/naming/pom.xml
+++ b/applications/naming/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy Engine - XACML PDP
================================================================================
Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -35,11 +35,6 @@
<dependencies>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
diff --git a/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java b/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java
index aa8fde41..deeee2f5 100644
--- a/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java
+++ b/applications/naming/src/test/java/org/onap/policy/xacml/pdp/application/naming/NamingPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,25 +27,22 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.att.research.xacml.api.Response;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.Arrays;
import java.util.Collection;
-import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
import org.assertj.core.api.Condition;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -60,61 +57,53 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class NamingPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class NamingPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(NamingPdpApplicationTest.class);
- private static Properties properties = new Properties();
- private static File propertiesFile;
+ private static final Properties properties = new Properties();
private static XacmlApplicationServiceProvider service;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static DecisionRequest baseRequest;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ static void setUp() throws Exception {
//
// Load Single Decision Request
//
baseRequest = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.naming.input.json"),
- DecisionRequest.class);
- //
- // Setup our temporary folder
- //
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
- propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.naming.input.json"),
+ DecisionRequest.class);
+
//
// Copy the test policy types into data area
//
String policy = "onap.policies.Naming";
String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
LOGGER.info("Copying {}", policyType);
- Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
- policyType.getBytes());
+ Files.write(Paths.get(policyFolder.toFile().getAbsolutePath(), policy + "-1.0.0.yaml"),
+ policyType.getBytes());
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Iterate through Xacml application services and find
// the optimization service. Save it for use throughout
// all the Junit tests.
//
StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -136,11 +125,15 @@ public class NamingPdpApplicationTest {
// Tell it to initialize based on the properties file
// we just built for it.
//
+
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
+ File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
+ properties, myCreator);
service.initialize(propertiesFile.toPath().getParent(), null);
}
@Test
- public void test01Basics() {
+ void test01Basics() {
//
// Make sure there's an application name
//
@@ -155,13 +148,13 @@ public class NamingPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.Naming", "1.0.0"))).isTrue();
+ "onap.policies.Naming", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.foobar", "1.0.0"))).isFalse();
+ "onap.foobar", "1.0.0"))).isFalse();
}
@Test
- public void test02NoPolicies() throws CoderException {
+ void test02NoPolicies() throws CoderException {
//
// Ask for a decision when there are no policies loaded
//
@@ -180,7 +173,7 @@ public class NamingPdpApplicationTest {
}
@Test
- public void test03Naming() throws CoderException, FileNotFoundException, IOException,
+ void test03Naming() throws
XacmlApplicationException {
//
// Now load all the optimization policies
@@ -198,7 +191,7 @@ public class NamingPdpApplicationTest {
//
// Ask for VNF
//
- baseRequest.getResource().put("policy-type", Arrays.asList("onap.policies.Naming"));
+ baseRequest.getResource().put("policy-type", List.of("onap.policies.Naming"));
//
// Ask for a decision for VNF default policies
//
@@ -238,13 +231,13 @@ public class NamingPdpApplicationTest {
Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
validateMatchable((Collection<String>) request.getResource().get("nfRole"),
- (Collection<String>) policyProperties.get("nfRole"));
+ (Collection<String>) policyProperties.get("nfRole"));
validateMatchable((Collection<String>) request.getResource().get("naming-type"),
- (Collection<String>) policyProperties.get("naming-type"));
+ (Collection<String>) policyProperties.get("naming-type"));
validateMatchable((Collection<String>) request.getResource().get("property-name"),
- (Collection<String>) policyProperties.get("property-name"));
+ (Collection<String>) policyProperties.get("property-name"));
}
}
@@ -258,8 +251,8 @@ public class NamingPdpApplicationTest {
return;
}
Condition<String> condition = new Condition<>(
- requestList::contains,
- "Request list is contained");
+ requestList::contains,
+ "Request list is contained");
assertThat(policyProperties).haveAtLeast(1, condition);
}
diff --git a/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java b/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java
index 6a706760..47e92c09 100644
--- a/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java
+++ b/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,13 +32,13 @@ import com.att.research.xacml.api.Response;
import com.att.research.xacml.std.dom.DOMRequest;
import com.att.research.xacml.std.dom.DOMResponse;
import java.io.File;
+import java.nio.file.Path;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -53,38 +53,38 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NativePdpApplicationTest {
+class NativePdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTest.class);
private static final String PERMIT = "Permit";
private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static NativePdpApplication service;
private static Request request;
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
LOGGER.info("Setting up class");
//
// Setup our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ properties, myCreator);
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Find the native application and save for use in all the tests
//
@@ -115,12 +115,12 @@ public class NativePdpApplicationTest {
// Load XACML Request
//
request = DOMRequest.load(
- TextFileUtils.getTextFileAsString(
- "src/test/resources/requests/native.policy.request.xml"));
+ TextFileUtils.getTextFileAsString(
+ "src/test/resources/requests/native.policy.request.xml"));
}
@Test
- public void testUncommon() {
+ void testUncommon() {
NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
translator.convertRequest(null)
@@ -132,12 +132,12 @@ public class NativePdpApplicationTest {
assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
"onap.policies.native.Xacml", "1.0.0"))).isTrue();
assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.native.SomethingElse", "1.0.0"))).isFalse();
+ "onap.policies.native.SomethingElse", "1.0.0"))).isFalse();
assertThat(application.actionDecisionsSupported()).contains("native");
}
@Test
- public void testBadPolicies() throws Exception {
+ void testBadPolicies() throws Exception {
NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml");
//
@@ -173,7 +173,7 @@ public class NativePdpApplicationTest {
}
@Test
- public void testNativePolicy() throws Exception {
+ void testNativePolicy() throws Exception {
LOGGER.info("*********** Running native policy test *************");
//
@@ -184,18 +184,16 @@ public class NativePdpApplicationTest {
//
// Send the request and verify decision result
//
- requestAndCheckDecision(request, PERMIT);
+ requestAndCheckDecision(request);
}
/**
* Request a decision and check that it matches expectation.
*
* @param request to send to XACML PDP
- * @param expected from the response
* @throws Exception on errors requesting a decision and checking the returned decision
- *
**/
- private void requestAndCheckDecision(Request request, String expected) throws Exception {
+ private void requestAndCheckDecision(Request request) throws Exception {
//
// Ask for a decision
//
@@ -203,23 +201,21 @@ public class NativePdpApplicationTest {
//
// Check decision
//
- checkDecision(expected, decision);
+ checkDecision(decision);
}
/**
* Check that decision matches expectation.
*
- * @param expected from the response
* @param response received
* @throws Exception on errors checking the decision
- *
**/
- private void checkDecision(String expected, Response response) throws Exception {
- LOGGER.info("Looking for {} Decision", expected);
+ private void checkDecision(Response response) throws Exception {
+ LOGGER.info("Looking for {} Decision", NativePdpApplicationTest.PERMIT);
assertThat(response).isNotNull();
Decision decision = response.getResults().iterator().next().getDecision();
assertThat(decision).isNotNull();
- assertThat(decision).hasToString(expected);
+ assertThat(decision).hasToString(NativePdpApplicationTest.PERMIT);
LOGGER.info("Xacml response we received {}", DOMResponse.toString(response));
}
}
diff --git a/applications/optimization/pom.xml b/applications/optimization/pom.xml
index 50c4f043..cfb7d931 100644
--- a/applications/optimization/pom.xml
+++ b/applications/optimization/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy Engine - XACML PDP
================================================================================
Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023 Nordix Foundation.
+ Modifications Copyright (C) 2023-2024 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -35,11 +35,6 @@
<dependencies>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.xacml-pdp.applications</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
diff --git a/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java b/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java
index 6d86bdb4..55be0e1b 100644
--- a/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java
+++ b/applications/optimization/src/main/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* 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.
@@ -33,8 +34,8 @@ import com.att.research.xacml.std.StdMutableRequest;
import com.att.research.xacml.std.StdMutableRequestAttributes;
import com.att.research.xacml.std.annotations.XACMLSubject;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -75,12 +76,12 @@ public class OptimizationSubscriberRequest extends StdMatchablePolicyRequest {
// Should always be a collection, but in case someone changes
// the class without checking this repo.
//
- if (entrySet.getValue() instanceof Collection) {
- addSubject(contextAttributes, (Collection) entrySet.getValue(),
- ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
+ if (entrySet.getValue() instanceof Collection collection) {
+ addSubject(contextAttributes, collection,
+ ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
} else {
- addSubject(contextAttributes, Arrays.asList(entrySet.getValue().toString()),
- ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
+ addSubject(contextAttributes, Collections.singletonList(entrySet.getValue().toString()),
+ ToscaDictionary.ID_SUBJECT_OPTIMIZATION_SUBSCRIBER_NAME);
}
} catch (DataTypeException e) {
throw new XacmlApplicationException("Failed to add resource ", e);
@@ -91,19 +92,20 @@ public class OptimizationSubscriberRequest extends StdMatchablePolicyRequest {
}
protected static StdMutableRequestAttributes addSubject(StdMutableRequestAttributes attributes,
- Collection<Object> values, Identifier id) throws DataTypeException {
+ Collection<Object> values, Identifier id)
+ throws DataTypeException {
var factory = getDataTypeFactory();
if (factory == null) {
return null;
}
for (Object value : values) {
- var mutableAttribute = new StdMutableAttribute();
+ var mutableAttribute = new StdMutableAttribute();
mutableAttribute.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT);
mutableAttribute.setAttributeId(id);
mutableAttribute.setIncludeInResults(true);
- DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
+ DataType<?> dataTypeExtended = factory.getDataType(XACML3.ID_DATATYPE_STRING);
AttributeValue<?> attributeValue = dataTypeExtended.createAttributeValue(value);
Collection<AttributeValue<?>> attributeValues = new ArrayList<>();
attributeValues.add(attributeValue);
diff --git a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java
index f9fe8728..a93895c1 100644
--- a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java
+++ b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationPdpApplicationTest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,9 +30,9 @@ import com.att.research.xacml.api.Response;
import com.google.common.collect.Lists;
import java.io.File;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -40,12 +40,11 @@ import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
import org.assertj.core.api.Condition;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runners.MethodSorters;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
@@ -64,16 +63,16 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class OptimizationPdpApplicationTest {
+@TestMethodOrder(MethodOrderer.MethodName.class)
+class OptimizationPdpApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplicationTest.class);
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
- private static StandardCoder gson = new StandardCoder();
+ private static final StandardCoder gson = new StandardCoder();
private static DecisionRequest baseRequest;
- private static String[] listPolicyTypeFiles = {
+ private static final String[] listPolicyTypeFiles = {
"onap.policies.Optimization",
"onap.policies.optimization.Resource",
"onap.policies.optimization.Service",
@@ -87,53 +86,51 @@ public class OptimizationPdpApplicationTest {
"onap.policies.optimization.resource.Vim_fit",
"onap.policies.optimization.resource.VnfPolicy"};
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* Copies the xacml.properties and policies files into
* temporary folder and loads the service provider saving
* instance of provider off for other tests to use.
*/
- @BeforeClass
- public static void setUp() throws Exception {
+ @BeforeAll
+ static void setUp() throws Exception {
//
// Load Single Decision Request
//
baseRequest = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.optimization.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.optimization.input.json"),
+ DecisionRequest.class);
//
// Setup our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
- properties, myCreator);
+ properties, myCreator);
//
// Copy the test policy types into data area
//
for (String policy : listPolicyTypeFiles) {
String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
LOGGER.info("Copying {}", policyType);
- Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
- policyType.getBytes());
+ Files.write(Paths.get(policyFolder.toFile().getAbsolutePath(), policy + "-1.0.0.yaml"),
+ policyType.getBytes());
}
//
// Load service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Iterate through Xacml application services and find
// the optimization service. Save it for use throughout
// all the Junit tests.
//
StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
- Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
- while (iterator.hasNext()) {
- XacmlApplicationServiceProvider application = iterator.next();
+ for (XacmlApplicationServiceProvider application : applicationLoader) {
//
// Is it our service?
//
@@ -162,7 +159,7 @@ public class OptimizationPdpApplicationTest {
* Simply test some of the simple methods for the application.
*/
@Test
- public void test01Basics() {
+ void test01Basics() {
//
// Make sure there's an application name
//
@@ -177,13 +174,13 @@ public class OptimizationPdpApplicationTest {
// can support the correct policy types.
//
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.optimization.resource.AffinityPolicy", "1.0.0"))).isTrue();
+ "onap.policies.optimization.resource.AffinityPolicy", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.optimization.service.SubscriberPolicy", "1.0.0"))).isTrue();
+ "onap.policies.optimization.service.SubscriberPolicy", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.policies.optimization.service.CustomUseCase", "1.0.0"))).isTrue();
+ "onap.policies.optimization.service.CustomUseCase", "1.0.0"))).isTrue();
assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
- "onap.foobar", "1.0.0"))).isFalse();
+ "onap.foobar", "1.0.0"))).isFalse();
}
/**
@@ -192,7 +189,7 @@ public class OptimizationPdpApplicationTest {
* @throws CoderException CoderException
*/
@Test
- public void test02NoPolicies() throws CoderException {
+ void test02NoPolicies() throws CoderException {
//
// Ask for a decision when there are no policies loaded
//
@@ -217,12 +214,12 @@ public class OptimizationPdpApplicationTest {
* @throws XacmlApplicationException could not load policies
*/
@Test
- public void test03OptimizationDefault() throws XacmlApplicationException {
+ void test03OptimizationDefault() throws XacmlApplicationException {
//
// Now load all the optimization policies
//
List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies("src/test/resources/test-optimization-policies.yaml",
- service);
+ service);
assertThat(loadedPolicies).isNotNull().hasSize(14);
validateDecisionCount(2);
@@ -233,7 +230,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test04OptimizationDefaultHpa() {
+ void test04OptimizationDefaultHpa() {
//
// Add in policy type
//
@@ -248,7 +245,7 @@ public class OptimizationPdpApplicationTest {
assertThat(response.getPolicies()).hasSize(1);
response.getPolicies().forEach((key, value) -> {
assertThat(((Map<String, Object>) value)).containsEntry("type",
- "onap.policies.optimization.resource.HpaPolicy");
+ "onap.policies.optimization.resource.HpaPolicy");
});
//
// Validate it
@@ -261,7 +258,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test05OptimizationDefaultGeography() throws CoderException {
+ void test05OptimizationDefaultGeography() {
//
// Remove all the policy-type resources from the request
//
@@ -279,7 +276,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test06OptimizationDefaultGeographyAndService() {
+ void test06OptimizationDefaultGeographyAndService() {
//
// Add vCPE to the service list
//
@@ -293,7 +290,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test07OptimizationDefaultGeographyAndServiceAndResource() {
+ void test07OptimizationDefaultGeographyAndServiceAndResource() {
//
// Add vG to the resource list
//
@@ -307,7 +304,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test08OptimizationGeographyAndServiceAndResourceAndScopeIsGoldSubscriber() {
+ void test08OptimizationGeographyAndServiceAndResourceAndScopeIsGoldSubscriber() {
//
// Add gold as a scope
//
@@ -321,7 +318,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test09OptimizationGeographyAndServiceAndResourceAndScopeGoldOrPlatinumSubscriber() {
+ void test09OptimizationGeographyAndServiceAndResourceAndScopeGoldOrPlatinumSubscriber() {
//
// Add platinum to the scope list: this is now gold OR platinum
//
@@ -336,7 +333,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test10OptimizationGeographyAndServiceAndResourceAndScopeNotGoldStillPlatinum() {
+ void test10OptimizationGeographyAndServiceAndResourceAndScopeNotGoldStillPlatinum() {
//
// Add gold as a scope
//
@@ -351,7 +348,7 @@ public class OptimizationPdpApplicationTest {
* Filter by Affinity policy.
*/
@Test
- public void test11OptimizationPolicyTypeDefault() {
+ void test11OptimizationPolicyTypeDefault() {
//
// Add in policy type
//
@@ -366,7 +363,7 @@ public class OptimizationPdpApplicationTest {
*/
@SuppressWarnings("unchecked")
@Test
- public void test12OptimizationPolicyTypeDefault() {
+ void test12OptimizationPolicyTypeDefault() {
//
// Add in another policy type
//
@@ -377,7 +374,7 @@ public class OptimizationPdpApplicationTest {
}
@Test
- public void test999BadSubscriberPolicies() throws Exception {
+ void test999BadSubscriberPolicies() throws Exception {
final StandardYamlCoder yamlCoder = new StandardYamlCoder();
//
// Decode it
@@ -460,16 +457,16 @@ public class OptimizationPdpApplicationTest {
Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
validateMatchable((Collection<String>) request.getResource().get("scope"),
- (Collection<String>) policyProperties.get("scope"));
+ (Collection<String>) policyProperties.get("scope"));
validateMatchable((Collection<String>) request.getResource().get("services"),
- (Collection<String>) policyProperties.get("services"));
+ (Collection<String>) policyProperties.get("services"));
validateMatchable((Collection<String>) request.getResource().get("resources"),
- (Collection<String>) policyProperties.get("resources"));
+ (Collection<String>) policyProperties.get("resources"));
validateMatchable((Collection<String>) request.getResource().get("geography"),
- (Collection<String>) policyProperties.get("geography"));
+ (Collection<String>) policyProperties.get("geography"));
}
}
@@ -483,8 +480,8 @@ public class OptimizationPdpApplicationTest {
return;
}
Condition<String> condition = new Condition<>(
- requestList::contains,
- "Request list is contained");
+ requestList::contains,
+ "Request list is contained");
assertThat(policyProperties).haveAtLeast(1, condition);
}
diff --git a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java
index 3fd9e44b..c400e987 100644
--- a/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.java
+++ b/applications/optimization/src/test/java/org/onap/policy/xacml/pdp/application/optimization/OptimizationSubscriberRequestTest.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.
@@ -29,13 +30,13 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
-public class OptimizationSubscriberRequestTest {
+class OptimizationSubscriberRequestTest {
private static StandardCoder gson = new StandardCoder();
private DecisionRequest request;
@@ -44,19 +45,19 @@ public class OptimizationSubscriberRequestTest {
*
* @throws Exception Exception if unable to load
*/
- @Before
- public void setupLoadDecision() throws Exception {
+ @BeforeEach
+ void setupLoadDecision() throws Exception {
request = gson.decode(
- TextFileUtils
- .getTextFileAsString(
- "src/test/resources/decision.optimization.input.json"),
- DecisionRequest.class);
+ TextFileUtils
+ .getTextFileAsString(
+ "src/test/resources/decision.optimization.input.json"),
+ DecisionRequest.class);
assertThat(request).isNotNull();
}
@Test
- public void testDecisionRequest() throws Exception {
+ void testDecisionRequest() throws Exception {
//
// Add context
//
diff --git a/main/pom.xml b/main/pom.xml
index 05ef2140..f6b0595d 100644
--- a/main/pom.xml
+++ b/main/pom.xml
@@ -135,11 +135,6 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
diff --git a/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java b/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java
index a00eba90..b6801d82 100644
--- a/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java
+++ b/main/src/main/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisher.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2022 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.
@@ -92,8 +93,8 @@ public class XacmlPdpUpdatePublisher {
} catch (XacmlApplicationException e) {
// Failed to load policy, return error(s) to PAP
LOGGER.error("Failed to load policy: {}", policy, e);
- errorMessage.append("Failed to load policy: " + policy + ": "
- + e.getMessage() + XacmlPolicyUtils.LINE_SEPARATOR);
+ errorMessage.append("Failed to load policy: ").append(policy).append(": ").append(e.getMessage())
+ .append(XacmlPolicyUtils.LINE_SEPARATOR);
stats.updateDeployFailureCount();
}
}
diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java
index 996d2276..fd84c9ba 100644
--- a/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java
+++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManager.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -52,6 +52,7 @@ public class XacmlPdpApplicationManager {
private final ServiceLoader<XacmlApplicationServiceProvider> applicationLoader;
private final Map<String, XacmlApplicationServiceProvider> providerActionMap = new HashMap<>();
+ @Getter
private final List<ToscaConceptIdentifier> toscaPolicyTypeIdents = new ArrayList<>();
private final Map<ToscaPolicy, XacmlApplicationServiceProvider> mapLoadedPolicies = new HashMap<>();
@@ -89,7 +90,7 @@ public class XacmlPdpApplicationManager {
//
var applicationInitialized = false;
//
- // Have it initialize at a path
+ // Have it initialized at a path
//
try {
initializeApplicationPath(Paths.get(applicationParameters.getApplicationPath()), application,
@@ -148,15 +149,11 @@ public class XacmlPdpApplicationManager {
*/
public List<ToscaConceptIdentifier> getToscaPolicyIdentifiers() {
//
- // converting map to return List of ToscaPolicyIdentiers
+ // converting map to return List of ToscaPolicyIdentifiers
//
return mapLoadedPolicies.keySet().stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList());
}
- public List<ToscaConceptIdentifier> getToscaPolicyTypeIdents() {
- return toscaPolicyTypeIdents;
- }
-
/**
* Finds the appropriate application and removes the policy.
*
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java b/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java
index 89312cf5..d2baff20 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/CommonRest.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 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.
@@ -37,10 +37,10 @@ import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.SSLContext;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import org.onap.policy.common.utils.network.NetworkUtil;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.common.utils.security.SelfSignedKeyStore;
@@ -108,7 +108,7 @@ public class CommonRest {
*
* @throws Exception if an error occurs
*/
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
System.setProperty("javax.net.ssl.keyStore", new SelfSignedKeyStore().getKeystoreName());
System.setProperty("javax.net.ssl.keyStorePassword", SelfSignedKeyStore.KEYSTORE_PASSWORD);
@@ -132,7 +132,7 @@ public class CommonRest {
/**
* Stops the "Main".
*/
- @AfterClass
+ @AfterAll
public static void tearDownAfterClass() {
stopMain();
}
@@ -140,7 +140,7 @@ public class CommonRest {
/**
* Resets the statistics.
*/
- @Before
+ @BeforeEach
public void setUp() {
activatorWasAlive = XacmlPdpActivator.getCurrent().isAlive();
XacmlPdpStatisticsManager.getCurrent().resetAllStatistics();
@@ -149,7 +149,7 @@ public class CommonRest {
/**
* Restores the "alive" status of the activator.
*/
- @After
+ @AfterEach
public void tearDown() {
markActivator(activatorWasAlive);
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java
index 4dd02c62..e2d7d0dd 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,15 +23,15 @@
package org.onap.policy.pdpx.main;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class PolicyXacmlPdpExceptionTest {
+class PolicyXacmlPdpExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(2, new ExceptionsTester().test(PolicyXacmlPdpException.class));
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java
index 80e69747..d1cc98d5 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeExceptionTest.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,15 +23,15 @@
package org.onap.policy.pdpx.main;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.test.ExceptionsTester;
-public class PolicyXacmlPdpRuntimeExceptionTest {
+class PolicyXacmlPdpRuntimeExceptionTest {
@Test
- public void test() {
+ void test() {
assertEquals(2, new ExceptionsTester().test(PolicyXacmlPdpRuntimeException.class));
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java b/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java
index 62c90f54..6479b6e7 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/XacmlStateTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021, 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
* Modifications Copyright (C) 2023 Bell Canada.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,20 +22,20 @@
package org.onap.policy.pdpx.main;
-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 static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterAll;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
import org.onap.policy.models.pdp.concepts.PdpStateChange;
import org.onap.policy.models.pdp.concepts.PdpStatus;
@@ -46,8 +46,8 @@ import org.onap.policy.models.pdp.enums.PdpState;
import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager;
import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
-@RunWith(MockitoJUnitRunner.class)
-public class XacmlStateTest {
+@ExtendWith(MockitoExtension.class)
+class XacmlStateTest {
private static final String PDP_TYPE = "xacml-flavor";
private static final String GROUP = "my-group";
private static final String SUBGROUP = "my-subgroup";
@@ -66,21 +66,21 @@ public class XacmlStateTest {
/**
* Initializes objects, including the state.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
pdpName = XacmlState.PDP_NAME;
XacmlPdpActivator.setCurrent(act);
state = new XacmlState(appmgr, GROUP, PDP_TYPE);
}
- @AfterClass
- public static void tearDownAfterClass() {
+ @AfterAll
+ static void tearDownAfterClass() {
XacmlPdpActivator.setCurrent(null);
}
@Test
- public void testShouldHandle() {
+ void testShouldHandle() {
PdpUpdate msg = new PdpUpdate();
assertFalse(state.shouldHandle(msg));
@@ -89,7 +89,7 @@ public class XacmlStateTest {
}
@Test
- public void testGenHeartbeat() {
+ void testGenHeartbeat() {
// not healthy
PdpStatus status = state.genHeartbeat();
assertEquals(PdpHealthStatus.NOT_HEALTHY, status.getHealthy());
@@ -107,7 +107,7 @@ public class XacmlStateTest {
}
@Test
- public void testUpdateInternalStatePdpStateChange() {
+ void testUpdateInternalStatePdpStateChange() {
PdpStateChange req = new PdpStateChange();
req.setName(pdpName);
req.setPdpGroup("wrong-pdp-group");
@@ -139,7 +139,7 @@ public class XacmlStateTest {
}
@Test
- public void testUpdateInternalStatePdpUpdate() {
+ void testUpdateInternalStatePdpUpdate() {
PdpUpdate req = new PdpUpdate();
req.setPdpGroup("wrong-pdp-group");
req.setPdpSubgroup(SUBGROUP);
@@ -164,7 +164,7 @@ public class XacmlStateTest {
}
@Test
- public void testTerminatePdpMessage() {
+ void testTerminatePdpMessage() {
PdpStatus status = state.terminatePdpMessage();
assertEquals(PdpState.TERMINATED, status.getState());
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java
index 51689584..29dc10e7 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpHearbeatPublisherTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,15 +22,15 @@
package org.onap.policy.pdpx.main.comm;
import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.LinkedList;
@@ -37,19 +38,19 @@ import java.util.Queue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.common.endpoints.event.comm.TopicSink;
import org.onap.policy.common.endpoints.event.comm.client.BidirectionalTopicClient;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.models.pdp.concepts.PdpStatus;
import org.onap.policy.pdpx.main.XacmlState;
-@RunWith(MockitoJUnitRunner.class)
-public class XacmlPdpHearbeatPublisherTest {
+@ExtendWith(MockitoExtension.class)
+class XacmlPdpHearbeatPublisherTest {
private static final long INTERVAL1 = 1000L;
private static final long INTERVAL2 = 2000L;
@@ -83,23 +84,24 @@ public class XacmlPdpHearbeatPublisherTest {
/**
* Initializes objects, including the publisher.
*/
- @Before
- public void setUp() {
- when(sink.getTopic()).thenReturn("my-topic");
- when(checker.getSink()).thenReturn(sink);
- when(checker.isReady()).thenReturn(true);
- when(state.genHeartbeat()).thenReturn(status);
+ @BeforeEach
+ void setUp() {
+ lenient().when(sink.getTopic()).thenReturn("my-topic");
+ lenient().when(checker.getSink()).thenReturn(sink);
+ lenient().when(checker.isReady()).thenReturn(true);
+ lenient().when(state.genHeartbeat()).thenReturn(status);
status = new PdpStatus();
timers = new LinkedList<>(Arrays.asList(timer1, timer2));
- when(executor.scheduleWithFixedDelay(any(), anyLong(), anyLong(), any())).thenAnswer(args -> timers.remove());
+ lenient().when(executor.scheduleWithFixedDelay(any(), anyLong(), anyLong(), any()))
+ .thenAnswer(args -> timers.remove());
publisher = new MyPublisher(checker, 10, state);
}
@Test
- public void testRun() {
+ void testRun() {
publisher.run();
verify(state).genHeartbeat();
@@ -110,7 +112,7 @@ public class XacmlPdpHearbeatPublisherTest {
* Tests the run() method when the probe is disabled.
*/
@Test
- public void testRunNoProbe() throws CoderException {
+ void testRunNoProbe() throws CoderException {
publisher = new MyPublisher(checker, 0, state);
publisher.run();
@@ -126,24 +128,24 @@ public class XacmlPdpHearbeatPublisherTest {
* Tests the run() method when the topic is not ready, and then becomes ready.
*/
@Test
- public void testRunNotReady() throws CoderException {
+ void testRunNotReady() throws CoderException {
// not ready yet
- when(checker.isReady()).thenReturn(false);
- when(checker.awaitReady(any(), anyLong())).thenReturn(false);
+ lenient().when(checker.isReady()).thenReturn(false);
+ lenient().when(checker.awaitReady(any(), anyLong())).thenReturn(false);
publisher.run();
verify(state, never()).genHeartbeat();
verify(checker, never()).send(any());
// isReady is still false, but awaitReady is now true - should generate heartbeat
- when(checker.awaitReady(any(), anyLong())).thenReturn(true);
+ lenient().when(checker.awaitReady(any(), anyLong())).thenReturn(true);
publisher.run();
verify(state).genHeartbeat();
verify(checker).send(any());
// now isReady is true, too - should not rerun awaitReady
- when(checker.isReady()).thenReturn(true);
+ lenient().when(checker.isReady()).thenReturn(true);
publisher.run();
verify(state, times(2)).genHeartbeat();
@@ -155,11 +157,11 @@ public class XacmlPdpHearbeatPublisherTest {
* Tests the run() method when the checker throws an exception.
*/
@Test
- public void testRunCheckerEx() throws CoderException {
+ void testRunCheckerEx() throws CoderException {
// force it to call awaitReady
- when(checker.isReady()).thenReturn(false);
+ lenient().when(checker.isReady()).thenReturn(false);
- when(checker.awaitReady(any(), anyLong()))
+ lenient().when(checker.awaitReady(any(), anyLong()))
.thenThrow(new CoderException("expected exception"))
.thenReturn(true);
@@ -175,7 +177,7 @@ public class XacmlPdpHearbeatPublisherTest {
}
@Test
- public void testTerminate() {
+ void testTerminate() {
// not yet started
publisher.terminate();
@@ -198,7 +200,7 @@ public class XacmlPdpHearbeatPublisherTest {
}
@Test
- public void testRestart() {
+ void testRestart() {
// not started yet - should only update the interval
publisher.restart(INTERVAL1);
@@ -231,11 +233,11 @@ public class XacmlPdpHearbeatPublisherTest {
}
@Test
- public void testStart() {
+ void testStart() {
publisher.start();
verify(executor).scheduleWithFixedDelay(publisher, 0, XacmlPdpHearbeatPublisher.DEFAULT_HB_INTERVAL_MS,
- TimeUnit.MILLISECONDS);
+ TimeUnit.MILLISECONDS);
// repeat - nothing more should happen
publisher.start();
@@ -244,7 +246,7 @@ public class XacmlPdpHearbeatPublisherTest {
}
@Test
- public void testMakeTimerThread() {
+ void testMakeTimerThread() {
// create a plain listener to test the "real" makeTimer() method
publisher = new XacmlPdpHearbeatPublisher(checker, 1, state);
@@ -257,7 +259,7 @@ public class XacmlPdpHearbeatPublisherTest {
private class MyPublisher extends XacmlPdpHearbeatPublisher {
- public MyPublisher(BidirectionalTopicClient topicChecker, long probeHeartbeatTopicMs, XacmlState state) {
+ MyPublisher(BidirectionalTopicClient topicChecker, long probeHeartbeatTopicMs, XacmlState state) {
super(topicChecker, probeHeartbeatTopicMs, state);
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java
index 9f4d80bc..3d3ed864 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpPapRegistrationTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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.
@@ -23,17 +24,16 @@ package org.onap.policy.pdpx.main.comm;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.Mockito.when;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
-import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
import org.onap.policy.models.pdp.concepts.PdpStatus;
-@RunWith(MockitoJUnitRunner.class)
-public class XacmlPdpPapRegistrationTest {
+@ExtendWith(MockitoExtension.class)
+class XacmlPdpPapRegistrationTest {
@Mock
private TopicSinkClient client;
@@ -46,22 +46,22 @@ public class XacmlPdpPapRegistrationTest {
/**
* Initializes objects, including the registration object.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
when(client.send(status)).thenReturn(true);
reg = new XacmlPdpPapRegistration(client);
}
@Test
- public void testPdpRegistration_SendOk() throws TopicSinkClientException {
+ void testPdpRegistration_SendOk() {
assertThatCode(() ->
reg.pdpRegistration(status)
).doesNotThrowAnyException();
}
@Test
- public void testPdpRegistration_SendFail() throws TopicSinkClientException {
+ void testPdpRegistration_SendFail() {
when(client.send(status)).thenReturn(false);
assertThatCode(() ->
reg.pdpRegistration(status)
@@ -69,7 +69,7 @@ public class XacmlPdpPapRegistrationTest {
}
@Test
- public void testPdpRegistration_SendEx() throws TopicSinkClientException {
+ void testPdpRegistration_SendEx() {
when(client.send(status)).thenThrow(new IllegalStateException());
assertThatCode(() ->
reg.pdpRegistration(status)
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java
index 872bec15..0a10eb7a 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/XacmlPdpUpdatePublisherTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021-2022 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,22 +21,21 @@
package org.onap.policy.pdpx.main.comm;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.startsWith;
-import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
import org.onap.policy.models.pdp.concepts.PdpStatus;
import org.onap.policy.models.pdp.concepts.PdpUpdate;
@@ -51,8 +51,8 @@ import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
/**
* Initializes objects, including the publisher.
*/
-@RunWith(MockitoJUnitRunner.class)
-public class XacmlPdpUpdatePublisherTest {
+@ExtendWith(MockitoExtension.class)
+class XacmlPdpUpdatePublisherTest {
private static final int NEW_COUNT = 5;
@@ -108,8 +108,8 @@ public class XacmlPdpUpdatePublisherTest {
/**
* Initializes objects, including the publisher.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
ToscaConceptIdentifier deployedId1 = new ToscaConceptIdentifier("deployed-1", "1.0.0");
ToscaConceptIdentifier deployedId2 = new ToscaConceptIdentifier("deployed-2", "1.0.0");
ToscaConceptIdentifier deployedId4 = new ToscaConceptIdentifier("deployed-4", "1.0.0");
@@ -117,15 +117,15 @@ public class XacmlPdpUpdatePublisherTest {
ToscaConceptIdentifier addedId1 = new ToscaConceptIdentifier("added-1", "1.0.0");
ToscaConceptIdentifier addedId2 = new ToscaConceptIdentifier("added-2", "1.0.0");
- when(deployed1.getIdentifier()).thenReturn(deployedId1);
- when(deployed2.getIdentifier()).thenReturn(deployedId2);
- when(deployed3.getIdentifier()).thenReturn(new ToscaConceptIdentifier("deployed-3", "1.0.0"));
- when(deployed4.getIdentifier()).thenReturn(deployedId4);
- when(deployed5.getIdentifier()).thenReturn(deployedId5);
- when(added1.getIdentifier()).thenReturn(addedId1);
- when(added2.getIdentifier()).thenReturn(addedId2);
- when(failPolicy1.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-1", "1.0.0"));
- when(failPolicy2.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-2", "1.0.0"));
+ lenient().when(deployed1.getIdentifier()).thenReturn(deployedId1);
+ lenient().when(deployed2.getIdentifier()).thenReturn(deployedId2);
+ lenient().when(deployed3.getIdentifier()).thenReturn(new ToscaConceptIdentifier("deployed-3", "1.0.0"));
+ lenient().when(deployed4.getIdentifier()).thenReturn(deployedId4);
+ lenient().when(deployed5.getIdentifier()).thenReturn(deployedId5);
+ lenient().when(added1.getIdentifier()).thenReturn(addedId1);
+ lenient().when(added2.getIdentifier()).thenReturn(addedId2);
+ lenient().when(failPolicy1.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-1", "1.0.0"));
+ lenient().when(failPolicy2.getIdentifier()).thenReturn(new ToscaConceptIdentifier("failPolicy-2", "1.0.0"));
Map<ToscaPolicy, XacmlApplicationServiceProvider> deployedPolicies = new HashMap<>();
deployedPolicies.put(deployed1, null);
@@ -133,22 +133,23 @@ public class XacmlPdpUpdatePublisherTest {
deployedPolicies.put(deployed3, null);
deployedPolicies.put(deployed4, null);
deployedPolicies.put(deployed5, null);
- when(appmgr.getToscaPolicies()).thenReturn(deployedPolicies);
+ lenient().when(appmgr.getToscaPolicies()).thenReturn(deployedPolicies);
// update includes one overlap with existing and one overlap between the two
- when(update.getPoliciesToBeDeployed()).thenReturn(List.of(added1, deployed2, deployed5, added2));
- when(update.getPoliciesToBeUndeployed()).thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4));
+ lenient().when(update.getPoliciesToBeDeployed()).thenReturn(List.of(added1, deployed2, deployed5, added2));
+ lenient().when(update.getPoliciesToBeUndeployed())
+ .thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4));
- when(failurePdpUpdate.getPoliciesToBeDeployed())
- .thenReturn(List.of(added1, deployed2, deployed5, failPolicy1, failPolicy2));
- when(failurePdpUpdate.getPoliciesToBeUndeployed())
- .thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4));
+ lenient().when(failurePdpUpdate.getPoliciesToBeDeployed())
+ .thenReturn(List.of(added1, deployed2, deployed5, failPolicy1, failPolicy2));
+ lenient().when(failurePdpUpdate.getPoliciesToBeUndeployed())
+ .thenReturn(List.of(addedId1, deployedId1, deployedId5, deployedId4));
- when(appmgr.getPolicyCount()).thenReturn(NEW_COUNT);
+ lenient().when(appmgr.getPolicyCount()).thenReturn(NEW_COUNT);
- when(state.updateInternalState(any(), any())).thenReturn(status);
+ lenient().when(state.updateInternalState(any(), any())).thenReturn(status);
- when(client.send(any())).thenReturn(true);
+ lenient().when(client.send(any())).thenReturn(true);
publisher = new XacmlPdpUpdatePublisher(client, state, appmgr);
@@ -157,7 +158,7 @@ public class XacmlPdpUpdatePublisherTest {
}
@Test
- public void testHandlePdpUpdate() throws XacmlApplicationException {
+ void testHandlePdpUpdate() throws XacmlApplicationException {
publisher.handlePdpUpdate(update);
// two removed
@@ -182,8 +183,8 @@ public class XacmlPdpUpdatePublisherTest {
}
@Test
- public void testHandlePdpUpdate_Deploy() throws XacmlApplicationException {
- when(update.getPoliciesToBeUndeployed()).thenReturn(null);
+ void testHandlePdpUpdate_Deploy() throws XacmlApplicationException {
+ lenient().when(update.getPoliciesToBeUndeployed()).thenReturn(null);
publisher.handlePdpUpdate(update);
@@ -201,8 +202,8 @@ public class XacmlPdpUpdatePublisherTest {
}
@Test
- public void testHandlePdpUpdate_Undeploy() throws XacmlApplicationException {
- when(update.getPoliciesToBeDeployed()).thenReturn(null);
+ void testHandlePdpUpdate_Undeploy() throws XacmlApplicationException {
+ lenient().when(update.getPoliciesToBeDeployed()).thenReturn(null);
publisher.handlePdpUpdate(update);
@@ -220,10 +221,10 @@ public class XacmlPdpUpdatePublisherTest {
}
@Test
- public void testHandlePdpUpdate_LoadPolicyFailed() throws XacmlApplicationException {
+ void testHandlePdpUpdate_LoadPolicyFailed() throws XacmlApplicationException {
// Set loadPolicy to fail
- doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy1);
- doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy2);
+ lenient().doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy1);
+ lenient().doThrow(new XacmlApplicationException()).when(appmgr).loadDeployedPolicy(failPolicy2);
publisher.handlePdpUpdate(failurePdpUpdate);
@@ -239,9 +240,9 @@ public class XacmlPdpUpdatePublisherTest {
}
@Test
- public void testHandlePdpUpdate_NullPolicies() throws XacmlApplicationException {
- when(update.getPoliciesToBeDeployed()).thenReturn(null);
- when(update.getPoliciesToBeUndeployed()).thenReturn(null);
+ void testHandlePdpUpdate_NullPolicies() throws XacmlApplicationException {
+ lenient().when(update.getPoliciesToBeDeployed()).thenReturn(null);
+ lenient().when(update.getPoliciesToBeUndeployed()).thenReturn(null);
publisher.handlePdpUpdate(update);
@@ -255,9 +256,9 @@ public class XacmlPdpUpdatePublisherTest {
}
@Test
- public void testHandlePdpUpdate_SendFail() {
+ void testHandlePdpUpdate_SendFail() {
- when(client.send(any())).thenReturn(false);
+ lenient().when(client.send(any())).thenReturn(false);
publisher.handlePdpUpdate(update);
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java
index dbc065a1..f646ef29 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpStateChangeListenerTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,23 +22,23 @@
package org.onap.policy.pdpx.main.comm.listeners;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
import org.onap.policy.models.pdp.concepts.PdpStateChange;
import org.onap.policy.models.pdp.concepts.PdpStatus;
import org.onap.policy.pdpx.main.XacmlState;
-@RunWith(MockitoJUnitRunner.class)
-public class XacmlPdpStateChangeListenerTest {
+@ExtendWith(MockitoExtension.class)
+class XacmlPdpStateChangeListenerTest {
private static final String TOPIC = "my-topic";
@Mock
@@ -57,19 +58,19 @@ public class XacmlPdpStateChangeListenerTest {
/**
* Initializes objects, including the listener.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
listener = new XacmlPdpStateChangeListener(client, state);
- when(state.shouldHandle(change)).thenReturn(true);
- when(state.updateInternalState(change)).thenReturn(status);
+ lenient().when(state.shouldHandle(change)).thenReturn(true);
+ lenient().when(state.updateInternalState(change)).thenReturn(status);
- when(client.send(status)).thenReturn(true);
+ lenient().when(client.send(status)).thenReturn(true);
}
@Test
- public void testOnTopicEvent_Unhandled() {
- when(state.shouldHandle(change)).thenReturn(false);
+ void testOnTopicEvent_Unhandled() {
+ lenient().when(state.shouldHandle(change)).thenReturn(false);
listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, change);
verify(state, never()).updateInternalState(any(PdpStateChange.class));
@@ -77,8 +78,8 @@ public class XacmlPdpStateChangeListenerTest {
}
@Test
- public void testOnTopicEvent_SendFailed() {
- when(client.send(status)).thenReturn(false);
+ void testOnTopicEvent_SendFailed() {
+ lenient().when(client.send(status)).thenReturn(false);
listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, change);
@@ -87,7 +88,7 @@ public class XacmlPdpStateChangeListenerTest {
}
@Test
- public void testOnTopicEvent_SendOk() {
+ void testOnTopicEvent_SendOk() {
listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, change);
verify(state).updateInternalState(change);
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java
index 7a9dc4d7..7d23b742 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/comm/listeners/XacmlPdpUpdateListenerTest.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,19 +21,18 @@
package org.onap.policy.pdpx.main.comm.listeners;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+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.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
import org.onap.policy.models.pdp.concepts.PdpUpdate;
@@ -43,8 +42,8 @@ import org.onap.policy.pdpx.main.comm.XacmlPdpUpdatePublisher;
import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager;
import org.springframework.test.util.ReflectionTestUtils;
-@RunWith(MockitoJUnitRunner.class)
-public class XacmlPdpUpdateListenerTest {
+@ExtendWith(MockitoExtension.class)
+class XacmlPdpUpdateListenerTest {
private static final String EXPECTED_EXCEPTION = "expected exception";
private static final String TOPIC = "my-topic";
private static final long HB_INTERVAL = 100L;
@@ -71,19 +70,19 @@ public class XacmlPdpUpdateListenerTest {
/**
* Initializes objects, including the listener.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
listener = new MyListener(client, state, heartbeat, appmgr);
update = new PdpUpdate();
- when(state.shouldHandle(update)).thenReturn(true);
+ lenient().when(state.shouldHandle(update)).thenReturn(true);
update.setPdpHeartbeatIntervalMs(HB_INTERVAL);
}
@Test
- public void testOnTopicEvent_Unhandled() {
- when(state.shouldHandle(update)).thenReturn(false);
+ void testOnTopicEvent_Unhandled() {
+ lenient().when(state.shouldHandle(update)).thenReturn(false);
listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, update);
verify(publisher, never()).handlePdpUpdate(any());
@@ -91,7 +90,7 @@ public class XacmlPdpUpdateListenerTest {
}
@Test
- public void testOnTopicEvent_SendOk() {
+ void testOnTopicEvent_SendOk() {
listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, update);
verify(publisher).handlePdpUpdate(update);
@@ -99,8 +98,8 @@ public class XacmlPdpUpdateListenerTest {
}
@Test
- public void testOnTopicEvent_SendEx() {
- doThrow(new RuntimeException(EXPECTED_EXCEPTION)).when(publisher).handlePdpUpdate(update);
+ void testOnTopicEvent_SendEx() {
+ lenient().doThrow(new RuntimeException(EXPECTED_EXCEPTION)).when(publisher).handlePdpUpdate(update);
listener.onTopicEvent(CommInfrastructure.NOOP, TOPIC, null, update);
@@ -109,7 +108,7 @@ public class XacmlPdpUpdateListenerTest {
}
@Test
- public void testMakePublisher() {
+ void testMakePublisher() {
// create a plain listener to test the "real" makePublisher() method
listener = new XacmlPdpUpdateListener(client, state, heartbeat, appmgr);
assertNotNull(ReflectionTestUtils.getField(listener, "publisher"));
@@ -117,14 +116,14 @@ public class XacmlPdpUpdateListenerTest {
private class MyListener extends XacmlPdpUpdateListener {
- public MyListener(TopicSinkClient client, XacmlState state, XacmlPdpHearbeatPublisher heartbeat,
- XacmlPdpApplicationManager appManager) {
+ MyListener(TopicSinkClient client, XacmlState state, XacmlPdpHearbeatPublisher heartbeat,
+ XacmlPdpApplicationManager appManager) {
super(client, state, heartbeat, appManager);
}
@Override
protected XacmlPdpUpdatePublisher makePublisher(TopicSinkClient client, XacmlState state,
- XacmlPdpApplicationManager appManager) {
+ XacmlPdpApplicationManager appManager) {
return publisher;
}
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java
index f39061a6..614f9bee 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019, 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,17 +23,16 @@
package org.onap.policy.pdpx.main.parameters;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
-import java.io.IOException;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import java.nio.file.Path;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.endpoints.parameters.RestClientParameters;
import org.onap.policy.common.endpoints.parameters.RestServerParameters;
import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
@@ -41,35 +40,34 @@ import org.onap.policy.common.parameters.ValidationResult;
/**
* Class to perform unit test of XacmlPdpParameterGroup.
- *
*/
-public class TestXacmlPdpParameterGroup {
+class TestXacmlPdpParameterGroup {
private static File applicationPath;
private static final CommonTestData testData = new CommonTestData();
- @ClassRule
- public static final TemporaryFolder applicationFolder = new TemporaryFolder();
+ @TempDir
+ static Path applicationFolder;
- @Before
- public void setupPath() throws IOException {
- applicationPath = applicationFolder.newFolder();
+ @BeforeEach
+ void setupPath() {
+ applicationPath = applicationFolder.toFile();
}
@Test
- public void testXacmlPdpParameterGroup() throws IOException {
+ void testXacmlPdpParameterGroup() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters =
- new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME,
- CommonTestData.PDPX_GROUP, "flavor", restServerParameters, policyApiParameters,
- topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME,
+ CommonTestData.PDPX_GROUP, "flavor", restServerParameters, policyApiParameters,
+ topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertThat(validationResult.getResult()).isNull();
assertTrue(validationResult.isValid());
@@ -84,18 +82,18 @@ public class TestXacmlPdpParameterGroup {
}
@Test
- public void testXacmlPdpParameterGroup_NullParameterGroupName() {
+ void testXacmlPdpParameterGroup_NullParameterGroupName() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters = new XacmlPdpParameterGroup(null, CommonTestData.PDPX_GROUP,
- null, restServerParameters, policyApiParameters, topicParameterGroup, xacmlApplicationParameters);
+ null, restServerParameters, policyApiParameters, topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertNull(pdpxParameters.getName());
@@ -103,19 +101,19 @@ public class TestXacmlPdpParameterGroup {
}
@Test
- public void testXacmlPdpParameterGroup_EmptyParameterGroupName() {
+ void testXacmlPdpParameterGroup_EmptyParameterGroupName() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters = new XacmlPdpParameterGroup("", CommonTestData.PDPX_GROUP,
- CommonTestData.PDPX_TYPE, restServerParameters, policyApiParameters, topicParameterGroup,
- xacmlApplicationParameters);
+ CommonTestData.PDPX_TYPE, restServerParameters, policyApiParameters, topicParameterGroup,
+ xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertEquals("", pdpxParameters.getName());
@@ -123,19 +121,19 @@ public class TestXacmlPdpParameterGroup {
}
@Test
- public void testXacmlPdpParameterGroup_NullPdpGroup() {
+ void testXacmlPdpParameterGroup_NullPdpGroup() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters =
- new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, null, null, restServerParameters,
- policyApiParameters, topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, null, null, restServerParameters,
+ policyApiParameters, topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertNull(pdpxParameters.getPdpGroup());
@@ -143,19 +141,19 @@ public class TestXacmlPdpParameterGroup {
}
@Test
- public void testXacmlPdpParameterGroup_EmptyPdpGroup() {
+ void testXacmlPdpParameterGroup_EmptyPdpGroup() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters =
- new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, "", null, restServerParameters,
- policyApiParameters, topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, "", null, restServerParameters,
+ policyApiParameters, topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertEquals("", pdpxParameters.getPdpGroup());
@@ -163,80 +161,80 @@ public class TestXacmlPdpParameterGroup {
}
@Test
- public void testXacmlPdpParameterGroup_EmptyRestServerParameters() {
+ void testXacmlPdpParameterGroup_EmptyRestServerParameters() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(true), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters =
- new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
- null, restServerParameters, policyApiParameters,
- topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
+ null, restServerParameters, policyApiParameters,
+ topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertThat(validationResult.getResult()).contains("\"RestServerParameters\"");
}
@Test
- public void testXacmlPdpParameterGroup_EmptyPolicyApiParameters() {
+ void testXacmlPdpParameterGroup_EmptyPolicyApiParameters() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(true), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(true), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters =
- new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
- null, restServerParameters, policyApiParameters,
- topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
+ null, restServerParameters, policyApiParameters,
+ topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertThat(validationResult.getResult()).contains("\"policyApiParameters\"");
}
@Test
- public void testXacmlPdpParameterGroup_EmptyTopicParameterGroup() {
+ void testXacmlPdpParameterGroup_EmptyTopicParameterGroup() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(true), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters =
- new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
- null, restServerParameters, policyApiParameters,
- topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
+ null, restServerParameters, policyApiParameters,
+ topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertThat(validationResult.getResult()).contains("\"TopicParameterGroup\"");
}
@Test
- public void testXacmlPdpParameterGroup_EmptyApplicationParameterGroup() {
+ void testXacmlPdpParameterGroup_EmptyApplicationParameterGroup() {
final RestServerParameters restServerParameters =
testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class);
final RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
final TopicParameterGroup topicParameterGroup =
testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(true,
- applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(true,
+ applicationPath.getAbsolutePath()), XacmlApplicationParameters.class);
final XacmlPdpParameterGroup pdpxParameters =
- new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
- null, restServerParameters, policyApiParameters,
- topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup(CommonTestData.PDPX_PARAMETER_GROUP_NAME, CommonTestData.PDPX_GROUP,
+ null, restServerParameters, policyApiParameters,
+ topicParameterGroup, xacmlApplicationParameters);
final ValidationResult validationResult = pdpxParameters.validate();
assertFalse(validationResult.isValid());
assertThat(validationResult.getResult()).contains("\"XacmlApplicationParameters\"");
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java
index 00e95db7..d64c39fa 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation
+ * Modifications Copyright (C) 2020, 2024 Nordix Foundation
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,88 +23,87 @@ package org.onap.policy.pdpx.main.parameters;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
import org.onap.policy.pdpx.main.startstop.XacmlPdpCommandLineArguments;
/**
* Class to perform unit test of XacmlPdpParameterHandler.
- *
*/
-public class TestXacmlPdpParameterHandler {
+class TestXacmlPdpParameterHandler {
@Test
- public void testParameterHandlerNoParameterFile() throws PolicyXacmlPdpException {
+ void testParameterHandlerNoParameterFile() throws PolicyXacmlPdpException {
final String[] noArgumentString = {"-c", "parameters/NoParameterFile.json"};
final XacmlPdpCommandLineArguments noArguments = new XacmlPdpCommandLineArguments();
noArguments.parse(noArgumentString);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(noArguments))
- .isInstanceOf(PolicyXacmlPdpException.class);
+ .isInstanceOf(PolicyXacmlPdpException.class);
}
@Test
- public void testParameterHandlerEmptyParameters() throws PolicyXacmlPdpException {
+ void testParameterHandlerEmptyParameters() throws PolicyXacmlPdpException {
final String[] emptyArgumentString = {"-c", "parameters/EmptyParameters.json"};
final XacmlPdpCommandLineArguments emptyArguments = new XacmlPdpCommandLineArguments();
emptyArguments.parse(emptyArgumentString);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(emptyArguments))
- .hasMessage("no parameters found in \"parameters/EmptyParameters.json\"");
+ .hasMessage("no parameters found in \"parameters/EmptyParameters.json\"");
}
@Test
- public void testParameterHandlerBadParameters() throws PolicyXacmlPdpException {
+ void testParameterHandlerBadParameters() throws PolicyXacmlPdpException {
final String[] badArgumentString = {"-c", "parameters/BadParameters.json"};
final XacmlPdpCommandLineArguments badArguments = new XacmlPdpCommandLineArguments();
badArguments.parse(badArgumentString);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(badArguments))
- .hasMessageContaining("error reading parameters from", "parameters/BadParameters.json",
- "JsonSyntaxException", "java.lang.IllegalStateException",
- "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name");
+ .hasMessageContaining("error reading parameters from", "parameters/BadParameters.json",
+ "JsonSyntaxException", "java.lang.IllegalStateException",
+ "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name");
}
@Test
- public void testParameterHandlerInvalidParameters() throws PolicyXacmlPdpException {
+ void testParameterHandlerInvalidParameters() throws PolicyXacmlPdpException {
final String[] invalidArgumentString = {"-c", "parameters/InvalidParameters.json"};
final XacmlPdpCommandLineArguments invalidArguments = new XacmlPdpCommandLineArguments();
invalidArguments.parse(invalidArgumentString);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(invalidArguments))
- .hasMessageContaining("error reading parameters from", "parameters/InvalidParameters.json",
- "JsonSyntaxException", "java.lang.IllegalStateException",
- "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name");
+ .hasMessageContaining("error reading parameters from", "parameters/InvalidParameters.json",
+ "JsonSyntaxException", "java.lang.IllegalStateException",
+ "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name");
}
@Test
- public void testParameterHandlerNoParameters() throws PolicyXacmlPdpException {
+ void testParameterHandlerNoParameters() throws PolicyXacmlPdpException {
final String[] noArgumentString = {"-c", "parameters/NoParameters.json"};
final XacmlPdpCommandLineArguments noArguments = new XacmlPdpCommandLineArguments();
noArguments.parse(noArgumentString);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(noArguments))
- .hasMessageContaining("validation error(s) on parameters from \"parameters/NoParameters.json\"",
- "\"XacmlPdpParameterGroup\" INVALID, item has status INVALID",
- "\"name\" value \"null\" INVALID, is null",
- "\"pdpGroup\" value \"null\" INVALID, is null",
- "\"pdpType\" value \"null\" INVALID, is null",
- "\"applicationPath\" value \"null\" INVALID, is null");
+ .hasMessageContaining("validation error(s) on parameters from \"parameters/NoParameters.json\"",
+ "\"XacmlPdpParameterGroup\" INVALID, item has status INVALID",
+ "\"name\" value \"null\" INVALID, is null",
+ "\"pdpGroup\" value \"null\" INVALID, is null",
+ "\"pdpType\" value \"null\" INVALID, is null",
+ "\"applicationPath\" value \"null\" INVALID, is null");
}
@Test
- public void testParameterHandlerMinumumParameters() throws PolicyXacmlPdpException {
+ void testParameterHandlerMinumumParameters() throws PolicyXacmlPdpException {
final String[] minArgumentString = {"-c", "parameters/MinimumParameters.json"};
final XacmlPdpCommandLineArguments minArguments = new XacmlPdpCommandLineArguments();
@@ -117,7 +116,7 @@ public class TestXacmlPdpParameterHandler {
}
@Test
- public void testXacmlPdpParameterGroup() throws PolicyXacmlPdpException {
+ void testXacmlPdpParameterGroup() throws PolicyXacmlPdpException {
final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json"};
final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments();
@@ -130,31 +129,31 @@ public class TestXacmlPdpParameterHandler {
}
@Test
- public void testXacmlPdpParameterGroup_Invalid() throws PolicyXacmlPdpException {
+ void testXacmlPdpParameterGroup_Invalid() throws PolicyXacmlPdpException {
final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidName.json"};
final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments();
arguments.parse(xacmlPdpConfigParameters);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)).hasMessageContaining(
- "\"name\" value \" \" INVALID, is blank");
+ "\"name\" value \" \" INVALID, is blank");
xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters_InvalidPdpGroup.json";
arguments.parse(xacmlPdpConfigParameters);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)).hasMessageContaining(
- "\"pdpGroup\" value \" \" INVALID, is blank");
+ "\"pdpGroup\" value \" \" INVALID, is blank");
xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters_InvalidPdpType.json";
arguments.parse(xacmlPdpConfigParameters);
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)).hasMessageContaining(
- "\"pdpType\" value \"\" INVALID, is blank");
+ "\"pdpType\" value \"\" INVALID, is blank");
}
@Test
- public void testXacmlPdpParameterGroup_InvalidRestServerParameters() throws PolicyXacmlPdpException, IOException {
+ void testXacmlPdpParameterGroup_InvalidRestServerParameters() throws PolicyXacmlPdpException, IOException {
final String[] xacmlPdpConfigParameters =
{"-c", "parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json"};
@@ -162,15 +161,15 @@ public class TestXacmlPdpParameterHandler {
arguments.parse(xacmlPdpConfigParameters);
new String(Files.readAllBytes(
- Paths.get("src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt")));
+ Paths.get("src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt")));
assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments))
- .hasMessageContaining("validation error(s) on parameters from "
- + "\"parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json\"");
+ .hasMessageContaining("validation error(s) on parameters from "
+ + "\"parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json\"");
}
@Test
- public void testXacmlPdpParameterGroup_Exclusions() throws PolicyXacmlPdpException {
+ void testXacmlPdpParameterGroup_Exclusions() throws PolicyXacmlPdpException {
final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_Exclusions.json"};
final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments();
@@ -184,7 +183,7 @@ public class TestXacmlPdpParameterHandler {
}
@Test
- public void testXacmlPdpVersion() throws PolicyXacmlPdpException {
+ void testXacmlPdpVersion() throws PolicyXacmlPdpException {
final String[] xacmlPdpConfigParameters = {"-v"};
final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments();
final String version = arguments.parse(xacmlPdpConfigParameters);
@@ -192,7 +191,7 @@ public class TestXacmlPdpParameterHandler {
}
@Test
- public void testXacmlPdpHelp() throws PolicyXacmlPdpException {
+ void testXacmlPdpHelp() throws PolicyXacmlPdpException {
final String[] xacmlPdpConfigParameters = {"-h"};
final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments();
final String help = arguments.parse(xacmlPdpConfigParameters);
@@ -200,12 +199,12 @@ public class TestXacmlPdpParameterHandler {
}
@Test
- public void testXacmlPdpInvalidOption() {
+ void testXacmlPdpInvalidOption() {
final String[] xacmlPdpConfigParameters = {"-d"};
final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments();
assertThatThrownBy(() ->
arguments.parse(xacmlPdpConfigParameters)
).isInstanceOf(PolicyXacmlPdpException.class)
- .hasMessageContaining("invalid command line arguments specified");
+ .hasMessageContaining("invalid command line arguments specified");
}
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java
index 5dddec30..5bfc4372 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestAbbreviateDecisionResults.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020,2023 Nordix Foundation
+ * Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +22,9 @@
package org.onap.policy.pdpx.main.rest;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.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 jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.MediaType;
@@ -42,18 +42,15 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.endpoints.http.client.HttpClient;
-import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
import org.onap.policy.common.endpoints.http.client.internal.JerseyClient;
import org.onap.policy.common.endpoints.parameters.RestClientParameters;
import org.onap.policy.common.endpoints.parameters.RestServerParameters;
import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
-import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.network.NetworkUtil;
import org.onap.policy.models.decisions.concepts.DecisionRequest;
@@ -72,23 +69,21 @@ import org.onap.policy.xacml.pdp.application.monitoring.MonitoringPdpApplication
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TestAbbreviateDecisionResults {
+class TestAbbreviateDecisionResults {
private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
private static int port;
private static Main main;
private static HttpClient client;
- private static CommonTestData testData = new CommonTestData();
+ private static final CommonTestData testData = new CommonTestData();
- private static Properties properties = new Properties();
+ private static final Properties properties = new Properties();
private static File propertiesFile;
private static XacmlApplicationServiceProvider service;
- private static RestClientParameters policyApiParameters;
-
- @ClassRule
- public static final TemporaryFolder appsFolder = new TemporaryFolder();
+ @TempDir
+ static Path appsFolder;
/**
* BeforeClass setup environment.
@@ -96,17 +91,15 @@ public class TestAbbreviateDecisionResults {
* @throws IOException Cannot create temp apps folder
* @throws Exception exception if service does not start
*/
- @BeforeClass
- public static void beforeClass() throws Exception {
+ @BeforeAll
+ static void beforeClass() throws Exception {
port = NetworkUtil.allocPort();
//
// Copy test directory over of the application directories
//
Path src = Paths.get("src/test/resources/apps");
- File apps = appsFolder.newFolder("apps");
- Files.walk(src).forEach(source -> {
- copy(source, apps.toPath().resolve(src.relativize(source)));
- });
+ File apps = appsFolder.resolve("apps").toFile();
+ Files.walk(src).forEach(source -> copy(source, apps.toPath().resolve(src.relativize(source))));
// Start the Monitoring Application
startXacmlApplicationService(apps);
@@ -116,18 +109,19 @@ public class TestAbbreviateDecisionResults {
// Create parameters for XacmlPdPService
RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port),
- RestServerParameters.class);
- policyApiParameters = testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ RestServerParameters.class);
+ RestClientParameters policyApiParameters =
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false),
- TopicParameterGroup.class);
+ TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- apps.getAbsolutePath().toString()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ apps.getAbsolutePath()), XacmlApplicationParameters.class);
XacmlPdpParameterGroup params =
- new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters,
+ new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters,
topicParameterGroup, xacmlApplicationParameters);
StandardCoder gson = new StandardCoder();
- File fileParams = appsFolder.newFile("params.json");
+ File fileParams = appsFolder.resolve("params.json").toFile();
String jsonParams = gson.encode(params);
LOGGER.info("Creating new params: {}", jsonParams);
Files.write(fileParams.toPath(), jsonParams.getBytes());
@@ -151,8 +145,8 @@ public class TestAbbreviateDecisionResults {
/**
* Clean up.
*/
- @AfterClass
- public static void after() throws PolicyXacmlPdpException {
+ @AfterAll
+ static void after() {
stopXacmlPdpService(main);
client.shutdown();
}
@@ -162,7 +156,7 @@ public class TestAbbreviateDecisionResults {
* should have been removed from the response.
*/
@Test
- public void testAbbreviateDecisionResult() throws HttpClientConfigException {
+ void testAbbreviateDecisionResult() {
LOGGER.info("Running testAbbreviateDecisionResult");
@@ -192,19 +186,18 @@ public class TestAbbreviateDecisionResults {
}
private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
- final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
- return new Main(XacmlPdpConfigParameters);
+ final String[] xacmlPdpConfigParameters = {"-c", params.getAbsolutePath()};
+ return new Main(xacmlPdpConfigParameters);
}
- private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
+ private static void stopXacmlPdpService(final Main main) {
main.shutdown();
}
/**
* Performs the POST request to Decision API.
- *
*/
- private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
+ private DecisionResponse getDecision(DecisionRequest request) {
Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
Response response = client.post("", entityRequest, Collections.emptyMap());
@@ -215,10 +208,9 @@ public class TestAbbreviateDecisionResults {
/**
* Create HttpClient.
- *
*/
private static HttpClient getNoAuthHttpClient()
- throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
+ throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
RestClientParameters clientParams = new RestClientParameters();
clientParams.setClientName("testName");
clientParams.setUseHttps(false);
@@ -248,22 +240,22 @@ public class TestAbbreviateDecisionResults {
* @param apps - the path to xacml.properties file
*/
private static void startXacmlApplicationService(File apps)
- throws XacmlApplicationException, CoderException, IOException {
+ throws XacmlApplicationException, IOException {
LOGGER.info("****** Starting Xacml Application Service ******");
//
// Setup our temporary folder
//
XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
new File(apps, "monitoring/" + filename).delete();
- return appsFolder.newFile("apps/monitoring/" + filename);
+ return appsFolder.resolve("apps/monitoring/" + filename).toFile();
};
propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
- "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
+ "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
//
// Load XacmlApplicationServiceProvider service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
- .load(XacmlApplicationServiceProvider.class);
+ .load(XacmlApplicationServiceProvider.class);
//
// Look for our class instance and save it
//
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java
index 93d04ce0..9e2c9893 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestDecision.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +22,7 @@
package org.onap.policy.pdpx.main.rest;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -36,16 +36,13 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.endpoints.http.client.HttpClient;
import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
@@ -66,27 +63,28 @@ import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TestDecision {
+class TestDecision {
private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
private static int port;
private static Main main;
private static HttpClient client;
- private static CommonTestData testData = new CommonTestData();
+ private static final CommonTestData testData = new CommonTestData();
private static final String APPLICATION_XACML_XML = "application/xacml+xml";
private static final String APPLICATION_XACML_JSON = "application/xacml+json";
- @ClassRule
- public static final TemporaryFolder appsFolder = new TemporaryFolder();
+ @TempDir
+ static Path appsFolder;
/**
* BeforeClass setup environment.
+ *
* @throws IOException Cannot create temp apps folder
- * @throws Exception exception if service does not start
+ * @throws Exception exception if service does not start
*/
- @BeforeClass
- public static void beforeClass() throws Exception {
+ @BeforeAll
+ static void beforeClass() throws Exception {
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
@@ -96,7 +94,7 @@ public class TestDecision {
// Copy test directory over of the application directories
//
Path src = Paths.get("src/test/resources/apps");
- File apps = appsFolder.newFolder("apps");
+ File apps = appsFolder.resolve("apps").toFile();
Files.walk(src).forEach(source -> {
copy(source, apps.toPath().resolve(src.relativize(source)));
});
@@ -106,17 +104,17 @@ public class TestDecision {
RestServerParameters rest =
testData.toObject(testData.getRestServerParametersMap(port), RestServerParameters.class);
RestClientParameters policyApiParameters =
- testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
+ testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
TopicParameterGroup topicParameterGroup =
- testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
+ testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- apps.getAbsolutePath().toString()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ apps.getAbsolutePath()), XacmlApplicationParameters.class);
XacmlPdpParameterGroup params =
- new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters,
- topicParameterGroup, xacmlApplicationParameters);
+ new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters,
+ topicParameterGroup, xacmlApplicationParameters);
final Gson gson = new GsonBuilder().create();
- File fileParams = appsFolder.newFile("params.json");
+ File fileParams = appsFolder.resolve("params.json").toFile();
String jsonParams = gson.toJson(params);
LOGGER.info("Creating new params: {}", jsonParams);
Files.write(fileParams.toPath(), jsonParams.getBytes());
@@ -137,14 +135,14 @@ public class TestDecision {
client = getNoAuthHttpClient();
}
- @AfterClass
- public static void after() throws PolicyXacmlPdpException {
+ @AfterAll
+ static void after() {
stopXacmlPdpService(main);
client.shutdown();
}
@Test
- public void testDecision_UnsupportedAction() throws Exception {
+ void testDecision_UnsupportedAction() {
LOGGER.info("Running test testDecision_UnsupportedAction");
DecisionRequest request = new DecisionRequest();
@@ -164,8 +162,7 @@ public class TestDecision {
}
@Test
- public void testDecision_Guard() throws KeyManagementException, NoSuchAlgorithmException,
- ClassNotFoundException {
+ void testDecision_Guard() {
LOGGER.info("Running test testDecision_Guard");
DecisionRequest request = new DecisionRequest();
@@ -184,17 +181,17 @@ public class TestDecision {
}
@Test
- public void testDecision_Native() throws IOException {
+ void testDecision_Native() throws IOException {
LOGGER.info("Running test testDecision_Native");
String xmlRequestAsString = ResourceUtils.getResourceAsString(
- "src/test/resources/decisions/decision.native.request.xml");
+ "src/test/resources/decisions/decision.native.request.xml");
if (xmlRequestAsString == null) {
throw new IOException("failed to read the xml request");
}
String jsonRequestAsString = ResourceUtils.getResourceAsString(
- "src/test/resources/decisions/decision.native.request.json");
+ "src/test/resources/decisions/decision.native.request.json");
if (jsonRequestAsString == null) {
throw new IOException("failed to read the json request");
}
@@ -209,11 +206,11 @@ public class TestDecision {
}
private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
- final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath()};
- return new Main(XacmlPdpConfigParameters);
+ final String[] xacmlPdpConfigParameters = {"-c", params.getAbsolutePath()};
+ return new Main(xacmlPdpConfigParameters);
}
- private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
+ private static void stopXacmlPdpService(final Main main) {
main.shutdown();
}
@@ -246,10 +243,10 @@ public class TestDecision {
private static HttpClient getNoAuthHttpClient() throws HttpClientConfigException {
return HttpClientFactoryInstance.getClientFactory().build(RestClientParameters.builder()
- .clientName("testDecisionClient")
- .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port)
- .basePath("policy/pdpx/v1")
- .userName("healthcheck").password("zb!XztG34").managed(true).build());
+ .clientName("testDecisionClient")
+ .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port)
+ .basePath("policy/pdpx/v1")
+ .userName("healthcheck").password("zb!XztG34").managed(true).build());
}
private static void copy(Path source, Path dest) {
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java
index 1b8411e5..e94830e6 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestGuardOverrideApplication.java
@@ -3,6 +3,7 @@
* 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.
@@ -58,13 +59,9 @@ public class TestGuardOverrideApplication extends GuardPdpApplication {
@Override
public boolean canSupportPolicyType(ToscaConceptIdentifier policyTypeId) {
- boolean canSuper = super.canSupportPolicyType(policyTypeId);
- if (canSuper) {
- return canSuper;
- }
- if (MY_EXTRAGUARD_POLICY_TYPE.equals(policyTypeId.getName())) {
+ if (super.canSupportPolicyType(policyTypeId)) {
return true;
}
- return false;
+ return MY_EXTRAGUARD_POLICY_TYPE.equals(policyTypeId.getName());
}
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java
index f774e022..ae9f6574 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java
@@ -32,7 +32,7 @@ import org.onap.policy.pdpx.main.rest.model.StatisticsReport;
* Class to perform unit testing of {@link StatisticsReport}.
*
*/
-public class TestStatisticsReport {
+class TestStatisticsReport {
static StatisticsReport report;
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java
index 2cac6dcc..6be2e7a0 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021-2022 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,12 +21,12 @@
package org.onap.policy.pdpx.main.rest;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import jakarta.ws.rs.client.Invocation;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.endpoints.report.HealthCheckReport;
import org.onap.policy.pdpx.main.CommonRest;
import org.onap.policy.pdpx.main.XacmlState;
@@ -35,10 +35,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Class to perform unit test of {@link XacmlPdpRestServer}.
- *
+ * Class to perform unit test of {@link org.onap.policy.pdpx.main.startstop.XacmlPdpRestServer}.
*/
-public class TestXacmlPdpRestServer extends CommonRest {
+class TestXacmlPdpRestServer extends CommonRest {
private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpRestServer.class);
private static final String NOT_ALIVE = "not alive";
@@ -51,16 +50,16 @@ public class TestXacmlPdpRestServer extends CommonRest {
private int nupdates = 0;
@Test
- public void testHealthCheckSuccess() throws Exception {
+ void testHealthCheckSuccess() throws Exception {
LOGGER.info("***************************** Running testHealthCheckSuccess *****************************");
final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
LOGGER.info("test1HealthCheckSuccess health report {}", report);
- validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
+ validateHealthCheckReport(true, 200, ALIVE, report);
}
@Test
- public void testHealthCheckFailure() throws Exception {
+ void testHealthCheckFailure() throws Exception {
LOGGER.info("***************************** Running testHealthCheckFailure *****************************");
markActivatorDead();
@@ -68,20 +67,20 @@ public class TestXacmlPdpRestServer extends CommonRest {
final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
LOGGER.info("testHealthCheckFailure health report {}", report);
- validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report);
+ validateHealthCheckReport(false, 500, NOT_ALIVE, report);
}
@Test
- public void testHttpsHealthCheckSuccess() throws Exception {
+ void testHttpsHealthCheckSuccess() throws Exception {
LOGGER.info("***************************** Running testHttpsHealthCheckSuccess *****************************");
final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
LOGGER.info("testHttpsHealthCheckSuccess health report {}", report);
- validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
+ validateHealthCheckReport(true, 200, ALIVE, report);
}
@Test
- public void testStatistics_200() throws Exception {
+ void testStatistics_200() throws Exception {
LOGGER.info("***************************** Running testStatistics_200 *****************************");
Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
@@ -95,7 +94,7 @@ public class TestXacmlPdpRestServer extends CommonRest {
}
@Test
- public void testStatistics_500() throws Exception {
+ void testStatistics_500() throws Exception {
LOGGER.info("***************************** Running testStatistics_500 *****************************");
markActivatorDead();
@@ -107,7 +106,7 @@ public class TestXacmlPdpRestServer extends CommonRest {
}
@Test
- public void testHttpsStatistic() throws Exception {
+ void testHttpsStatistic() throws Exception {
LOGGER.info("***************************** Running testHttpsStatistic *****************************");
final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
@@ -151,10 +150,10 @@ public class TestXacmlPdpRestServer extends CommonRest {
assertEquals(decisionsMap, report.getApplicationMetrics());
}
- private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
- final String message, final HealthCheckReport report) {
- assertEquals(name, report.getName());
- assertEquals(url, report.getUrl());
+ private void validateHealthCheckReport(final boolean healthy, final int code,
+ final String message, final HealthCheckReport report) {
+ assertEquals(TestXacmlPdpRestServer.NAME, report.getName());
+ assertEquals(TestXacmlPdpRestServer.SELF, report.getUrl());
assertEquals(healthy, report.isHealthy());
assertEquals(code, report.getCode());
assertEquals(message, report.getMessage());
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java
index f72ae4f4..236e6fbc 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpServiceFilter.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,15 +29,15 @@ import static org.mockito.Mockito.when;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.junit.jupiter.MockitoExtension;
-@RunWith(MockitoJUnitRunner.class)
-public class TestXacmlPdpServiceFilter {
+@ExtendWith(MockitoExtension.class)
+class TestXacmlPdpServiceFilter {
// pick an arbitrary service
private static final String PERM_SVC = XacmlPdpServiceFilter.PERMANENT_SERVICES.iterator().next();
@@ -56,8 +56,8 @@ public class TestXacmlPdpServiceFilter {
/**
* Initializes the fields.
*/
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
XacmlPdpServiceFilter.disableApi();
filterChain = (req, resp) -> {
@@ -69,7 +69,7 @@ public class TestXacmlPdpServiceFilter {
}
@Test
- public void testDoFilter() throws Exception {
+ void testDoFilter() throws Exception {
XacmlPdpServiceFilter.enableApi();
lenient().when(request.getRequestURI()).thenReturn("/other");
assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK);
@@ -79,7 +79,7 @@ public class TestXacmlPdpServiceFilter {
* Tests doFilter() when the API is disabled, but a permanent service is requested.
*/
@Test
- public void testDoFilter_DisabledPermanentServiceReq() throws Exception {
+ void testDoFilter_DisabledPermanentServiceReq() throws Exception {
XacmlPdpServiceFilter.disableApi();
when(request.getRequestURI()).thenReturn(PERM_SVC);
assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK);
@@ -89,7 +89,7 @@ public class TestXacmlPdpServiceFilter {
* Tests doFilter() when the API is disabled, but a permanent service is requested, with a leading slash.
*/
@Test
- public void testDoFilter_DisabledPermanentServiceReqLeadingSlash() throws Exception {
+ void testDoFilter_DisabledPermanentServiceReqLeadingSlash() throws Exception {
XacmlPdpServiceFilter.disableApi();
when(request.getRequestURI()).thenReturn("/" + PERM_SVC);
assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK);
@@ -99,7 +99,7 @@ public class TestXacmlPdpServiceFilter {
* Tests doFilter() when the API is disabled, but a permanent service is requested, with extra URI prefix.
*/
@Test
- public void testDoFilter_DisabledPermanentServiceReqExtraUri() throws Exception {
+ void testDoFilter_DisabledPermanentServiceReqExtraUri() throws Exception {
XacmlPdpServiceFilter.disableApi();
when(request.getRequestURI()).thenReturn("/some/stuff/" + PERM_SVC);
assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK);
@@ -110,7 +110,7 @@ public class TestXacmlPdpServiceFilter {
* the service name.
*/
@Test
- public void testDoFilter_DisabledPermanentServiceReqExtraChars() throws Exception {
+ void testDoFilter_DisabledPermanentServiceReqExtraChars() throws Exception {
XacmlPdpServiceFilter.disableApi();
when(request.getRequestURI()).thenReturn("/ExtraStuff" + PERM_SVC);
assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_CONFLICT);
@@ -120,24 +120,14 @@ public class TestXacmlPdpServiceFilter {
* Tests doFilter() when the API is disabled and an API service is requested.
*/
@Test
- public void testDoFilter_DisabledApiReq() throws Exception {
+ void testDoFilter_DisabledApiReq() throws Exception {
XacmlPdpServiceFilter.disableApi();
when(request.getRequestURI()).thenReturn("/other");
assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_CONFLICT);
}
- /**
- * Tests doFilter() when the API is disabled and an API service is requested.
- */
- @Test
- public void testDoFilter_EnabledApiReq() throws Exception {
- XacmlPdpServiceFilter.enableApi();
- lenient().when(request.getRequestURI()).thenReturn("/other");
- assertThat(getFilterResponse()).isEqualTo(HttpServletResponse.SC_OK);
- }
-
@Test
- public void testEnableApi_testDisableApi_testIsApiEnabled() {
+ void testEnableApi_testDisableApi_testIsApiEnabled() {
XacmlPdpServiceFilter.enableApi();
assertThat(XacmlPdpServiceFilter.isApiEnabled()).isTrue();
@@ -148,9 +138,10 @@ public class TestXacmlPdpServiceFilter {
/**
* Invokes doFilter().
+ *
* @return the response code set by the filter
*/
- private int getFilterResponse() throws Exception {
+ private int getFilterResponse() throws Exception {
filter.doFilter(request, response, filterChain);
// should only be called once
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java
index 856a29a3..45d3dfc5 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2022 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,11 +22,11 @@
package org.onap.policy.pdpx.main.rest;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.onap.policy.pdpx.main.CommonRest;
import org.onap.policy.pdpx.main.rest.model.StatisticsReport;
import org.slf4j.Logger;
@@ -33,16 +34,15 @@ import org.slf4j.LoggerFactory;
/**
* Class to perform unit test of {@link XacmlPdpRestController}.
- *
*/
-public class TestXacmlPdpStatistics extends CommonRest {
+class TestXacmlPdpStatistics extends CommonRest {
private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpStatistics.class);
private int nupdates = 0;
@Test
- public void testXacmlPdpStatistics_200() throws Exception {
+ void testXacmlPdpStatistics_200() throws Exception {
LOGGER.info("*************************** Running testXacmlPdpStatistics_200 ***************************");
StatisticsReport report = getXacmlPdpStatistics();
validateReport(report, 0, 200, new HashMap<>());
@@ -52,7 +52,7 @@ public class TestXacmlPdpStatistics extends CommonRest {
}
@Test
- public void testXacmlPdpStatistics_500() throws Exception {
+ void testXacmlPdpStatistics_500() throws Exception {
LOGGER.info("***************************** Running testXacmlPdpStatistics_500 *****************************");
markActivatorDead();
final StatisticsReport report = getXacmlPdpStatistics();
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java
index b04f44fb..e4a61d53 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/XacmlPdpApplicationManagerTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2020-2022 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.
@@ -31,10 +32,9 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
@@ -50,28 +50,28 @@ import org.onap.policy.xacml.pdp.application.optimization.OptimizationPdpApplica
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class XacmlPdpApplicationManagerTest {
+class XacmlPdpApplicationManagerTest {
private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManagerTest.class);
private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
private static Path appsDirectory;
private static ToscaServiceTemplate completedJtst;
private static final CommonTestData testData = new CommonTestData();
- @ClassRule
- public static final TemporaryFolder appsFolder = new TemporaryFolder();
+ @TempDir
+ static Path appsFolder;
/**
* setupTestEnvironment.
*
* @throws Exception Exception if anything is missing
*/
- @BeforeClass
- public static void setupTestEnvironment() throws Exception {
+ @BeforeAll
+ static void setupTestEnvironment() throws Exception {
//
// Load an example policy
//
String policyYaml = ResourceUtils
- .getResourceAsString("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml");
+ .getResourceAsString("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml");
//
// Serialize it into a class
//
@@ -82,13 +82,13 @@ public class XacmlPdpApplicationManagerTest {
throw new XacmlApplicationException("Failed to decode policy from resource file", e);
}
//
- // Make sure all the fields are setup properly
+ // Make sure all the fields are set up properly
//
JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
jtst.fromAuthorative(serviceTemplate);
completedJtst = jtst.toAuthorative();
//
- // We need at least 1 policies
+ // We need at least 1 policy
//
assertThat(completedJtst).isNotNull();
assertThat(completedJtst.getToscaTopologyTemplate().getPolicies()).isNotEmpty();
@@ -96,20 +96,20 @@ public class XacmlPdpApplicationManagerTest {
// Copy test directory over of the application directories
//
Path src = Paths.get("src/test/resources/apps");
- File apps = appsFolder.newFolder("apps");
+ File apps = appsFolder.resolve("apps").toFile();
Files.walk(src).forEach(source -> copy(source, apps.toPath().resolve(src.relativize(source))));
appsDirectory = apps.toPath();
}
@Test
- public void testXacmlPdpApplicationManagerBadPath() throws Exception {
+ void testXacmlPdpApplicationManagerBadPath() throws Exception {
//
- // Make up a non existent directory to initialize from
+ // Make up a non-existent directory to initialize from
//
- Path nonExistentPath = Paths.get(appsFolder.getRoot().getAbsolutePath(), "nonexistent");
+ Path nonExistentPath = Paths.get(appsFolder.toFile().getAbsolutePath(), "nonexistent");
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- nonExistentPath.toString()), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ nonExistentPath.toString()), XacmlApplicationParameters.class);
//
// Create our app manager
//
@@ -132,12 +132,12 @@ public class XacmlPdpApplicationManagerTest {
}
@Test
- public void testXacmlPdpApplicationManagerSimple() {
+ void testXacmlPdpApplicationManagerSimple() {
final String[] exclusions = {"org.onap.policy.xacml.pdp.application.guard.GuardPdpApplication",
- "org.onap.policy.xacml.pdp.application.match.MatchPdpApplication" };
+ "org.onap.policy.xacml.pdp.application.match.MatchPdpApplication"};
final XacmlApplicationParameters xacmlApplicationParameters =
- testData.toObject(testData.getXacmlapplicationParametersMap(false,
- appsDirectory.toString(), exclusions), XacmlApplicationParameters.class);
+ testData.toObject(testData.getXacmlapplicationParametersMap(false,
+ appsDirectory.toString(), exclusions), XacmlApplicationParameters.class);
XacmlPdpApplicationManager manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, null);
//
// Test the basics from the startup
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java
index 2a0a5524..0dcd2fa1 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/CommonSerialization.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +21,8 @@
package org.onap.policy.pdpx.main.rest.serialization;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.att.research.xacml.api.Request;
import com.att.research.xacml.api.Response;
@@ -46,14 +46,11 @@ public class CommonSerialization {
assertFalse(getter.apply(null, null, null, null));
// valid media type and class type
- assertTrue("writeable " + subType, getter.apply(
- REQUEST_CLASS, null, null, new MediaType(primaryType, subType)));
- assertTrue("writeable " + subType, getter.apply(
- RESPONSE_CLASS, null, null, new MediaType(primaryType, subType)));
+ assertTrue(getter.apply(REQUEST_CLASS, null, null, new MediaType(primaryType, subType)));
+ assertTrue(getter.apply(RESPONSE_CLASS, null, null, new MediaType(primaryType, subType)));
// valid media type but invalid class type
- assertFalse(getter.apply(
- GENERAL_CLASS, null, null, new MediaType(primaryType, subType)));
+ assertFalse(getter.apply(GENERAL_CLASS, null, null, new MediaType(primaryType, subType)));
// null subtype or invalid media type
assertFalse(getter.apply(null, null, null, new MediaType(primaryType, null)));
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java
index 31d6c60f..20b4336c 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonExceptionMapper.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,25 +21,25 @@
package org.onap.policy.pdpx.main.rest.serialization;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
-public class TestXacmlJsonExceptionMapper {
+class TestXacmlJsonExceptionMapper {
private XacmlJsonExceptionMapper mapper;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
mapper = new XacmlJsonExceptionMapper();
}
@Test
- public void testToResponse() throws CoderException {
+ void testToResponse() throws CoderException {
final IOException writeToEx = new IOException("failed to convert a json response to a string");
final IOException readFromEx = new IOException("failed to decode incoming request string to a json request");
final IOException unexpectedEx = new IOException("unexpected exception");
@@ -49,10 +49,13 @@ public class TestXacmlJsonExceptionMapper {
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), writeToResp.getStatus());
assertEquals("{'errorDetails':'invalid JSON xacml response'}".replace('\'', '"'),
- new StandardCoder().encode(writeToResp.getEntity()));
+ new StandardCoder().encode(writeToResp.getEntity()));
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), readFromResp.getStatus());
assertEquals("{'errorDetails':'invalid JSON xacml request'}".replace('\'', '"'),
- new StandardCoder().encode(readFromResp.getEntity()));
+ new StandardCoder().encode(readFromResp.getEntity()));
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), unexpectedResp.getStatus());
+ writeToResp.close();
+ readFromResp.close();
+ unexpectedResp.close();
}
} \ No newline at end of file
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java
index 1dbbff9d..34e64004 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlJsonMessageBodyHandler.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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,8 +21,8 @@
package org.onap.policy.pdpx.main.rest.serialization;
-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 com.att.research.xacml.api.Request;
import com.att.research.xacml.api.RequestAttributes;
@@ -34,11 +35,11 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.resources.ResourceUtils;
-public class TestXacmlJsonMessageBodyHandler {
+class TestXacmlJsonMessageBodyHandler {
private static final String PRIMARY_TYPE = "application";
private static final String SUB_TYPE = "xacml+json";
@@ -50,35 +51,35 @@ public class TestXacmlJsonMessageBodyHandler {
private XacmlJsonMessageBodyHandler hdlr;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
hdlr = new XacmlJsonMessageBodyHandler();
}
@Test
- public void testIsWriteable() {
+ void testIsWriteable() {
CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isWriteable);
}
@Test
- public void testWriteTo() throws IOException, DOMStructureException, JSONStructureException {
+ void testWriteTo() throws IOException, DOMStructureException, JSONStructureException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Response resp = DOMResponse.load(ResourceUtils.getResourceAsString(
- "src/test/resources/decisions/decision.native.response.xml"));
+ "src/test/resources/decisions/decision.native.response.xml"));
hdlr.writeTo(resp, RESPONSE_CLASS, RESPONSE_CLASS, null, null, null, stream);
assertEquals(resp, JsonResponseTranslator.load(new ByteArrayInputStream(stream.toByteArray())));
}
@Test
- public void testIsReadable() {
+ void testIsReadable() {
CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isReadable);
}
@Test
@SuppressWarnings("unchecked")
- public void testReadFrom() throws IOException {
+ void testReadFrom() throws IOException {
Request req = hdlr.readFrom(REQUEST_CLASS, REQUEST_CLASS, null, null, null, ResourceUtils.getResourceAsStream(
- "src/test/resources/decisions/decision.native.request.json"));
+ "src/test/resources/decisions/decision.native.request.json"));
assertFalse(req.getCombinedDecision());
assertFalse(req.getReturnPolicyIdList());
assertEquals(3, req.getRequestAttributes().size());
@@ -87,16 +88,16 @@ public class TestXacmlJsonMessageBodyHandler {
RequestAttributes firstRequestAttributes = iter.next();
assertEquals(1, firstRequestAttributes.getAttributes().size());
assertEquals("Julius Hibbert", firstRequestAttributes.getAttributes().iterator().next()
- .getValues().iterator().next().getValue().toString());
+ .getValues().iterator().next().getValue().toString());
RequestAttributes secondRequestAttributes = iter.next();
assertEquals(1, secondRequestAttributes.getAttributes().size());
assertEquals("http://medico.com/record/patient/BartSimpson", secondRequestAttributes.getAttributes()
- .iterator().next().getValues().iterator().next().getValue().toString());
+ .iterator().next().getValues().iterator().next().getValue().toString());
RequestAttributes thirdRequestAttributes = iter.next();
assertEquals(1, thirdRequestAttributes.getAttributes().size());
assertEquals("read", thirdRequestAttributes.getAttributes().iterator().next()
- .getValues().iterator().next().getValue().toString());
+ .getValues().iterator().next().getValue().toString());
}
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java
index 3fd76c3b..1a6f7a0e 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlExceptionMapper.java
@@ -3,7 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,25 +21,25 @@
package org.onap.policy.pdpx.main.rest.serialization;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
-public class TestXacmlXmlExceptionMapper {
+class TestXacmlXmlExceptionMapper {
private XacmlXmlExceptionMapper mapper;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
mapper = new XacmlXmlExceptionMapper();
}
@Test
- public void testToResponse() throws CoderException {
+ void testToResponse() throws CoderException {
final IOException writeToEx = new IOException("failed to convert a dom response to a string");
final IOException readFromEx = new IOException("failed to decode incoming request string to a dom request");
final IOException unexpectedEx = new IOException("unexpected exception");
@@ -49,10 +49,13 @@ public class TestXacmlXmlExceptionMapper {
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), writeToResp.getStatus());
assertEquals("{'errorDetails':'invalid XML xacml response'}".replace('\'', '"'),
- new StandardCoder().encode(writeToResp.getEntity()));
+ new StandardCoder().encode(writeToResp.getEntity()));
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), readFromResp.getStatus());
assertEquals("{'errorDetails':'invalid XML xacml request'}".replace('\'', '"'),
- new StandardCoder().encode(readFromResp.getEntity()));
+ new StandardCoder().encode(readFromResp.getEntity()));
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), unexpectedResp.getStatus());
+ writeToResp.close();
+ readFromResp.close();
+ unexpectedResp.close();
}
} \ No newline at end of file
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java
index f2e4f4f6..f7938e3b 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/serialization/TestXacmlXmlMessageBodyHandler.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* 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,8 +21,8 @@
package org.onap.policy.pdpx.main.rest.serialization;
-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 com.att.research.xacml.api.Request;
import com.att.research.xacml.api.RequestAttributes;
@@ -32,11 +33,11 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.common.utils.resources.ResourceUtils;
-public class TestXacmlXmlMessageBodyHandler {
+class TestXacmlXmlMessageBodyHandler {
private static final String PRIMARY_TYPE = "application";
private static final String SUB_TYPE = "xacml+xml";
@@ -48,35 +49,35 @@ public class TestXacmlXmlMessageBodyHandler {
private XacmlXmlMessageBodyHandler hdlr;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
hdlr = new XacmlXmlMessageBodyHandler();
}
@Test
- public void testIsWriteable() {
+ void testIsWriteable() {
CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isWriteable);
}
@Test
- public void testWriteTo() throws IOException, DOMStructureException {
+ void testWriteTo() throws IOException, DOMStructureException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Response resp = DOMResponse.load(ResourceUtils.getResourceAsString(
- "src/test/resources/decisions/decision.native.response.xml"));
+ "src/test/resources/decisions/decision.native.response.xml"));
hdlr.writeTo(resp, RESPONSE_CLASS, RESPONSE_CLASS, null, null, null, stream);
assertEquals(resp, DOMResponse.load(new ByteArrayInputStream(stream.toByteArray())));
}
@Test
- public void testIsReadable() {
+ void testIsReadable() {
CommonSerialization.testIsWritableOrReadable(PRIMARY_TYPE, SUB_TYPE, hdlr::isReadable);
}
@Test
@SuppressWarnings("unchecked")
- public void testReadFrom() throws IOException {
+ void testReadFrom() throws IOException {
Request req = hdlr.readFrom(REQUEST_CLASS, REQUEST_CLASS, null, null, null, ResourceUtils.getResourceAsStream(
- "src/test/resources/decisions/decision.native.request.xml"));
+ "src/test/resources/decisions/decision.native.request.xml"));
assertFalse(req.getCombinedDecision());
assertFalse(req.getReturnPolicyIdList());
assertEquals(4, req.getRequestAttributes().size());
@@ -85,16 +86,16 @@ public class TestXacmlXmlMessageBodyHandler {
RequestAttributes firstRequestAttributes = iter.next();
assertEquals(1, firstRequestAttributes.getAttributes().size());
assertEquals("Julius Hibbert", firstRequestAttributes.getAttributes().iterator().next()
- .getValues().iterator().next().getValue().toString());
+ .getValues().iterator().next().getValue().toString());
RequestAttributes secondRequestAttributes = iter.next();
assertEquals(1, secondRequestAttributes.getAttributes().size());
assertEquals("http://medico.com/record/patient/BartSimpson", secondRequestAttributes.getAttributes()
- .iterator().next().getValues().iterator().next().getValue().toString());
+ .iterator().next().getValues().iterator().next().getValue().toString());
RequestAttributes thirdRequestAttributes = iter.next();
assertEquals(1, thirdRequestAttributes.getAttributes().size());
assertEquals("read", thirdRequestAttributes.getAttributes().iterator().next()
- .getValues().iterator().next().getValue().toString());
+ .getValues().iterator().next().getValue().toString());
}
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java
index 5e46b669..80e6f707 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,27 +24,27 @@ package org.onap.policy.pdpx.main.startstop;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.onap.policy.pdpx.main.CommonRest;
import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
/**
* Class to perform unit test of Main.
- *
*/
-public class TestMain extends CommonRest {
+class TestMain extends CommonRest {
private Main main;
/**
* Sets up properties and configuration.
+ *
* @throws Exception if an error occurs
*/
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
CommonRest.setUpBeforeClass();
@@ -53,7 +53,7 @@ public class TestMain extends CommonRest {
}
@Override
- @Before
+ @BeforeEach
public void setUp() {
main = null;
}
@@ -62,7 +62,7 @@ public class TestMain extends CommonRest {
* Shuts "main" down.
*/
@Override
- @After
+ @AfterEach
public void tearDown() {
if (main != null) {
main.shutdown();
@@ -70,7 +70,7 @@ public class TestMain extends CommonRest {
}
@Test
- public void testMain() throws PolicyXacmlPdpException {
+ void testMain() {
final String[] xacmlPdpConfigParameters = {"-c", CONFIG_FILE};
assertThatCode(() -> {
main = new Main(xacmlPdpConfigParameters);
@@ -80,30 +80,30 @@ public class TestMain extends CommonRest {
}
@Test
- public void testMain_NoArguments() {
+ void testMain_NoArguments() {
final String[] xacmlPdpConfigParameters = {};
assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class)
- .hasMessage("policy xacml pdp configuration file was not specified as an argument");
+ .hasMessage("policy xacml pdp configuration file was not specified as an argument");
}
@Test
- public void testMain_InvalidArguments() {
+ void testMain_InvalidArguments() {
final String[] xacmlPdpConfigParameters = {"parameters/XacmlPdpConfigParameters.json"};
assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class)
.hasMessage("too many command line arguments specified : [parameters/XacmlPdpConfigParameters.json]");
}
@Test
- public void testMain_Help() throws PolicyXacmlPdpException {
+ void testMain_Help() throws PolicyXacmlPdpException {
final String[] xacmlPdpConfigParameters = {"-h"};
- Assert.assertTrue(new Main(xacmlPdpConfigParameters).getArgumentMessage().contains("-h,--help"));
+ Assertions.assertTrue(new Main(xacmlPdpConfigParameters).getArgumentMessage().contains("-h,--help"));
}
@Test
- public void testMain_InvalidParameters() {
+ void testMain_InvalidParameters() {
final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidName.json"};
assertThatThrownBy(() -> new Main(xacmlPdpConfigParameters)).isInstanceOf(PolicyXacmlPdpException.class)
- .hasMessageContaining("validation error");
+ .hasMessageContaining("validation error");
}
}
diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java
index 61ba8b85..bdcbd99c 100644
--- a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java
+++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019,2023 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 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,17 +21,16 @@
package org.onap.policy.pdpx.main.startstop;
-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 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.onap.policy.pdpx.main.CommonRest;
-import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
import org.onap.policy.pdpx.main.parameters.CommonTestData;
import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterHandler;
@@ -40,7 +39,6 @@ import org.springframework.test.util.ReflectionTestUtils;
/**
* Class to perform unit test of XacmlPdpActivator.
- *
*/
public class TestXacmlPdpActivator extends CommonRest {
private static final String PROBE_FIELD_NAME = "probeHeartbeatTopicSec";
@@ -52,7 +50,7 @@ public class TestXacmlPdpActivator extends CommonRest {
/**
* Loads properties.
*/
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
CommonRest.setUpBeforeClass();
@@ -68,14 +66,14 @@ public class TestXacmlPdpActivator extends CommonRest {
* Creates the activator.
*/
@Override
- @Before
+ @BeforeEach
public void setUp() {
ReflectionTestUtils.setField(parGroup, PROBE_FIELD_NAME, 4);
activator = new XacmlPdpActivator(parGroup);
}
@Test
- public void testXacmlPdpActivator() throws Exception {
+ void testXacmlPdpActivator() {
assertFalse(activator.isAlive());
assertFalse(activator.isApiEnabled());
activator.start();
@@ -95,7 +93,7 @@ public class TestXacmlPdpActivator extends CommonRest {
}
@Test
- public void testXacmlPdpActivator_NoProbe() throws Exception {
+ void testXacmlPdpActivator_NoProbe() {
ReflectionTestUtils.setField(parGroup, PROBE_FIELD_NAME, 0);
activator = new XacmlPdpActivator(parGroup);
activator.start();
@@ -103,13 +101,13 @@ public class TestXacmlPdpActivator extends CommonRest {
}
@Test
- public void testGetCurrent_testSetCurrent() {
+ void testGetCurrent_testSetCurrent() {
XacmlPdpActivator.setCurrent(activator);
assertSame(activator, XacmlPdpActivator.getCurrent());
}
@Test
- public void testTerminate() throws Exception {
+ void testTerminate() {
activator.start();
activator.stop();
assertFalse(activator.isAlive());
@@ -117,10 +115,9 @@ public class TestXacmlPdpActivator extends CommonRest {
/**
* Teardown tests.
- * @throws PolicyXacmlPdpException on termination errors
*/
- @After
- public void teardown() throws PolicyXacmlPdpException {
+ @AfterEach
+ public void teardown() {
if (activator != null && activator.isAlive()) {
activator.stop();
}
diff --git a/pom.xml b/pom.xml
index 9fca14fc..8c8194cb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -3,7 +3,7 @@
ONAP Policy Engine - XACML PDP
================================================================================
Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2020,2023 Nordix Foundation.
+ Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation.
Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
@@ -57,23 +57,18 @@
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>io.cucumber</groupId>
- <artifactId>cucumber-java</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>io.cucumber</groupId>
- <artifactId>cucumber-junit</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
diff --git a/tutorials/tutorial-xacml-application/src/test/java/org/onap/policy/tutorial/tutorial/TutorialApplicationTest.java b/tutorials/tutorial-xacml-application/src/test/java/org/onap/policy/tutorial/tutorial/TutorialApplicationTest.java
index ee089195..85cf999f 100644
--- a/tutorials/tutorial-xacml-application/src/test/java/org/onap/policy/tutorial/tutorial/TutorialApplicationTest.java
+++ b/tutorials/tutorial-xacml-application/src/test/java/org/onap/policy/tutorial/tutorial/TutorialApplicationTest.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 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.
@@ -19,20 +20,20 @@
package org.onap.policy.tutorial.tutorial;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.att.research.xacml.api.Response;
import com.att.research.xacml.api.XACML3;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.TextFileUtils;
@@ -44,33 +45,33 @@ import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TutorialApplicationTest {
+class TutorialApplicationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(TutorialApplicationTest.class);
private static final Properties properties = new Properties();
private static XacmlApplicationServiceProvider service;
private static final StandardCoder gson = new StandardCoder();
- @ClassRule
- public static final TemporaryFolder policyFolder = new TemporaryFolder();
+ @TempDir
+ static Path policyFolder;
/**
* set up the tests.
*
* @throws Exception Should not have exceptions thrown.
*/
- @BeforeClass
- public static void setup() throws Exception {
+ @BeforeAll
+ static void setup() throws Exception {
//
// Set up our temporary folder
//
- XacmlPolicyUtils.FileCreator myCreator = policyFolder::newFile;
+ XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
File propertiesFile = XacmlPolicyUtils
.copyXacmlPropertiesContents("src/test/resources/xacml.properties", properties, myCreator);
//
// Load XacmlApplicationServiceProvider service
//
ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
- ServiceLoader.load(XacmlApplicationServiceProvider.class);
+ ServiceLoader.load(XacmlApplicationServiceProvider.class);
//
// Look for our class instance and save it
//
@@ -94,13 +95,13 @@ public class TutorialApplicationTest {
}
@Test
- public void testSingleDecision() throws CoderException, IOException {
+ void testSingleDecision() throws CoderException, IOException {
//
// Load a Decision request
//
DecisionRequest decisionRequest =
- gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/tutorial-decision-request.json"),
- DecisionRequest.class);
+ gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/tutorial-decision-request.json"),
+ DecisionRequest.class);
LOGGER.info("{}", gson.encode(decisionRequest, true));
//
// Test a decision - should start with a permit
@@ -112,7 +113,7 @@ public class TutorialApplicationTest {
// Check that there are attributes
//
assertThat(decision.getLeft().getAttributes()).isNotNull().hasSize(1)
- .containsKey(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
+ .containsKey(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
//
// This should be a "deny"
//
@@ -125,18 +126,18 @@ public class TutorialApplicationTest {
// Check that there are attributes
//
assertThat(decision.getLeft().getAttributes()).isNotNull().hasSize(1)
- .containsKey(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
+ .containsKey(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
}
@Test
- public void testMultiDecision() throws CoderException, IOException {
+ void testMultiDecision() throws CoderException, IOException {
//
// Load a Decision request
//
DecisionRequest decisionRequest = gson.decode(
- TextFileUtils.getTextFileAsString("src/test/resources/tutorial-decision-multi-request.json"),
- DecisionRequest.class);
+ TextFileUtils.getTextFileAsString("src/test/resources/tutorial-decision-multi-request.json"),
+ DecisionRequest.class);
LOGGER.info("{}", gson.encode(decisionRequest, true));
//
// Test a decision - should start with a permit