From 577b34e9bdad94d0b1559a9917af3283124aeeda Mon Sep 17 00:00:00 2001 From: bobbymander Date: Wed, 13 Nov 2019 10:30:56 -0500 Subject: [PATCH] Few JUnit additions for PAP-REST Issue-ID: POLICY-2130 Change-Id: Ie9972bc0014def93acf04c4a2386585fb4accdef Signed-off-by: bobbymander --- .../org/onap/policy/pap/xacml/rest/Heartbeat.java | 35 +++++---- .../rest/components/CreateBrmsParamPolicy.java | 31 ++++---- .../onap/policy/pap/xacml/rest/HeartbeatTest.java | 50 +++++++++++++ .../pap/xacml/rest/components/BRMSPolicyTest.java | 47 +++++++++++- .../OptimizationDictionaryControllerTest.java | 85 +++++++++++++++------- .../pap/xacml/rest/handler/DeleteHandlerTest.java | 67 ++++++++++++++++- .../pap/xacml/rest/service/ImportServiceTest.java | 2 +- 7 files changed, 257 insertions(+), 60 deletions(-) diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java index 81e7c6778..920c3dd87 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java @@ -23,7 +23,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPStatus; import com.att.research.xacml.util.XACMLProperties; - +import com.google.common.annotations.VisibleForTesting; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; @@ -33,7 +33,6 @@ import java.net.UnknownHostException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; - import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -88,9 +87,9 @@ public class Heartbeat implements Runnable { public Heartbeat(PAPPolicyEngine papEngine2) { papEngine = papEngine2; this.heartbeatInterval = - Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); this.heartbeatTimeout = - Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); + Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); } @Override @@ -127,7 +126,8 @@ public class Heartbeat implements Runnable { } } - private void getPdpsFromGroup() { + @VisibleForTesting + protected void getPdpsFromGroup() { try { for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) { for (OnapPDP p : g.getOnapPdps()) { @@ -136,11 +136,12 @@ public class Heartbeat implements Runnable { } } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - "Heartbeat unable to read PDPs from PAPEngine"); + "Heartbeat unable to read PDPs from PAPEngine"); } } - private void notifyEachPdp() { + @VisibleForTesting + protected void notifyEachPdp() { HashMap idToUrlMap = new HashMap<>(); for (OnapPDP pdp : pdps) { // Check for shutdown @@ -163,14 +164,15 @@ public class Heartbeat implements Runnable { } } catch (MalformedURLException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, XACMLPAPSERVLET, - " PDP id '" + fullUrlString + "' is not a valid URL"); + " PDP id '" + fullUrlString + "' is not a valid URL"); } } updatePdpStatus(pdp, openPdpConnection(pdpUrl, pdp)); } } - private String openPdpConnection(URL pdpUrl, OnapPDP pdp) { + @VisibleForTesting + protected String openPdpConnection(URL pdpUrl, OnapPDP pdp) { // Do a GET with type HeartBeat String newStatus = ""; HttpURLConnection connection = null; @@ -197,25 +199,25 @@ public class Heartbeat implements Runnable { // anything else is an unexpected result newStatus = PDPStatus.Status.UNKNOWN.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " - + connection.getResponseCode() + ": " + pdp.getId()); + + connection.getResponseCode() + ": " + pdp.getId()); } } } catch (UnknownHostException e) { newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' NO_SUCH_HOST"); + HEARTBEATSTRING + pdp.getId() + "' NO_SUCH_HOST"); } catch (SocketTimeoutException e) { newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' connection timeout"); + HEARTBEATSTRING + pdp.getId() + "' connection timeout"); } catch (ConnectException e) { newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' cannot connect"); + HEARTBEATSTRING + pdp.getId() + "' cannot connect"); } catch (Exception e) { newStatus = PDPStatus.Status.UNKNOWN.toString(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET, - HEARTBEATSTRING + pdp.getId() + "' connect exception"); + HEARTBEATSTRING + pdp.getId() + "' connect exception"); } finally { // cleanup the connection if (connection != null) @@ -224,7 +226,8 @@ public class Heartbeat implements Runnable { return newStatus; } - private void updatePdpStatus(OnapPDP pdp, String newStatus) { + @VisibleForTesting + protected void updatePdpStatus(OnapPDP pdp, String newStatus) { if (!pdp.getStatus().getStatus().toString().equals(newStatus)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("previous status='" + pdp.getStatus().getStatus() + "' new Status='" + newStatus + "'"); @@ -233,7 +236,7 @@ public class Heartbeat implements Runnable { getPAPInstance().setPDPSummaryStatus(pdp, newStatus); } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, - "Unable to set state for PDP '" + pdp.getId()); + "Unable to set state for PDP '" + pdp.getId()); } } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java index c728f3bff..ffb902bc4 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java @@ -22,7 +22,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.std.IdentifierImpl; - +import com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -41,9 +41,7 @@ import java.util.Map.Entry; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; - import javax.script.SimpleBindings; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -57,7 +55,6 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; 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.apache.commons.io.FilenameUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -131,7 +128,7 @@ public class CreateBrmsParamPolicy extends Policy { out.close(); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", - "Exception saving configuration file"); + "Exception saving configuration file"); } } @@ -148,6 +145,7 @@ public class CreateBrmsParamPolicy extends Policy { } // Validations for Config form + @Override public boolean validateConfigForm() { // Validating mandatory Fields. @@ -252,7 +250,7 @@ public class CreateBrmsParamPolicy extends Policy { } } String param = - params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""); + params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""); String[] components = param.split(":"); String caption = ""; for (int i = 0; i < components.length; i++) { @@ -283,7 +281,7 @@ public class CreateBrmsParamPolicy extends Policy { } } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy", - "Exception parsing file in findType"); + "Exception parsing file in findType"); } } return mapFieldType; @@ -327,7 +325,7 @@ public class CreateBrmsParamPolicy extends Policy { try { body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " - + "purpose. \n\t " + "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); + + "purpose. \n\t " + "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); body.append("<%$Values="); for (Map.Entry entry : ruleAndUIValue.entrySet()) { String uiKey = entry.getKey(); @@ -339,7 +337,7 @@ public class CreateBrmsParamPolicy extends Policy { body.append(valueFromDictionary + "\n"); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", - "Exception saving policy"); + "Exception saving policy"); } saveConfigurations(policyName, body.toString()); @@ -407,7 +405,7 @@ public class CreateBrmsParamPolicy extends Policy { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", - "Exception creating ACCESS URI"); + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -429,7 +427,7 @@ public class CreateBrmsParamPolicy extends Policy { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", - "Exception creating Config URI"); + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -461,7 +459,8 @@ public class CreateBrmsParamPolicy extends Policy { } // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + @VisibleForTesting + protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) { // Policy Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); @@ -546,8 +545,8 @@ public class CreateBrmsParamPolicy extends Policy { // Adding Controller Information. if (policyAdapter.getBrmsController() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add(createResponseAttributes( - "controller:" + policyAdapter.getBrmsController(), + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("controller:" + policyAdapter.getBrmsController(), brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); } @@ -561,14 +560,14 @@ public class CreateBrmsParamPolicy extends Policy { key.append(dependencyName + ","); } advice.getAttributeAssignmentExpression() - .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); + .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); } // Dynamic Field Config Attributes. Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); for (Entry map : dynamicFieldConfigAttributes.entrySet()) { advice.getAttributeAssignmentExpression() - .add(createResponseAttributes("key:" + map.getKey(), map.getValue())); + .add(createResponseAttributes("key:" + map.getKey(), map.getValue())); } // Risk Attributes diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java index 13fb81d17..33b7f8be6 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java @@ -20,13 +20,24 @@ package org.onap.policy.pap.xacml.rest; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.att.research.xacml.api.pap.PAPException; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.onap.policy.xacml.std.pap.StdPDPGroup; public class HeartbeatTest { @Test @@ -38,4 +49,43 @@ public class HeartbeatTest { hb.terminate(); assertFalse(hb.isHeartBeatRunning()); } + + @Test + public void testGetPdps() throws PAPException, IOException { + Set pdpGroups = new HashSet(); + StdPDPGroup pdpGroup = new StdPDPGroup(); + OnapPDP pdp = new StdPDP(); + pdpGroup.addPDP(pdp); + pdpGroups.add(pdpGroup); + PAPPolicyEngine pap = Mockito.mock(PAPPolicyEngine.class); + Mockito.when(pap.getOnapPDPGroups()).thenReturn(pdpGroups); + Heartbeat hb = new Heartbeat(pap); + hb.getPdpsFromGroup(); + assertFalse(hb.isHeartBeatRunning()); + + assertThatCode(hb::notifyEachPdp).doesNotThrowAnyException(); + assertThatThrownBy(hb::run).isInstanceOf(Exception.class); + assertThatThrownBy(hb::notifyEachPdp).isInstanceOf(Exception.class); + } + + @Test + public void testOpen() throws MalformedURLException { + Heartbeat hb = new Heartbeat(null); + OnapPDP pdp = new StdPDP(); + + assertThatCode(() -> { + URL url = new URL("http://onap.org"); + hb.openPdpConnection(url, pdp); + }).doesNotThrowAnyException(); + + assertThatCode(() -> { + URL url = new URL("http://1.2.3.4"); + hb.openPdpConnection(url, pdp); + }).doesNotThrowAnyException(); + + assertThatCode(() -> { + URL url = new URL("http://fakesite.fakenews"); + hb.openPdpConnection(url, pdp); + }).doesNotThrowAnyException(); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java index 333d878ca..5c1d3dd76 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java @@ -22,15 +22,22 @@ package org.onap.policy.pap.xacml.rest.components; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import com.att.research.xacml.api.pap.PAPException; import java.io.IOException; - +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; +import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; public class BRMSPolicyTest { @@ -68,4 +75,42 @@ public class BRMSPolicyTest { String userID = "testID"; assertEquals(1, template.addRule(rule, ruleName, description, userID).size()); } + + @Test + public void testCreateBrmsParamPolicyAdapter() throws PAPException { + Map brmsParamBody = new HashMap(); + brmsParamBody.put("key", "value"); + + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setHighestVersion(1); + adapter.setPolicyType("Config"); + adapter.setBrmsParamBody(brmsParamBody); + adapter.setNewFileName("policyName.1.xml"); + Map dynamicFieldConfigAttributes = new HashMap(); + dynamicFieldConfigAttributes.put("key", "value"); + adapter.setDynamicFieldConfigAttributes(dynamicFieldConfigAttributes); + CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy(adapter); + String ruleContents = "contents"; + + assertThatCode(() -> policy.saveConfigurations("name.xml", "rules")).doesNotThrowAnyException(); + try { + policy.prepareToSave(); + policy.savePolicies(); + } catch (Exception ex) { + // Ignore + } + + assertThatThrownBy(() -> policy.expandConfigBody(ruleContents, brmsParamBody)) + .isInstanceOf(NullPointerException.class); + assertTrue(policy.validateConfigForm()); + policy.getAdviceExpressions(1, "name.1.xml"); + assertNotNull(policy.getCorrectPolicyDataObject()); + } + + @Test + public void testRead() { + Charset encoding = Charset.defaultCharset(); + assertThatCode(() -> CreateBrmsParamPolicy.readFile("xacml.pap.properties", encoding)) + .doesNotThrowAnyException(); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java index 451989c1f..d990b9002 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java @@ -22,16 +22,20 @@ package org.onap.policy.pap.xacml.rest.controller; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.mockrunner.mock.web.MockHttpServletRequest; import java.io.BufferedReader; import java.io.StringReader; import javax.servlet.http.HttpServletRequest; - +import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -72,16 +76,16 @@ public class OptimizationDictionaryControllerTest { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); jsonString = "{\"optimizationModelsDictionaryData\": {\"modelName\": \"test\",\"inprocess\": false,\"model\":" - + " {\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," - + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\"," - + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," + "\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," - + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," - + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + + " {\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," + + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\"," + + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," + "\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," + + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; br = new BufferedReader(new StringReader(jsonString)); // --- mock the getReader() call @@ -108,7 +112,7 @@ public class OptimizationDictionaryControllerTest { controller.getOptimizationModelsDictionaryEntityData(response); logger.info("response.getContentAsString(): " + response.getContentAsString()); assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); + && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -130,7 +134,7 @@ public class OptimizationDictionaryControllerTest { controller.saveOptimizationModelsDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); + && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -149,28 +153,59 @@ public class OptimizationDictionaryControllerTest { try { // mock the getReader() call jsonString = - "{\"data\": {\"modelName\": \"test\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\"," - + "\"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," - + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\"," - + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," - + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," - + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + "{\"data\": {\"modelName\": \"test\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\"," + + "\"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," + + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\"," + + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," + + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.removeOptimizationModelsDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); + && response.getContentAsString().contains("optimizationModelsDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); } logger.info("testRemoveOptimizationModelsDictionary: exit"); } + + @Test + public void testGet() { + OptimizationDictionaryController controller = new OptimizationDictionaryController(commonClassDao); + MockHttpServletResponse response = new MockHttpServletResponse(); + controller.getOptimizationModelsDictionaryByNameEntityData(response); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void testSave() { + OptimizationDictionaryController controller = new OptimizationDictionaryController(commonClassDao); + MockHttpServletRequest req = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + req.setBodyContent("{\n\"modelType\": \"type.yml\", \"dataOrderInfo\": \"info\", \"userid\": \"id\", " + + "\"optimizationModelsDictionaryData\": {\"description\": \"desc\", \"modelName\": \"name\", \"version\": \"1.0\"}, " + + "\"classMap\": \"{\\\"dep\\\":\\\"{\\\"dependency\\\":\\\"depval\\\"}\\\"}\" }\n"); + // + "\"classMap\": \"{\\\"dep\\\":\\\"dependency\\\"}\" }\n"); + assertThatThrownBy(() -> controller.saveOptimizationModelsDictionary(req, response)) + .isInstanceOf(NullPointerException.class); + + req.setBodyContent("{\n\"modelType\": \"type.xml\", \"dataOrderInfo\": \"info\", \"userid\": \"id\", " + + "\"optimizationModelsDictionaryData\": {\"description\": \"desc\", \"modelName\": \"name\", \"version\": \"1.0\"}, " + + "\"classMap\": \"{\\\"dep\\\": {\\\"dependency\\\":\\\"depval\\\"} }\" }\n"); + assertThatCode(() -> controller.saveOptimizationModelsDictionary(req, response)).doesNotThrowAnyException(); + + req.setupAddParameter("apiflag", "api"); + assertThatThrownBy(() -> controller.saveOptimizationModelsDictionary(req, response)) + .isInstanceOf(NullPointerException.class); + } + } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java index a9da00d5a..d0e4416f9 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java @@ -25,11 +25,13 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; import com.mockrunner.mock.web.MockHttpServletRequest; import com.mockrunner.mock.web.MockHttpServletResponse; import java.io.IOException; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.hibernate.Session; @@ -45,6 +47,7 @@ import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import org.onap.policy.xacml.std.pap.StdEngine; import org.powermock.api.mockito.PowerMockito; @@ -120,12 +123,74 @@ public class DeleteHandlerTest { CommonClassDao dao = Mockito.mock(CommonClassDao.class); DeleteHandler handler = new DeleteHandler(dao); - // Mock request + // Request #1 MockHttpServletRequest request = new MockHttpServletRequest(); request.setBodyContent( "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); MockHttpServletResponse response = new MockHttpServletResponse(); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #2 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Action_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #3 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #4 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Bar_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #5 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #6 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Action_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Request #7 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + + // Mock dao + List pePVs = new ArrayList(); + PolicyVersion pv = new PolicyVersion(); + pePVs.add(pv); + List peObjs = new ArrayList(pePVs); + List peEnts = new ArrayList(); + PolicyEntity peEnt = new PolicyEntity(); + peEnts.add(peEnt); + List peEntObjs = new ArrayList(peEnts); + Mockito.when(dao.getDataByQuery(eq("Select p from PolicyVersion p where p.policyName=:pname"), any())) + .thenReturn(peObjs); + Mockito.when( + dao.getDataByQuery(eq("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope"), any())) + .thenReturn(peEntObjs); + + // Request #8 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n"); + handler.doApiDeleteFromPap(request, response); + assertTrue(response.containsHeader("error")); + // Request #9 + request.setBodyContent( + "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n, \"deleteCondition\": \"All Versions\"}\n"); handler.doApiDeleteFromPap(request, response); assertTrue(response.containsHeader("error")); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java index 3b826f694..b7d6bacbd 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java @@ -37,7 +37,7 @@ public class ImportServiceTest { HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); service.doImportMicroServicePut(request, response); - assertEquals(response.getHeader("error"), "missing"); + assertEquals("missing", response.getHeader("error")); } @Test -- 2.16.6