diff options
author | Temoc Rodriguez <cr056n@att.com> | 2017-12-14 15:58:32 -0800 |
---|---|---|
committer | Temoc Rodriguez <cr056n@att.com> | 2017-12-15 09:09:12 -0800 |
commit | 4c8000e91a9dee0738e55e2bda930b94af474157 (patch) | |
tree | 578fdc9102ea43ad4765ba2d2dbb1322b24a37a2 /controlloop | |
parent | 5cfd3b7066e6a6305e140fa59b1fccb8e3c5f81b (diff) |
Add guard junits
Added a few junit files which test most functionality in the guard
submodule. Some minor bugs were found by the junits and fixed those
newly found bugs. Added persistence.xml for use by junits in guard.
Issue-ID: POLICY-490
Change-Id: Ied7e276cfd417e1f396b5a6685a2e9acc9efd109
Signed-off-by: Temoc Rodriguez <cr056n@att.com>
Diffstat (limited to 'controlloop')
12 files changed, 555 insertions, 18 deletions
diff --git a/controlloop/common/guard/pom.xml b/controlloop/common/guard/pom.xml index 467cbc05a..f41328438 100644 --- a/controlloop/common/guard/pom.xml +++ b/controlloop/common/guard/pom.xml @@ -54,5 +54,23 @@ <version>${project.version}</version> <scope>provided</scope> </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>simulators</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>2.13.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <version>[1.4.186,)</version> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java index 9b2644b95..6ba1a5a5f 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java @@ -338,7 +338,7 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ }catch(Exception ex){ logger.error("PIP thread got Exception. Can't connect to Operations History DB -- {}", OpsHistPU); logger.error("getCountFromDB threw: ", ex); - return 0; + return -1; } DateUtil dateUtil = new DateUtil(){ @@ -406,9 +406,9 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ + " and endtime between '" + new Timestamp(diff) + "' and '" + new Timestamp(now) + "'"; Query nq = em.createNativeQuery(sql); - nq.setParameter(0, actor); - nq.setParameter(1, operation); - nq.setParameter(2, target); + nq.setParameter(1, actor); + nq.setParameter(2, operation); + nq.setParameter(3, target); int ret = -1; try{ diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java index 0703b7611..cbaa8edde 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java @@ -104,12 +104,12 @@ public class PolicyGuardXacmlHelper { jsonReq.put("decisionAttributes", attributes); jsonReq.put("onapName", "PDPD"); - URLEntry urlEntry = restUrls[restUrlIndex]; try { // // Call RESTful PDP // + URLEntry urlEntry = restUrls[restUrlIndex]; netLogger.info("[OUT|{}|{}|]{}{}", "GUARD", urlEntry.restURL, System.lineSeparator(), jsonReq.toString()); response = callRESTfulPDP(new ByteArrayInputStream(jsonReq .toString().getBytes()), urlEntry.restURL, diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java index 72b723c1f..aef86f320 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java @@ -244,7 +244,7 @@ public class PolicyGuardYamlToXacml { xacmlFileContent = m.replaceAll("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + target + "</AttributeValue>" - + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}"); + + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); } p = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java index ca62f6149..93bdc0c37 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java @@ -68,6 +68,11 @@ public final class Util { public static final String PERMIT = "Permit"; public static final String DENY = "Deny"; + /* + * Junit props + */ + protected static final String PU_KEY = "OperationsHistoryPU"; + protected static final String JUNITPU = "TestOperationsHistoryPU"; private static final Logger logger = LoggerFactory.getLogger(Util.class); public static class Pair<A, B> { 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")); + } + +} diff --git a/controlloop/common/guard/src/test/resources/META-INF/persistence.xml b/controlloop/common/guard/src/test/resources/META-INF/persistence.xml new file mode 100644 index 000000000..f55c2f2d7 --- /dev/null +++ b/controlloop/common/guard/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<persistence version="2.1" + xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> + + <!-- In-mem DB for junit --> + <persistence-unit name="TestOperationsHistoryPU" + transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <class>org.onap.policy.controlloop.eventmanager.OperationsHistoryDbEntry</class> + <properties> + <property name="eclipselink.ddl-generation" value="create-or-extend-tables" /> + <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" /> + <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" /> + <property name="javax.persistence.jdbc.user" value="sa" /> + <property name="javax.persistence.jdbc.password" value="" /> + <property name="eclipselink.logging.level" value="CONFIG" /> + </properties> + </persistence-unit> + + +</persistence> diff --git a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java index 7415130ea..4551cf246 100644 --- a/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java +++ b/controlloop/common/simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java @@ -7,9 +7,9 @@ * 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. @@ -30,14 +30,15 @@ import org.json.JSONObject; @Path("/pdp/api") public class GuardSimulatorJaxRs { + public static final String DENY_CLNAME = "denyGuard"; @POST @Path("/getDecision") @Consumes(MediaType.APPLICATION_JSON) @Produces("application/json") - public String getGuardDecision(String req){ + public String getGuardDecision(String req){ String clName = new JSONObject(req).getJSONObject("decisionAttributes").getString("clname"); - if ("denyGuard".equals(clName)) + if (DENY_CLNAME.equals(clName)) { return "{\"decision\": \"DENY\", \"details\": \"Decision Deny. You asked for it\"}"; } |