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/src/test | |
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/src/test')
22 files changed, 649 insertions, 490 deletions
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 |