diff options
author | adheli.tavares <adheli.tavares@est.tech> | 2024-07-24 21:09:09 +0100 |
---|---|---|
committer | adheli.tavares <adheli.tavares@est.tech> | 2024-07-24 21:09:54 +0100 |
commit | 257358ffc369e0813bca5fa92b83710e3d97cfee (patch) | |
tree | 3bc494df192dc38fadc2e225cd8b09c88dd4884d /applications/common | |
parent | 66b1f3ead4f08893da0ea50aad25cd4831367b3c (diff) |
Convert unit tests from junit4 to junit5
Issue-ID: POLICY-5094
Change-Id: Id727408a5fd553aa08623a6ede1a56607b760e3f
Signed-off-by: adheli.tavares <adheli.tavares@est.tech>
Diffstat (limited to 'applications/common')
37 files changed, 811 insertions, 650 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 |