summaryrefslogtreecommitdiffstats
path: root/controlloop/common/guard/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'controlloop/common/guard/src/test/java')
-rw-r--r--controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java61
-rw-r--r--controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java168
-rw-r--r--controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java66
-rw-r--r--controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java101
-rw-r--r--controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java111
5 files changed, 499 insertions, 8 deletions
diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java
new file mode 100644
index 000000000..362931657
--- /dev/null
+++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * guard
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.guard;
+
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.isNotNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.drools.core.impl.StatefulKnowledgeSessionImpl;
+import org.junit.Test;
+
+public class CallGuardTaskTest{
+
+ static final String REQ_ID = "1-2-3-4-5";
+ static final String REQ_MATCHER = "0+1-0+2-0+3-0+4-0+5";
+
+ @Test
+ /**
+ * Tests that the run method inserts guard response into working memory
+ */
+ public void testRun() {
+ // Create mock working session
+ StatefulKnowledgeSessionImpl mockWorkingSession = mock(StatefulKnowledgeSessionImpl.class);
+ when(mockWorkingSession.insert(isNotNull())).thenReturn(null);
+ // Create CallGuardTask and run
+ CallGuardTask cgt = new CallGuardTask(mockWorkingSession, "cl", "act", "rec", "tar", REQ_ID);
+ cgt.run();
+ verify(mockWorkingSession).insert(argThat(
+ (Object o) -> {
+ if(!(o instanceof PolicyGuardResponse)){
+ return false;
+ }
+ // Check if the inserted response is PolicyGuardResponse, is Indeterminate, and has same reqID
+ PolicyGuardResponse response = (PolicyGuardResponse) o;
+ return Util.INDETERMINATE.equals(response.getResult()) &&
+ // req ID has form 00000001-0002-0003-0004-000000000005
+ response.getRequestID().toString().matches(REQ_MATCHER);
+ }));
+
+ }
+
+}
diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java
new file mode 100644
index 000000000..566cc7a93
--- /dev/null
+++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PIPEngineGetHistoryTest.java
@@ -0,0 +1,168 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * guard
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.guard;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+import javax.persistence.Query;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.policy.drools.system.PolicyEngine;
+
+import com.att.research.xacml.std.pip.StdPIPRequest;
+import com.att.research.xacml.std.pip.StdPIPResponse;
+import com.att.research.xacml.std.pip.finders.EngineFinder;
+
+public class PIPEngineGetHistoryTest {
+ static PIPEngineGetHistory pegh;
+ private static final String ISSUER = "issuerIntw:mid:end";
+
+ @BeforeClass
+ public static void testPIPEngineGetHistory(){
+ pegh = null;
+ try{
+ pegh = new PIPEngineGetHistory();
+ } catch(Exception e){
+ fail("PIPEngineGetHistory constructor failed");
+ }
+ }
+
+ @Test
+ public void testAttributesRequired() {
+ assertTrue(pegh.attributesRequired().isEmpty());
+ }
+
+ @Test
+ public void testAttributesProvided() {
+ assertTrue(pegh.attributesProvided().isEmpty());
+ }
+
+ @Test
+ public void testGetAttributes() {
+ StdPIPRequest mockPIPRequest = mock(StdPIPRequest.class);
+ EngineFinder mockPIPFinder = mock(EngineFinder.class);
+
+ // Test issuer null
+ when(mockPIPRequest.getIssuer()).thenReturn(null);
+ try {
+ assertEquals(pegh.getAttributes(mockPIPRequest, mockPIPFinder),
+ StdPIPResponse.PIP_RESPONSE_EMPTY);
+ } catch (Exception e) {
+ fail("getAttributes failed");
+ }
+
+ // Test issuer not equal to our issuer
+ pegh.setIssuer(ISSUER);
+ when(mockPIPRequest.getIssuer()).thenReturn("something else");
+ try {
+ assertEquals(pegh.getAttributes(mockPIPRequest, mockPIPFinder),
+ StdPIPResponse.PIP_RESPONSE_EMPTY);
+ } catch (Exception e) {
+ fail("getAttributes failed");
+ }
+
+ // Test issuer equal to our issuer
+ when(mockPIPRequest.getIssuer()).thenReturn(ISSUER);
+ try {
+ assertNotNull(pegh.getAttributes(mockPIPRequest, mockPIPFinder));
+ } catch (Exception e) {
+ // Normal to catch exception
+ }
+ }
+
+ @Test
+ public void testGetCountFromDB(){
+ // Set PU
+ System.setProperty(Util.PU_KEY, Util.JUNITPU);
+
+ //Enter dummy props to avoid nullPointerException
+ PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_URL, "a");
+ PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_USER, "b");
+ PolicyEngine.manager.setEnvironmentProperty(Util.ONAP_KEY_PASS, "c");
+
+ // Connect to in-mem db
+ EntityManager em = null;
+ try{
+ em = Persistence.createEntityManagerFactory(Util.JUNITPU).createEntityManager();
+ } catch(Exception e){
+ fail(e.getLocalizedMessage());
+ }
+
+ String sql = "CREATE TABLE `operationshistory10` (" +
+ "`CLNAME` varchar(255)," +
+ "`requestID` varchar(100)," +
+ "`actor` varchar(50) ," +
+ "`operation` varchar(50)," +
+ "`target` varchar(50)," +
+ "`starttime` timestamp," +
+ "`outcome` varchar(50)," +
+ "`message` varchar(255)," +
+ "`subrequestId` varchar(100)," +
+ "`endtime` timestamp"+
+ ")";
+ // Create necessary table
+ Query nq = em.createNativeQuery(sql);
+ em.getTransaction().begin();
+ nq.executeUpdate();
+ em.getTransaction().commit();
+
+ // Use reflection to run getCountFromDB
+ Method method = null;
+ int count = -1;
+ try {
+ method = PIPEngineGetHistory.class.getDeclaredMethod("getCountFromDB", String.class, String.class, String.class, String.class);
+ method.setAccessible(true);
+ count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE");
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {
+ fail(e.getLocalizedMessage());
+ }
+ // No entries yet
+ assertEquals(0, count);
+
+ // Add an entry
+ String addEntry = "insert into operationshistory10 (outcome, CLNAME, actor, operation, target, endtime)" +
+ "values('success','testcl', 'actor', 'op', 'target', CURRENT_TIMESTAMP())";
+ Query nq2 = em.createNativeQuery(addEntry);
+ em.getTransaction().begin();
+ nq2.executeUpdate();
+ em.getTransaction().commit();
+ em.close();
+
+ try {
+ count = (int) method.invoke(null, "actor", "op", "target", "1 MINUTE");
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ fail(e.getLocalizedMessage());
+ }
+ // Should count 1 entry now
+ assertEquals(1, count);
+ }
+
+}
diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java
index 7068fed3d..17e115707 100644
--- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java
+++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java
@@ -1,15 +1,15 @@
/*-
* ============LICENSE_START=======================================================
- * unit test
+ * guard
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,16 +17,66 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.guard;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.UUID;
+
import org.junit.Test;
+import org.onap.policy.controlloop.policy.TargetType;
public class PolicyGuardTest {
-
- @Test
- public void test() {
-
+ private class DummyLockCallback implements LockCallback{
+ @Override
+ public boolean isActive() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+ @Override
+ public boolean releaseLock() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+ }
+ private class DummyTargetLock implements TargetLock{
+ @Override
+ public UUID getLockID() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+ @Override
+ public TargetType getTargetType() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+ @Override
+ public String getTargetInstance() {
+ return INSTANCENAME;
+ }
+ @Override
+ public UUID getRequestID() {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
+ private static final String INSTANCENAME = "targetInstance";
+
+ @Test
+ public void testAll() {
+ UUID uuid = UUID.randomUUID();
+ TargetType type = TargetType.VM;
+
+
+ // Test isLocked before and after lock added
+ assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid));
+ PolicyGuard.lockTarget(type, INSTANCENAME, uuid , new DummyLockCallback());
+ assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid));
+
+ // Test isLocked after lock removed
+ PolicyGuard.unlockTarget(new DummyTargetLock());
+ assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid));
+ }
}
diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java
new file mode 100644
index 000000000..1d3ab02e4
--- /dev/null
+++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * guard
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.guard;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onap.policy.drools.http.server.HttpServletServer;
+import org.onap.policy.drools.utils.LoggerUtil;
+
+
+
+public class PolicyGuardXacmlHelperTest {
+
+ @BeforeClass
+ public static void setupSimulator() {
+ LoggerUtil.setLevel("ROOT", "INFO");
+ LoggerUtil.setLevel("org.eclipse.jetty", "WARN");
+ try {
+ org.onap.policy.simulators.Util.buildGuardSim();
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ //
+ // Set guard properties
+ //
+ org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision",
+ "python",
+ "test",
+ "python",
+ "test",
+ "DEVL");
+ }
+
+ @AfterClass
+ /**
+ * Shuts down simulator and performs 1 more test for the case where the connection fails
+ */
+ public static void tearDownSimulator() {
+ HttpServletServer.factory.destroy();
+
+ // Null/ Bad Connection Case
+ PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(
+ org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId");
+ String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq);
+ assertNotNull(rawDecision);
+ assertTrue(0 == Util.INDETERMINATE.compareToIgnoreCase(rawDecision));
+ }
+
+ @Test
+ public void testSimulator() {
+ PolicyGuardXacmlRequestAttributes request = new PolicyGuardXacmlRequestAttributes("clname_id", "actor_id", "operation_id", "target_id", "request_id");
+ String xacmlResponse = new PolicyGuardXacmlHelper().callPDP(request);
+ assertNotNull(xacmlResponse);
+ }
+
+ @Test
+ /**
+ * Tests PolicyGuardXacmlHelper.callPDP method to determine if it returns DENY, PERMIT, or INDETERMINATE
+ * as expected.
+ */
+ public void testCallPDP() {
+ // Deny Case
+ PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(
+ org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId");
+ String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq);
+ assertNotNull(rawDecision);
+ assertTrue(0 == Util.DENY.compareToIgnoreCase(rawDecision));
+
+ // Permit Case
+ xacmlReq = new PolicyGuardXacmlRequestAttributes(
+ "clname", "actor", "recipe", "target", "requestId");
+ rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq);
+ assertNotNull(rawDecision);
+ assertTrue(0 == Util.PERMIT.compareToIgnoreCase(rawDecision));
+
+ // Indeterminate case is in tearDown for efficiency
+ }
+
+}
diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java
new file mode 100644
index 000000000..1e972c30f
--- /dev/null
+++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java
@@ -0,0 +1,111 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * guard
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.policy.guard;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+
+public class PolicyGuardYamlToXacmlTest {
+
+ @Test
+ public void testFromYamlToXacml() {
+ //PolicyGuardYamlToXacml.fromYamlToXacml(yamlFile, xacmlTemplate, xacmlPolicyOutput);
+ //fail("Not yet implemented");
+ }
+
+ @Test
+ public void testGenerateXacmlGuard() {
+ String dummyFileContent = "${clname}, ${actor}, ${recipe}, ${targets}, ${limit}, ${twValue}, ${twUnits}, ${guardActiveStart}, ${guardActiveEnd}";
+ List<String> targets = new ArrayList();
+ targets.add("target1");
+ targets.add("target2");
+ Map<String, String> tw = new HashMap();
+ tw.put("value", "10");
+ tw.put("units", "hours");
+ String res = PolicyGuardYamlToXacml.generateXacmlGuard(dummyFileContent,
+ "cl", "actor", "recipe", targets, 5, tw, "start", "end");
+
+ // Assert no mote "${}" are left
+ assertFalse(res.contains("${"));
+ assertFalse(res.contains("}"));
+ // Assert all substitutions are made
+ assertTrue(res.contains("cl"));
+ assertTrue(res.contains("actor"));
+ assertTrue(res.contains("recipe"));
+ assertTrue(res.contains("target1"));
+ assertTrue(res.contains("target2"));
+ assertTrue(res.contains("10"));
+ assertTrue(res.contains("hours"));
+ assertTrue(res.contains("start"));
+ assertTrue(res.contains("end"));
+ }
+
+ @Test
+ public void testIsNullOrEmpty() {
+ assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty(""));
+ assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty(null));
+ assertFalse(PolicyGuardYamlToXacml.isNullOrEmpty("hello"));
+ }
+
+ @Test
+ public void testIsNullOrEmptyList() {
+ List<String> l = new ArrayList();
+ assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(null));
+ assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(l));
+
+ l.add("hello");
+ assertFalse(PolicyGuardYamlToXacml.isNullOrEmptyList(l));
+ }
+
+ @Test
+ public void testFromYamlToXacmlBlacklist() {
+ //fail("Not yet implemented");
+ }
+
+ @Test
+ public void testGenerateXacmlGuardBlacklist() {
+ String dummyFileContent = "${clname}, ${actor}, ${recipe}, ${blackListElement}, ${guardActiveStart}, ${guardActiveEnd}";
+ List<String> blacklist = new ArrayList();
+ blacklist.add("target1");
+ blacklist.add("target2");
+ String res = PolicyGuardYamlToXacml.generateXacmlGuardBlacklist(dummyFileContent,
+ "cl", "actor", "recipe", blacklist, "start", "end");
+
+ // Assert no mote "${}" are left
+ assertFalse(res.contains("${"));
+ assertFalse(res.contains("}"));
+ // Assert all substitutions are made
+ assertTrue(res.contains("cl"));
+ assertTrue(res.contains("actor"));
+ assertTrue(res.contains("recipe"));
+ assertTrue(res.contains("target1"));
+ assertTrue(res.contains("target2"));
+ assertTrue(res.contains("start"));
+ assertTrue(res.contains("end"));
+ }
+
+}