diff options
Diffstat (limited to 'controlloop/common/guard/src/test')
11 files changed, 1158 insertions, 1129 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 index 362931657..3255aec77 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.mockito.ArgumentMatchers.argThat; @@ -28,34 +29,34 @@ 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); - })); - - } +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 obj) -> { + if (!(obj instanceof PolicyGuardResponse)) { + return false; + } + // Check if the inserted response is PolicyGuardResponse, is Indeterminate, and has same + // reqID + PolicyGuardResponse response = (PolicyGuardResponse) obj; + // req ID has form 00000001-0002-0003-0004-000000000005 + return Util.INDETERMINATE.equals(response.getResult()) + && response.getRequestID().toString().matches(REQ_MATCHER); + })); + + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java index b4d417e35..a491d74cc 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java @@ -20,21 +20,22 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.Test; public class GuardResultTest { - @Test - public void guardResultTest() { - assertEquals(3, GuardResult.values().length); - assertNotNull(GuardResult.LOCK_ACQUIRED); - assertNotNull(GuardResult.LOCK_DENIED); - assertNotNull(GuardResult.LOCK_EXCEPTION); - - assertEquals(GuardResult.LOCK_ACQUIRED, GuardResult.valueOf("LOCK_ACQUIRED")); - assertEquals(GuardResult.LOCK_DENIED, GuardResult.valueOf("LOCK_DENIED")); - assertEquals(GuardResult.LOCK_EXCEPTION, GuardResult.valueOf("LOCK_EXCEPTION")); - } + @Test + public void guardResultTest() { + assertEquals(3, GuardResult.values().length); + assertNotNull(GuardResult.LOCK_ACQUIRED); + assertNotNull(GuardResult.LOCK_DENIED); + assertNotNull(GuardResult.LOCK_EXCEPTION); + + assertEquals(GuardResult.LOCK_ACQUIRED, GuardResult.valueOf("LOCK_ACQUIRED")); + assertEquals(GuardResult.LOCK_DENIED, GuardResult.valueOf("LOCK_DENIED")); + assertEquals(GuardResult.LOCK_EXCEPTION, GuardResult.valueOf("LOCK_EXCEPTION")); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java index 9e1d1b29e..8fc5a83da 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java @@ -20,7 +20,10 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.att.aft.dme2.internal.google.common.io.Files; import java.io.File; import java.io.IOException; @@ -32,78 +35,76 @@ import org.onap.policy.guard.Util.Pair; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; -import com.att.aft.dme2.internal.google.common.io.Files; - public class GuardUtilTest { - @Test - public void testLoadYamlOK() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - - ControlLoopPolicy clPolicy = new ControlLoopPolicy(); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - String clYamlString = clYaml.dump(clPolicy); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - - Pair<ControlLoopPolicy, String> result = Util.loadYaml(tempYAMLFile.getCanonicalPath()); - - assertEquals(clPolicy, result.a); - assertEquals(clYamlString, result.b); - - tempYAMLFile.delete(); - } - - @Test - public void testLoadYamlError() throws IOException { - File tempDir = Files.createTempDir(); - - // Read from a directory forces an IO exception - assertNull(Util.loadYaml(tempDir.getCanonicalPath())); - - tempDir.delete(); - } - - @Test - public void testLoadGuardYamlOK() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - - ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - String clYamlString = clYaml.dump(clGuardPolicy); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - - ControlLoopGuard result = Util.loadYamlGuard(tempYAMLFile.getCanonicalPath()); - - assertEquals(clGuardPolicy, result); - - tempYAMLFile.delete(); - } - - @Test - public void testLoadGuardYamlError() throws IOException { - File tempDir = Files.createTempDir(); - - // Read from a directory forces an IO exception - assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); - - tempDir.delete(); - } - - @Test - public void testMisc() { - Util.setGuardEnvProp("Actor", "Judy Garland"); - assertEquals("Judy Garland", Util.getGuardProp("Actor")); - - Util.setGuardEnvProps("http://somewhere.over.the.rainbow", "Dorothy", "Toto", "Wizard", "Emerald", "Oz"); - - assertEquals("http://somewhere.over.the.rainbow", Util.getGuardProp(Util.PROP_GUARD_URL)); - assertEquals("Dorothy", Util.getGuardProp(Util.PROP_GUARD_USER)); - assertEquals("Toto", Util.getGuardProp(Util.PROP_GUARD_PASS)); - assertEquals("Wizard", Util.getGuardProp(Util.PROP_GUARD_CLIENT_USER)); - assertEquals("Emerald", Util.getGuardProp(Util.PROP_GUARD_CLIENT_PASS)); - assertEquals("Oz", Util.getGuardProp(Util.PROP_GUARD_ENV)); - } + @Test + public void testLoadYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + + ControlLoopPolicy clPolicy = new ControlLoopPolicy(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clPolicy); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + Pair<ControlLoopPolicy, String> result = Util.loadYaml(tempYamlFile.getCanonicalPath()); + + assertEquals(clPolicy, result.parameterA); + assertEquals(clYamlString, result.parameterB); + + tempYamlFile.delete(); + } + + @Test + public void testLoadYamlError() throws IOException { + File tempDir = Files.createTempDir(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYaml(tempDir.getCanonicalPath())); + + tempDir.delete(); + } + + @Test + public void testLoadGuardYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + + ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clGuardPolicy); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + ControlLoopGuard result = Util.loadYamlGuard(tempYamlFile.getCanonicalPath()); + + assertEquals(clGuardPolicy, result); + + tempYamlFile.delete(); + } + + @Test + public void testLoadGuardYamlError() throws IOException { + File tempDir = Files.createTempDir(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); + + tempDir.delete(); + } + + @Test + public void testMisc() { + Util.setGuardEnvProp("Actor", "Judy Garland"); + assertEquals("Judy Garland", Util.getGuardProp("Actor")); + + Util.setGuardEnvProps("http://somewhere.over.the.rainbow", "Dorothy", "Toto", "Wizard", "Emerald", "Oz"); + + assertEquals("http://somewhere.over.the.rainbow", Util.getGuardProp(Util.PROP_GUARD_URL)); + assertEquals("Dorothy", Util.getGuardProp(Util.PROP_GUARD_USER)); + assertEquals("Toto", Util.getGuardProp(Util.PROP_GUARD_PASS)); + assertEquals("Wizard", Util.getGuardProp(Util.PROP_GUARD_CLIENT_USER)); + assertEquals("Emerald", Util.getGuardProp(Util.PROP_GUARD_CLIENT_PASS)); + assertEquals("Oz", Util.getGuardProp(Util.PROP_GUARD_ENV)); + } } 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 index 0c34d62b1..f1fd59961 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertEquals; @@ -26,24 +27,6 @@ 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 java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -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.api.Attribute; import com.att.research.xacml.api.AttributeValue; import com.att.research.xacml.api.Identifier; @@ -63,331 +46,364 @@ import com.att.research.xacml.std.pip.StdPIPResponse; import com.att.research.xacml.std.pip.finders.EngineFinder; import com.att.research.xacml.util.FactoryException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +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; + 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(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPIPRequest, mockPIPFinder)); - } catch (Exception e) { - fail("getAttributes failed"); - } - - // Test issuer not equal to our issuer - pegh.setIssuer(ISSUER); - when(mockPIPRequest.getIssuer()).thenReturn("something else"); - try { - assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPIPRequest, mockPIPFinder)); - } 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); - } - - @Test - public void testConfigure() throws PIPException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.configure("Dorothy", new Properties()); - - pegh.setDescription(null); - pegh.setIssuer(null); - pegh.configure("Dorothy", new Properties()); - } - - @Test - public void getAttributesTest() throws URISyntaxException, PIPException, FactoryException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.setIssuer("Dorothy"); - - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; - Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; - Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; - PIPRequest pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:1000:SECOND"); - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNOK())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); - } - - @Test - public void timeWindowTest() throws URISyntaxException, PIPException, FactoryException { - PIPEngineGetHistory pegh = new PIPEngineGetHistory(); - pegh.setIssuer("Dorothy"); - - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; - Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; - Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; - - PIPRequest pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:SECOND"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:MINUTE"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:HOUR"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:DAY"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:WEEK"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:MONTH"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:QUARTER"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:YEAR"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:FORTNIGHT"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - pipRequest = new StdPIPRequest(identifierCategory , identifierAttribute, identifierDataType, "Dorothy,tw:100:FORT NIGHT"); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); - - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNOK())); - assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); - } - - private class DummyPipFinder implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - try { - List<Attribute> attributeList = new ArrayList<>(); - Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); - Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://www.w3.org/2001/XMLSchema#string")); - - Identifier attributeIdIn0 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue<String> valueIn0 = new StdAttributeValue<String>(dataTypeIdIn, "ActorDorothy"); - Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); - attributeList.add(attribute0); - - Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue<String> valueIn1 = new StdAttributeValue<String>(dataTypeIdIn, "OperationHomeFromOZ"); - Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); - attributeList.add(attribute1); - - Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); - AttributeValue<String> valueIn2 = new StdAttributeValue<String>(dataTypeIdIn, "TargetWickedWitch"); - Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn2); - attributeList.add(attribute2); - - return new StdPIPResponse(attributeList); - } - catch (Exception e) { - return null; - } - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection<PIPEngine> getPIPEngines() { - return null; - } - } - - private class DummyPipFinderPipException implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - throw new PIPException(); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection<PIPEngine> getPIPEngines() { - return null; - } - } - - private class DummyPipFinderResponseStatusNOK implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - Status status = new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Processing Error"); - return new StdPIPResponse(status); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection<PIPEngine> getPIPEngines() { - return null; - } - } - - private class DummyPipFinderResponseEmptyAttrs implements PIPFinder { - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { - List<Attribute> attributeList = new ArrayList<>(); - return new StdPIPResponse(attributeList); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) throws PIPException { - return null; - } - - @Override - public Collection<PIPEngine> getPIPEngines() { - return null; - } - } + static PIPEngineGetHistory pegh; + private static final String ISSUER = "issuerIntw:mid:end"; + + /** + * Set up test class. + */ + @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(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); + } catch (Exception e) { + fail("getAttributes failed"); + } + + // Test issuer not equal to our issuer + pegh.setIssuer(ISSUER); + when(mockPipRequest.getIssuer()).thenReturn("something else"); + try { + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pegh.getAttributes(mockPipRequest, mockPipFinder)); + } 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); + } + + @Test + public void testConfigure() throws PIPException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.configure("Dorothy", new Properties()); + + pegh.setDescription(null); + pegh.setIssuer(null); + pegh.configure("Dorothy", new Properties()); + } + + @Test + public void getAttributesTest() throws URISyntaxException, PIPException, FactoryException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.setIssuer("Dorothy"); + + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; + Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; + Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; + PIPRequest pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:1000:SECOND"); + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); + } + + @Test + public void timeWindowTest() throws URISyntaxException, PIPException, FactoryException { + PIPEngineGetHistory pegh = new PIPEngineGetHistory(); + pegh.setIssuer("Dorothy"); + + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category"));; + Identifier identifierAttribute = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/atrtribute"));; + Identifier identifierDataType = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/datatype"));; + + PIPRequest pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:SECOND"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MINUTE"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:HOUR"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:DAY"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:WEEK"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:MONTH"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:QUARTER"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = + new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, "Dorothy,tw:100:YEAR"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:FORTNIGHT"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + pipRequest = new StdPIPRequest(identifierCategory, identifierAttribute, identifierDataType, + "Dorothy,tw:100:FORT NIGHT"); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinder())); + + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderPipException())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseStatusNok())); + assertNotNull(pegh.getAttributes(pipRequest, new DummyPipFinderResponseEmptyAttrs())); + } + + private class DummyPipFinder implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + try { + List<Attribute> attributeList = new ArrayList<>(); + Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); + Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://www.w3.org/2001/XMLSchema#string")); + + Identifier attributeIdIn0 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue<String> valueIn0 = new StdAttributeValue<String>(dataTypeIdIn, "ActorDorothy"); + Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn0); + attributeList.add(attribute0); + + Identifier attributeIdIn1 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue<String> valueIn1 = new StdAttributeValue<String>(dataTypeIdIn, "OperationHomeFromOZ"); + Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn1); + attributeList.add(attribute1); + + Identifier attributeIdIn2 = new IdentifierImpl(new URI(UUID.randomUUID().toString())); + AttributeValue<String> valueIn2 = new StdAttributeValue<String>(dataTypeIdIn, "TargetWickedWitch"); + Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn2); + attributeList.add(attribute2); + + return new StdPIPResponse(attributeList); + } catch (Exception e) { + return null; + } + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection<PIPEngine> getPIPEngines() { + return null; + } + } + + private class DummyPipFinderPipException implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + throw new PIPException(); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection<PIPEngine> getPIPEngines() { + return null; + } + } + + private class DummyPipFinderResponseStatusNok implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + Status status = new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Processing Error"); + return new StdPIPResponse(status); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection<PIPEngine> getPIPEngines() { + return null; + } + } + + private class DummyPipFinderResponseEmptyAttrs implements PIPFinder { + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude) throws PIPException { + List<Attribute> attributeList = new ArrayList<>(); + return new StdPIPResponse(attributeList); + } + + @Override + public PIPResponse getMatchingAttributes(PIPRequest pipRequest, PIPEngine exclude, PIPFinder pipFinderParent) + throws PIPException { + return null; + } + + @Override + public Collection<PIPEngine> getPIPEngines() { + return null; + } + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java index fa4acf7ec..7c9aae7b4 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java @@ -20,7 +20,8 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.UUID; @@ -28,26 +29,26 @@ import org.junit.Test; public class PolicyGuardRequestTest { - @Test - public void policyGuardRequestTest() { - UUID requestId = UUID.randomUUID(); - - assertNotNull(new PolicyGuardRequest(null, null, null, null)); - - PolicyGuardRequest request = new PolicyGuardRequest("Dorothy", "Kansas", requestId, "GetBackHome"); - - request.setRequestID(requestId); - assertEquals(requestId, request.getRequestID()); - - request.setActor("Dorothy"); - assertEquals("Dorothy", request.getActor()); - - request.setTarget("Kansas"); - assertEquals("Kansas", request.getTarget()); - - request.setOperation("GetBackHome"); - assertEquals("GetBackHome", request.getOperation()); - - assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); - } + @Test + public void policyGuardRequestTest() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardRequest(null, null, null, null)); + + PolicyGuardRequest request = new PolicyGuardRequest("Dorothy", "Kansas", requestId, "GetBackHome"); + + request.setRequestID(requestId); + assertEquals(requestId, request.getRequestID()); + + request.setActor("Dorothy"); + assertEquals("Dorothy", request.getActor()); + + request.setTarget("Kansas"); + assertEquals("Kansas", request.getTarget()); + + request.setOperation("GetBackHome"); + assertEquals("GetBackHome", request.getOperation()); + + assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java index fe0155541..f9bd94795 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java @@ -20,7 +20,8 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.UUID; @@ -28,23 +29,23 @@ import org.junit.Test; public class PolicyGuardResponseTest { - @Test - public void policyGuardResponseTest() { - UUID requestId = UUID.randomUUID(); - - assertNotNull(new PolicyGuardResponse(null, null, null)); - - PolicyGuardResponse response = new PolicyGuardResponse("BackHome", requestId, "GetBackHome"); - - response.setRequestID(requestId); - assertEquals(requestId, response.getRequestID()); - - response.setResult("BackHome"); - assertEquals("BackHome", response.getResult()); - - response.setOperation("GetBackHome"); - assertEquals("GetBackHome", response.getOperation()); - - assertEquals("PolicyGuardResponse [requestID=", response.toString().substring(0, 31)); - } + @Test + public void policyGuardResponseTest() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardResponse(null, null, null)); + + PolicyGuardResponse response = new PolicyGuardResponse("BackHome", requestId, "GetBackHome"); + + response.setRequestID(requestId); + assertEquals(requestId, response.getRequestID()); + + response.setResult("BackHome"); + assertEquals("BackHome", response.getResult()); + + response.setOperation("GetBackHome"); + assertEquals("GetBackHome", response.getOperation()); + + assertEquals("PolicyGuardResponse [requestID=", response.toString().substring(0, 31)); + } } 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 82656fa09..9c85845b5 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertEquals; @@ -35,201 +36,205 @@ import org.onap.policy.guard.impl.VMTargetLock; import org.onap.policy.guard.impl.VNFTargetLock; public class PolicyGuardTest { - private static final String INSTANCENAME = "targetInstance"; - - private class DummyLockCallback implements LockCallback { - @Override - public boolean isActive() { - return false; - } - @Override - public boolean releaseLock() { - return false; - } - } - - private class DummyTargetLock implements TargetLock { - @Override - public UUID getLockID() { - return null; - } - @Override - public TargetType getTargetType() { - return null; - } - @Override - public String getTargetInstance() { - return INSTANCENAME; - } - @Override - public UUID getRequestID() { - return null; - } - } - - @Test - public void testLockVM() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VM; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VMTargetLock.class, result.getB().getClass()); - - VMTargetLock vtl = (VMTargetLock) result.getB(); - assertNotNull(vtl.getLockID()); - assertEquals(INSTANCENAME, vtl.getTargetInstance()); - assertEquals(TargetType.VM, vtl.getTargetType()); - assertNotNull(vtl.getRequestID()); - assertEquals(dlcb, vtl.getCallback()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testLockPNF() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.PNF; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(PNFTargetLock.class, result.getB().getClass()); - - PNFTargetLock ptl = (PNFTargetLock) result.getB(); - assertNotNull(ptl.getLockID()); - assertEquals(INSTANCENAME, ptl.getTargetInstance()); - assertEquals(TargetType.PNF, ptl.getTargetType()); - assertNotNull(ptl.getRequestID()); - assertEquals(dlcb, ptl.getCallback()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - - @Test - public void testLockVNF() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VNF; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VNFTargetLock.class, result.getB().getClass()); - - VNFTargetLock vtl = (VNFTargetLock) result.getB(); - assertNotNull(vtl.getLockID()); - assertEquals(INSTANCENAME, vtl.getTargetInstance()); - assertEquals(TargetType.VNF, vtl.getTargetType()); - assertNotNull(vtl.getRequestID()); - assertEquals(dlcb, vtl.getCallback()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testLockVFC() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VFC; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_EXCEPTION, result.getA()); - assertNull(result.getB()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testUnLockNotLocked() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VM; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VMTargetLock.class, result.getB().getClass()); - - result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_DENIED, result.getA()); - assertNull(result.getB()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - // Test unlock after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testLockAlreadyLocked() { - UUID uuid = UUID.randomUUID(); - TargetType type = TargetType.VM; - - // Test isLocked before and after lock added - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - DummyLockCallback dlcb = new DummyLockCallback(); - LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); - assertEquals(VMTargetLock.class, result.getB().getClass()); - - result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid , dlcb); - assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - - assertEquals(GuardResult.LOCK_DENIED, result.getA()); - assertNull(result.getB()); - - // Test isLocked after lock removed - PolicyGuard.unlockTarget(new DummyTargetLock()); - assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); - } - - @Test - public void testInnards() { - - DummyLockCallback dlcb = new DummyLockCallback(); - assertFalse(dlcb.isActive()); - assertFalse(dlcb.releaseLock()); - - DummyTargetLock dtl = new DummyTargetLock(); - assertNull(dtl.getLockID()); - assertNull(dtl.getRequestID()); - assertEquals(INSTANCENAME, dtl.getTargetInstance()); - assertNull(dtl.getTargetType()); - } + private static final String INSTANCENAME = "targetInstance"; + + private class DummyLockCallback implements LockCallback { + @Override + public boolean isActive() { + return false; + } + + @Override + public boolean releaseLock() { + return false; + } + } + + private class DummyTargetLock implements TargetLock { + @Override + public UUID getLockID() { + return null; + } + + @Override + public TargetType getTargetType() { + return null; + } + + @Override + public String getTargetInstance() { + return INSTANCENAME; + } + + @Override + public UUID getRequestID() { + return null; + } + } + + @Test + public void testLockVm() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VM; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VMTargetLock.class, result.getB().getClass()); + + VMTargetLock vtl = (VMTargetLock) result.getB(); + assertNotNull(vtl.getLockID()); + assertEquals(INSTANCENAME, vtl.getTargetInstance()); + assertEquals(TargetType.VM, vtl.getTargetType()); + assertNotNull(vtl.getRequestID()); + assertEquals(dlcb, vtl.getCallback()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testLockPnf() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.PNF; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(PNFTargetLock.class, result.getB().getClass()); + + PNFTargetLock ptl = (PNFTargetLock) result.getB(); + assertNotNull(ptl.getLockID()); + assertEquals(INSTANCENAME, ptl.getTargetInstance()); + assertEquals(TargetType.PNF, ptl.getTargetType()); + assertNotNull(ptl.getRequestID()); + assertEquals(dlcb, ptl.getCallback()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + + @Test + public void testLockVnf() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VNF; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VNFTargetLock.class, result.getB().getClass()); + + VNFTargetLock vtl = (VNFTargetLock) result.getB(); + assertNotNull(vtl.getLockID()); + assertEquals(INSTANCENAME, vtl.getTargetInstance()); + assertEquals(TargetType.VNF, vtl.getTargetType()); + assertNotNull(vtl.getRequestID()); + assertEquals(dlcb, vtl.getCallback()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testLockVfc() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VFC; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_EXCEPTION, result.getA()); + assertNull(result.getB()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testUnLockNotLocked() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VM; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VMTargetLock.class, result.getB().getClass()); + + result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_DENIED, result.getA()); + assertNull(result.getB()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + // Test unlock after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testLockAlreadyLocked() { + UUID uuid = UUID.randomUUID(); + TargetType type = TargetType.VM; + + // Test isLocked before and after lock added + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + DummyLockCallback dlcb = new DummyLockCallback(); + LockResult<GuardResult, TargetLock> result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); + assertEquals(VMTargetLock.class, result.getB().getClass()); + + result = PolicyGuard.lockTarget(type, INSTANCENAME, uuid, dlcb); + assertTrue(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + + assertEquals(GuardResult.LOCK_DENIED, result.getA()); + assertNull(result.getB()); + + // Test isLocked after lock removed + PolicyGuard.unlockTarget(new DummyTargetLock()); + assertFalse(PolicyGuard.isLocked(type, INSTANCENAME, uuid)); + } + + @Test + public void testInnards() { + + DummyLockCallback dlcb = new DummyLockCallback(); + assertFalse(dlcb.isActive()); + assertFalse(dlcb.releaseLock()); + + DummyTargetLock dtl = new DummyTargetLock(); + assertNull(dtl.getLockID()); + assertNull(dtl.getRequestID()); + assertEquals(INSTANCENAME, dtl.getTargetInstance()); + assertNull(dtl.getTargetType()); + } } 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 index 10c6d7239..40123a4bb 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertEquals; @@ -24,20 +25,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Properties; -import java.util.UUID; - -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.system.PolicyEngine; -import org.onap.policy.drools.utils.LoggerUtil; - import com.att.research.xacml.api.Advice; import com.att.research.xacml.api.Attribute; import com.att.research.xacml.api.AttributeCategory; @@ -57,193 +44,200 @@ import com.att.research.xacml.std.StdResponse; import com.att.research.xacml.std.StdResult; import com.att.research.xacml.std.StdStatus; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Properties; +import java.util.UUID; + +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.system.PolicyEngine; +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); - assertEquals(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); - assertEquals(0, Util.PERMIT.compareToIgnoreCase(rawDecision)); - - // Indeterminate case is in tearDown for efficiency - } - - @Test - /** - * Tests PolicyGuardXacmlHelper.callPDP method to exercise all branches - */ - public void testCallPDPExtra() { - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); - - xacmlReq.setClnameID(null); - String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - assertNotNull(rawDecision); - assertEquals(-5, Util.DENY.compareToIgnoreCase(rawDecision)); - - org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", - "", - "", - "", - "", - ""); - - rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - assertNotNull(rawDecision); - - org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", - "python", - "test", - "python", - "test", - "DEVL"); - - } - - @Test - public void testParseXACMLPDPResponse() throws URISyntaxException { - PolicyGuardResponse pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(null); - assertEquals("Indeterminate", pgResponse.getResult()); - - Decision decision = Decision.PERMIT; - Status status = new StdStatus(StdStatus.STATUS_OK); - Result result = new StdResult(decision, status); - Response xacmlResponse = new StdResponse(result); - pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(xacmlResponse); - assertEquals("Permit", pgResponse.getResult()); - - - Collection<Obligation> obligationsIn = null; - Collection<Advice> adviceIn = null; - Collection<IdReference> policyIdentifiersIn = null; - Collection<IdReference> policySetIdentifiersIn = null; - - Collection<AttributeCategory> attributesIn = new ArrayList<>(); - Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow")); - Collection<Attribute> listAttributes = new ArrayList<>(); - Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); - Identifier attributeIdIn0 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:request:request-id")); - Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow.dataType")); - AttributeValue<String> valueIn = new StdAttributeValue<String>(dataTypeIdIn, UUID.randomUUID().toString()); - Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn); - listAttributes.add(attribute0); - - Identifier attributeIdIn1 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:operation:operation-id")); - Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn); - listAttributes.add(attribute1); - attributesIn.add(new StdAttributeCategory(identifierCategory , listAttributes)); - - Identifier attributeIdIn2 = new IdentifierImpl(new URI("Http://somewhere.over.the.rainbow/attributeId")); - Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn); - listAttributes.add(attribute2); - attributesIn.add(new StdAttributeCategory(identifierCategory , listAttributes)); - - Result fullResult = new StdResult(Decision.DENY, obligationsIn, adviceIn, attributesIn, policyIdentifiersIn, policySetIdentifiersIn); - Response fullXacmlResponse = new StdResponse(fullResult); - PolicyGuardResponse fullPGResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(fullXacmlResponse); - assertEquals("Deny", fullPGResponse.getResult()); - } - - @Test - public void testInit() { - Properties savedEnvironment = (Properties) PolicyEngine.manager.getEnvironment().clone(); - - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision,Dorothy"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision"); - - PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "1000"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().remove("pdpx.password"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("pdpx.username", "python"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().remove("pdpx.client.password"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().remove("pdpx.client.username"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "///"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", ""); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", "true"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.getEnvironment().clear(); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngine.manager.setEnvironment(savedEnvironment); - } + /** + * Set up test class. + */ + @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"); + } + + /** + * Shuts down simulator and performs 1 more test for the case where the connection fails. + */ + @AfterClass + 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); + assertEquals(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); + assertEquals(0, Util.PERMIT.compareToIgnoreCase(rawDecision)); + + // Indeterminate case is in tearDown for efficiency + } + + @Test + /** + * Tests PolicyGuardXacmlHelper.callPDP method to exercise all branches + */ + public void testCallPdpExtra() { + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", "requestId"); + + xacmlReq.setClnameID(null); + String rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + assertNotNull(rawDecision); + assertEquals(-5, Util.DENY.compareToIgnoreCase(rawDecision)); + + org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", "", "", "", "", ""); + + rawDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + assertNotNull(rawDecision); + + org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/pdp/api/getDecision", "python", "test", + "python", "test", "DEVL"); + + } + + @Test + public void testParseXacmlPdpResponse() throws URISyntaxException { + PolicyGuardResponse pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(null); + assertEquals("Indeterminate", pgResponse.getResult()); + + Decision decision = Decision.PERMIT; + Status status = new StdStatus(StdStatus.STATUS_OK); + Result result = new StdResult(decision, status); + Response xacmlResponse = new StdResponse(result); + pgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(xacmlResponse); + assertEquals("Permit", pgResponse.getResult()); + + + final Collection<Obligation> obligationsIn = null; + final Collection<Advice> adviceIn = null; + final Collection<IdReference> policyIdentifiersIn = null; + final Collection<IdReference> policySetIdentifiersIn = null; + + Collection<AttributeCategory> attributesIn = new ArrayList<>(); + Identifier identifierCategory = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow")); + Collection<Attribute> listAttributes = new ArrayList<>(); + Identifier categoryIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow/category")); + Identifier attributeIdIn0 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:request:request-id")); + Identifier dataTypeIdIn = new IdentifierImpl(new URI("http://somewhere.over.the.rainbow.dataType")); + AttributeValue<String> valueIn = new StdAttributeValue<String>(dataTypeIdIn, UUID.randomUUID().toString()); + Attribute attribute0 = new StdAttribute(categoryIdIn, attributeIdIn0, valueIn); + listAttributes.add(attribute0); + + Identifier attributeIdIn1 = new IdentifierImpl(new URI("urn:oasis:names:tc:xacml:1.0:operation:operation-id")); + Attribute attribute1 = new StdAttribute(categoryIdIn, attributeIdIn1, valueIn); + listAttributes.add(attribute1); + attributesIn.add(new StdAttributeCategory(identifierCategory, listAttributes)); + + Identifier attributeIdIn2 = new IdentifierImpl(new URI("Http://somewhere.over.the.rainbow/attributeId")); + Attribute attribute2 = new StdAttribute(categoryIdIn, attributeIdIn2, valueIn); + listAttributes.add(attribute2); + attributesIn.add(new StdAttributeCategory(identifierCategory, listAttributes)); + + Result fullResult = new StdResult(Decision.DENY, obligationsIn, adviceIn, attributesIn, policyIdentifiersIn, + policySetIdentifiersIn); + Response fullXacmlResponse = new StdResponse(fullResult); + PolicyGuardResponse fullPgResponse = PolicyGuardXacmlHelper.parseXACMLPDPResponse(fullXacmlResponse); + assertEquals("Deny", fullPgResponse.getResult()); + } + + @Test + public void testInit() { + final Properties savedEnvironment = (Properties) PolicyEngine.manager.getEnvironment().clone(); + + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", + "http://localhost:6669/pdp/api/getDecision,Dorothy"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", + "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", "http://localhost:6669/pdp/api/getDecision"); + + PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "1000"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().remove("pdpx.password"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("pdpx.username", "python"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().remove("pdpx.client.password"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().remove("pdpx.client.username"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.url", "///"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", ""); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", "true"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.getEnvironment().clear(); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngine.manager.setEnvironment(savedEnvironment); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java index d07a97a67..a61f5200b 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java @@ -20,7 +20,8 @@ package org.onap.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.UUID; @@ -28,37 +29,37 @@ import org.junit.Test; public class PolicyGuardXacmlRequestAttributesTest { - @Test - public void policyGuardXacmlRequestAttributesTest() { - assertNotNull(new PolicyGuardXacmlRequestAttributes(null, null, null, null, null)); - - UUID controlLoopID = UUID.randomUUID(); - UUID operationID = UUID.randomUUID(); - UUID requestID = UUID.randomUUID(); - UUID actorID = UUID.randomUUID(); - UUID targetID = UUID.randomUUID(); - - PolicyGuardXacmlRequestAttributes attributes = new PolicyGuardXacmlRequestAttributes( - controlLoopID.toString(), actorID.toString(), operationID.toString(), targetID.toString(), requestID.toString()); - - attributes.setRequestID(requestID.toString()); - assertEquals(requestID.toString(), attributes.getRequestID()); - - attributes.setOperationID(operationID.toString()); - assertEquals(operationID.toString(), attributes.getOperationID()); - - attributes.setActorID(actorID.toString()); - assertEquals(actorID.toString(), attributes.getActorID()); - - attributes.setTargetID(targetID.toString()); - assertEquals(targetID.toString(), attributes.getTargetID()); - - attributes.setTargetID(targetID.toString()); - assertEquals(targetID.toString(), attributes.getTargetID()); - - attributes.setClnameID(controlLoopID.toString()); - assertEquals(controlLoopID.toString(), attributes.getClnameID()); - - assertEquals("PolicyGuardXacmlRequestAttributes [actorID=", attributes.toString().substring(0, 43)); - } + @Test + public void policyGuardXacmlRequestAttributesTest() { + assertNotNull(new PolicyGuardXacmlRequestAttributes(null, null, null, null, null)); + + UUID controlLoopId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID actorId = UUID.randomUUID(); + UUID targetId = UUID.randomUUID(); + + PolicyGuardXacmlRequestAttributes attributes = new PolicyGuardXacmlRequestAttributes(controlLoopId.toString(), + actorId.toString(), operationId.toString(), targetId.toString(), requestId.toString()); + + attributes.setRequestID(requestId.toString()); + assertEquals(requestId.toString(), attributes.getRequestID()); + + attributes.setOperationID(operationId.toString()); + assertEquals(operationId.toString(), attributes.getOperationID()); + + attributes.setActorID(actorId.toString()); + assertEquals(actorId.toString(), attributes.getActorID()); + + attributes.setTargetID(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetID()); + + attributes.setTargetID(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetID()); + + attributes.setClnameID(controlLoopId.toString()); + assertEquals(controlLoopId.toString(), attributes.getClnameID()); + + assertEquals("PolicyGuardXacmlRequestAttributes [actorID=", attributes.toString().substring(0, 43)); + } } 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 index b35356438..3b517bcc1 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import static org.junit.Assert.assertFalse; @@ -40,192 +41,199 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class PolicyGuardYamlToXacmlTest { - private ControlLoopGuard clGuard; - - @Before - public void createControlLoopGuard() { - clGuard = new ControlLoopGuard(); - GuardPolicy guardPolicy = new GuardPolicy(); - MatchParameters matchParameters = new MatchParameters(); - matchParameters.setControlLoopName("WizardOfOz"); - matchParameters.setActor("Dorothy"); - matchParameters.setRecipe("GoToOz"); - List<String> targets = new ArrayList<>(); - targets.add("Wizard"); - targets.add("WickedWitchOfTheWest"); - matchParameters.setTargets(targets ); - guardPolicy.setMatch_parameters(matchParameters ); - Constraint limitConstraint = new Constraint(); - limitConstraint.setFreq_limit_per_target(5); - Map<String, String> timeWindow = new HashMap<>(); - timeWindow.put("value", "10"); - timeWindow.put("units", "hours"); - limitConstraint.setTime_window(timeWindow); - Map<String, String> activeTimeRange = new HashMap<>(); - activeTimeRange.put("start", "someStartTime"); - activeTimeRange.put("end", "someEndTime"); - limitConstraint.setActive_time_range(activeTimeRange ); - LinkedList<Constraint> limitConstraints = new LinkedList<>(); - limitConstraints.add(limitConstraint); - guardPolicy.setLimit_constraints(limitConstraints); - LinkedList<GuardPolicy> guardList = new LinkedList<>(); - guardList.add(guardPolicy); - clGuard.setGuards(guardList); - } - - @Test - public void testGenerateXacmlGuardFull() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacml(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("cl")); - assertTrue(result.contains("actor")); - assertTrue(result.contains("GoToOz")); - assertTrue(result.contains("Wizard")); - assertTrue(result.contains("WickedWitchOfTheWest")); - assertTrue(result.contains("10")); - assertTrue(result.contains("hours")); - assertTrue(result.contains("someStartTime")); - assertTrue(result.contains("someEndTime")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } - - @Test - public void testGenerateXacmlGuardPartial() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); - clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); - clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); - clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacml(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("cl")); - assertTrue(result.contains("actor")); - assertFalse(result.contains("GoToOz")); - assertFalse(result.contains("Wizard")); - assertFalse(result.contains("WickedWitchOfTheWest")); - assertTrue(result.contains("10")); - assertTrue(result.contains("hours")); - assertTrue(result.contains("someStartTime")); - assertTrue(result.contains("someEndTime")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } - - @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() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/blacklist_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - List<String> blacklist = new ArrayList<>(); - blacklist.add("WestWitches"); - blacklist.add("EastWitches"); - clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist ); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - System.err.println(result); - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("WestWitches")); - assertTrue(result.contains("EastWitches")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } - - @Test - public void testGenerateXacmlGuardBlacklistPartial() throws IOException { - File tempYAMLFile = File.createTempFile("ONAPPF", "yaml"); - File tempXACMLTemplateFile = new File("src/test/resources/blacklist_template.xml"); - File tempXACMLOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); - - List<String> blacklist = new ArrayList<>(); - blacklist.add("WestWitches"); - blacklist.add("EastWitches"); - clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist ); - - clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); - clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); - clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); - clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - TextFileUtils.putStringAsFile(clYamlString, tempYAMLFile); - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYAMLFile.getCanonicalPath(), tempXACMLTemplateFile.getCanonicalPath(), tempXACMLOutputFile.getCanonicalPath()); - - String result = TextFileUtils.getTextFileAsString(tempXACMLOutputFile.getCanonicalPath()); - System.err.println(result); - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("WestWitches")); - assertTrue(result.contains("EastWitches")); - - tempYAMLFile.delete(); - tempXACMLOutputFile.delete(); - } + private ControlLoopGuard clGuard; + + /** + * Set up test cases. + */ + @Before + public void createControlLoopGuard() { + clGuard = new ControlLoopGuard(); + MatchParameters matchParameters = new MatchParameters(); + matchParameters.setControlLoopName("WizardOfOz"); + matchParameters.setActor("Dorothy"); + matchParameters.setRecipe("GoToOz"); + List<String> targets = new ArrayList<>(); + targets.add("Wizard"); + targets.add("WickedWitchOfTheWest"); + matchParameters.setTargets(targets); + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setMatch_parameters(matchParameters); + Constraint limitConstraint = new Constraint(); + limitConstraint.setFreq_limit_per_target(5); + Map<String, String> timeWindow = new HashMap<>(); + timeWindow.put("value", "10"); + timeWindow.put("units", "hours"); + limitConstraint.setTime_window(timeWindow); + Map<String, String> activeTimeRange = new HashMap<>(); + activeTimeRange.put("start", "someStartTime"); + activeTimeRange.put("end", "someEndTime"); + limitConstraint.setActive_time_range(activeTimeRange); + LinkedList<Constraint> limitConstraints = new LinkedList<>(); + limitConstraints.add(limitConstraint); + guardPolicy.setLimit_constraints(limitConstraints); + LinkedList<GuardPolicy> guardList = new LinkedList<>(); + guardList.add(guardPolicy); + clGuard.setGuards(guardList); + } + + @Test + public void testGenerateXacmlGuardFull() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("cl")); + assertTrue(result.contains("actor")); + assertTrue(result.contains("GoToOz")); + assertTrue(result.contains("Wizard")); + assertTrue(result.contains("WickedWitchOfTheWest")); + assertTrue(result.contains("10")); + assertTrue(result.contains("hours")); + assertTrue(result.contains("someStartTime")); + assertTrue(result.contains("someEndTime")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } + + @Test + public void testGenerateXacmlGuardPartial() throws IOException { + final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); + clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); + clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); + clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("cl")); + assertTrue(result.contains("actor")); + assertFalse(result.contains("GoToOz")); + assertFalse(result.contains("Wizard")); + assertFalse(result.contains("WickedWitchOfTheWest")); + assertTrue(result.contains("10")); + assertTrue(result.contains("hours")); + assertTrue(result.contains("someStartTime")); + assertTrue(result.contains("someEndTime")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } + + @Test + public void testIsNullOrEmpty() { + assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty("")); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty(null)); + assertFalse(PolicyGuardYamlToXacml.isNullOrEmpty("hello")); + } + + @Test + public void testIsNullOrEmptyList() { + List<String> list = new ArrayList<>(); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(null)); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); + + list.add("hello"); + assertFalse(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); + } + + @Test + public void testFromYamlToXacmlBlacklist() { + // fail("Not yet implemented"); + } + + @Test + public void testGenerateXacmlGuardBlacklist() throws IOException { + final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + List<String> blacklist = new ArrayList<>(); + blacklist.add("WestWitches"); + blacklist.add("EastWitches"); + clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + System.err.println(result); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("WestWitches")); + assertTrue(result.contains("EastWitches")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } + + @Test + public void testGenerateXacmlGuardBlacklistPartial() throws IOException { + final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + List<String> blacklist = new ArrayList<>(); + blacklist.add("WestWitches"); + blacklist.add("EastWitches"); + clGuard.getGuards().getFirst().getLimit_constraints().getFirst().setBlacklist(blacklist); + + clGuard.getGuards().getFirst().getMatch_parameters().setControlLoopName(null); + clGuard.getGuards().getFirst().getMatch_parameters().setActor(null); + clGuard.getGuards().getFirst().getMatch_parameters().setRecipe(null); + clGuard.getGuards().getFirst().getMatch_parameters().setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + TextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = TextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + System.err.println(result); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("WestWitches")); + assertTrue(result.contains("EastWitches")); + + tempYamlFile.delete(); + tempXacmlOutputFile.delete(); + } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java index 21b75ed20..46a2762cc 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/TextFileUtils.java @@ -26,8 +26,8 @@ import java.io.FileOutputStream; import java.io.IOException; /** - * The Class TextFileUtils is class that provides useful functions for handling text files. Functions to read and wrtie text files to strings and strings are - * provided. + * The Class TextFileUtils is class that provides useful functions for handling text files. + * Functions to read and wrtie text files to strings and strings are provided. * * @author Liam Fallon (liam.fallon@ericsson.com) */ |