Set all cross references of policy/xacml-pdp
[policy/xacml-pdp.git] / applications / monitoring / src / test / java / org / onap / policy / xacml / pdp / application / monitoring / MonitoringPdpApplicationTest.java
index 9b26df1..b4a5579 100644 (file)
@@ -2,7 +2,8 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 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,13 +25,14 @@ package org.onap.policy.xacml.pdp.application.monitoring;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
+import com.att.research.xacml.api.Response;
 import java.io.File;
-import java.io.IOException;
-import java.util.Iterator;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.Properties;
 import java.util.ServiceLoader;
-
+import org.apache.commons.lang3.tuple.Pair;
 import org.junit.BeforeClass;
 import org.junit.ClassRule;
 import org.junit.FixMethodOrder;
@@ -42,12 +44,12 @@ import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.common.utils.resources.TextFileUtils;
 import org.onap.policy.models.decisions.concepts.DecisionRequest;
 import org.onap.policy.models.decisions.concepts.DecisionResponse;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
-import org.onap.policy.pdp.xacml.application.common.TestUtils;
 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
+import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -55,12 +57,12 @@ import org.slf4j.LoggerFactory;
 public class MonitoringPdpApplicationTest {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
-    private static Properties properties = new Properties();
-    private static File propertiesFile;
+    private static final Properties properties = new Properties();
     private static XacmlApplicationServiceProvider service;
     private static DecisionRequest requestSinglePolicy;
+    private static DecisionRequest requestPolicyType;
 
-    private static StandardCoder gson = new StandardCoder();
+    private static final StandardCoder gson = new StandardCoder();
 
     @ClassRule
     public static final TemporaryFolder policyFolder = new TemporaryFolder();
@@ -79,12 +81,18 @@ public class MonitoringPdpApplicationTest {
                 TextFileUtils
                     .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
                     DecisionRequest.class);
+        // Load Single Decision Request
+        //
+        requestPolicyType = gson.decode(
+                TextFileUtils
+                .getTextFileAsString("../../main/src/test/resources/decisions/decision.policytype.input.json"),
+                DecisionRequest.class);
         //
         // Setup our temporary folder
         //
-        XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
-        propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
-                properties, myCreator);
+        XacmlPolicyUtils.FileCreator myCreator = policyFolder::newFile;
+        File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
+            properties, myCreator);
         //
         // Load XacmlApplicationServiceProvider service
         //
@@ -93,10 +101,8 @@ public class MonitoringPdpApplicationTest {
         //
         // Look for our class instance and save it
         //
-        StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
-        Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
-        while (iterator.hasNext()) {
-            XacmlApplicationServiceProvider application = iterator.next();
+        StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
+        for (XacmlApplicationServiceProvider application : applicationLoader) {
             //
             // Is it our service?
             //
@@ -110,14 +116,14 @@ public class MonitoringPdpApplicationTest {
             strDump.append(application.applicationName());
             strDump.append(" supports ");
             strDump.append(application.supportedPolicyTypes());
-            strDump.append(System.lineSeparator());
+            strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
         }
         LOGGER.debug("{}", strDump);
         //
         // Tell it to initialize based on the properties file
         // we just built for it.
         //
-        service.initialize(propertiesFile.toPath().getParent());
+        service.initialize(propertiesFile.toPath().getParent(), null);
     }
 
     @Test
@@ -130,11 +136,18 @@ public class MonitoringPdpApplicationTest {
         // Ensure it has the supported policy types and
         // can support the correct policy types.
         //
-        assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.Monitoring", "1.0.0"))).isTrue();
-        assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.Monitoring", "1.5.0"))).isTrue();
-        assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
+        assertThat(service.canSupportPolicyType(
+                new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
+        assertThat(service.canSupportPolicyType(
+            new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "2.0.0"))).isTrue();
+        assertThat(service.canSupportPolicyType(
+                new ToscaConceptIdentifier(
                 "onap.policies.monitoring.foobar", "1.0.1"))).isTrue();
-        assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foobar", "1.0.0"))).isFalse();
+        assertThat(service.canSupportPolicyType(
+            new ToscaConceptIdentifier(
+                "onap.policies.monitoring.foobar", "2.0.1"))).isTrue();
+        assertThat(service.canSupportPolicyType(
+                new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
         //
         // Ensure it supports decisions
         //
@@ -146,102 +159,203 @@ public class MonitoringPdpApplicationTest {
         //
         // Ask for a decision
         //
-        DecisionResponse response = service.makeDecision(requestSinglePolicy);
-        LOGGER.info("Decision {}", response);
+        Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
+        LOGGER.info("Decision {}", decision);
+
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).isEmpty();
+        //
+        // Test the branch for query params, and we have no policy anyway
+        //
+        Map<String, String[]> requestQueryParams = new HashMap<>();
+        decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
+        LOGGER.info("Decision {}", decision);
+
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).isEmpty();
+        //
+        // Test the branch for query params, and we have no policy anyway
+        //
+        requestQueryParams.put("abbrev", new String[] {"false"});
+        decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
+        LOGGER.info("Decision {}", decision);
 
-        assertThat(response).isNotNull();
-        assertThat(response.getPolicies().size()).isEqualTo(0);
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).isEmpty();
+        //
+        // Monitoring applications should not have this information returned
+        //
+        assertNoInfo(decision);
+    }
+
+    @Test
+    public void tes3AddvDnsPolicy() throws CoderException, XacmlApplicationException {
+        testAddPolicy("src/test/resources/vDNS.policy.input.yaml",
+            "onap.policies.monitoring.cdap.tca.hi.lo.app",
+            "onap.scaleout.tca");
     }
 
     @Test
-    public void test3AddvDnsPolicy() throws IOException, CoderException, XacmlApplicationException {
+    public void tes4AddvFirewall1Policy() throws CoderException, XacmlApplicationException {
+        testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.yaml",
+            "onap.policies.monitoring.tcagen2",
+            "onap.vfirewall.tca");
+    }
+
+    @Test
+    public void tes5AddvFirewall2Policy() throws CoderException, XacmlApplicationException {
+        testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.v2.yaml",
+            "onap.policies.monitoring.tcagen2",
+            "onap.vfirewall.tca");
+    }
+
+    @SuppressWarnings("unchecked")
+    public void testAddPolicy(String policyResource, String policyType, String policyId)
+        throws CoderException, XacmlApplicationException {
         //
         // Now load the vDNS Policy - make sure
         // the pdp can support it and have it load
         // into the PDP.
         //
         //
-        // Now load the optimization policies
+        // Now load the monitoring policies
         //
-        final List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies("src/test/resources/vDNS.policy.input.yaml",
-                service);
+        final List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies(policyResource, service);
+
+        //
+        // Set the policy-id for the decision request.
+        //
+        requestSinglePolicy.getResource().put("policy-id", policyId);
+
         //
         // Ask for a decision
         //
-        DecisionResponse response = service.makeDecision(requestSinglePolicy);
-        LOGGER.info("Decision {}", response);
+        Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
+        LOGGER.info("Decision {}", decision);
+        //
+        // Should have one policy returned
+        //
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).hasSize(1);
+        //
+        // Monitoring applications should not have this information returned
+        //
+        assertNoInfo(decision);
+        //
+        // Dump it out as Json
+        //
+        LOGGER.info(gson.encode(decision.getKey()));
+
+        //
+        // Set the policy-type for the decision request.
+        //
+        requestPolicyType.getResource().put("policy-type", policyType);
+
+        //
+        // Ask for a decision based on policy-type
+        //
+        decision = service.makeDecision(requestPolicyType, null);
+        LOGGER.info("Decision {}", decision);
+        //
+        // Should have one policy returned
+        //
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).hasSize(1);
+        //
+        // Monitoring applications should not have this information returned
+        //
+        assertNoInfo(decision);
+        //
+        // Validate the full policy is returned
+        //
+        Map<String, Object> jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
+        assertThat(jsonPolicy).isNotNull();
+        assertThat(jsonPolicy.get("properties")).isNotNull();
+        //
+        // Dump it out as Json
+        //
+        LOGGER.info(gson.encode(decision.getKey()));
+        //
+        // Ask for abbreviated results
+        //
+        Map<String, String[]> requestQueryParams = new HashMap<>();
+        requestQueryParams.put("abbrev", new String[] {"true"});
+        decision = service.makeDecision(requestPolicyType, requestQueryParams);
+        LOGGER.info("Decision {}", decision);
+        //
+        // Should have one policy returned
+        //
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).hasSize(1);
+        //
+        // Monitoring applications should not have this information returned
+        //
+        assertNoInfo(decision);
+        //
+        // Validate an abbreviated policy is returned
+        //
+        jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
+        assertThat(jsonPolicy).isNotNull().doesNotContainKey("properties");
+        //
+        // Don't Ask for abbreviated results
+        //
+        requestQueryParams = new HashMap<>();
+        requestQueryParams.put("abbrev", new String[] {"false"});
+        decision = service.makeDecision(requestPolicyType, requestQueryParams);
+        LOGGER.info("Decision {}", decision);
+        //
+        // Should have one policy returned
+        //
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).hasSize(1);
+        //
+        // Monitoring applications should not have this information returned
+        //
+        assertNoInfo(decision);
+        //
+        // And should have full policy returned
+        //
+        jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
+        assertThat(jsonPolicy).isNotNull();
+        assertThat(jsonPolicy.get("properties")).isNotNull();
+        //
+        // Throw an unknown exception
+        //
+        requestQueryParams = new HashMap<>();
+        requestQueryParams.put("unknown", new String[] {"true"});
+        decision = service.makeDecision(requestPolicyType, requestQueryParams);
+        LOGGER.info("Decision {}", decision);
 
-        assertThat(response).isNotNull();
-        assertThat(response.getPolicies().size()).isEqualTo(1);
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).hasSize(1);
+        jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
+        assertThat(jsonPolicy).isNotNull();
+        assertThat(jsonPolicy.get("properties")).isNotNull();
         //
         // Dump it out as Json
         //
-        LOGGER.info(gson.encode(response));
-        LOGGER.info("Now testing unloading of policy");
+        LOGGER.info(gson.encode(decision.getKey()));
         //
         // Now unload it
         //
+        LOGGER.info("Now testing unloading of policy");
         for (ToscaPolicy policy : loadedPolicies) {
             assertThat(service.unloadPolicy(policy)).isTrue();
         }
         //
         // Ask for a decision
         //
-        response = service.makeDecision(requestSinglePolicy);
-        LOGGER.info("Decision {}", response);
+        decision = service.makeDecision(requestSinglePolicy, null);
+        LOGGER.info("Decision {}", decision.getKey());
 
-        assertThat(response).isNotNull();
-        assertThat(response.getPolicies().size()).isEqualTo(0);
+        assertThat(decision.getKey()).isNotNull();
+        assertThat(decision.getKey().getPolicies()).isEmpty();
     }
 
-    @Test
-    public void test4BadPolicies() {
-        /*
-         *
-         * THESE TEST SHOULD BE MOVED INTO THE API PROJECT
-         *
-        //
-        // No need for service, just test some of the methods
-        // for bad policies
-        //
-        MonitoringPdpApplication onapPdpEngine = new MonitoringPdpApplication();
-
-        assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
-            try (InputStream is =
-                    new FileInputStream("src/test/resources/test.monitoring.policy.missingmetadata.yaml")) {
-                onapPdpEngine.convertPolicies(is);
-            }
-        }).withMessageContaining("missing metadata section");
-
-        assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
-            try (InputStream is =
-                    new FileInputStream("src/test/resources/test.monitoring.policy.missingtype.yaml")) {
-                onapPdpEngine.convertPolicies(is);
-            }
-        }).withMessageContaining("missing type value");
-
-        assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
-            try (InputStream is =
-                    new FileInputStream("src/test/resources/test.monitoring.policy.missingversion.yaml")) {
-                onapPdpEngine.convertPolicies(is);
-            }
-        }).withMessageContaining("missing version value");
-
-        assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
-            try (InputStream is =
-                    new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.1.yaml")) {
-                onapPdpEngine.convertPolicies(is);
-            }
-        }).withMessageContaining("missing metadata policy-version");
-
-        assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
-            try (InputStream is =
-                    new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.2.yaml")) {
-                onapPdpEngine.convertPolicies(is);
-            }
-        }).withMessageContaining("missing metadata policy-id");
-
-        */
+    private void assertNoInfo(Pair<DecisionResponse, Response> decision) {
+        assertThat(decision.getKey().getAdvice()).isNull();
+        assertThat(decision.getKey().getObligations()).isNull();
+        assertThat(decision.getKey().getAttributes()).isNull();
     }
 
 }