diff options
Diffstat (limited to 'controlloop/m2/guard/src/test/java/org')
10 files changed, 880 insertions, 5 deletions
diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java new file mode 100644 index 000000000..3a647b130 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.isNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.function.Supplier; +import org.drools.core.WorkingMemory; +import org.junit.Test; + +public class CallGuardTaskTest { + + private static final String REQ_ID = "1-2-3-4-5"; + private static final String REQ_MATCHER = "0+1-0+2-0+3-0+4-0+5"; + private static final String VF_COUNT_ACTOR = "SO"; + private static final String INCR_VF_COUNT_RECIPE = "VF Module Create"; + + /** + * Tests that "run" works, and inserts guard response into working memory. + */ + @Test + public void testRun() { + // plain - doesn't need VF module count + //doTestRun(Util.INDETERMINATE, "act", "rec", () -> null); + + // SO actor, but plain recipe - doesn't need VF module count + //doTestRun(Util.INDETERMINATE, VF_COUNT_ACTOR, "rec", () -> null); + + // plain actor, but scale-out recipe - doesn't need VF module count + //doTestRun(Util.INDETERMINATE, "act", "VF Module Create", () -> null); + + // needs VF count + //doTestRun(Util.INDETERMINATE, VF_COUNT_ACTOR, INCR_VF_COUNT_RECIPE, () -> 22); + + // needs VF count, but it's missing ==> DENY + doTestRun(Util.DENY, VF_COUNT_ACTOR, INCR_VF_COUNT_RECIPE, () -> null); + } + + private void doTestRun(String status, String actor, String recipe, Supplier<Integer> vfCount) { + WorkingMemory mockWorkingSession = mock(WorkingMemory.class); + when(mockWorkingSession.insert(isNotNull())).thenReturn(null); + // Create CallGuardTask and run + CallGuardTask cgt = new CallGuardTask(mockWorkingSession, "cl", actor, recipe, "tar", REQ_ID, vfCount); + 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 status.equals(response.getResult()) && response.getRequestId().toString().matches(REQ_MATCHER); + })); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java index 54fd323c2..1b375cf21 100644 --- a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java @@ -84,11 +84,12 @@ public class GuardContextTest { @Test public void testGuardDbResponse() throws InterruptedException { Properties props = new Properties(prop); + props.setProperty(Util.PROP_GUARD_PERSISTENCE_UNIT, Util.JUNITPU); props.setProperty("guard.disabled", "false"); props.setProperty("guard.javax.persistence.jdbc.user", "user"); props.setProperty("guard.javax.persistence.jdbc.password", "secret"); props.setProperty("guard.javax.persistence.jdbc.driver", "org.h2.Driver"); - props.setProperty("guard.javax.persistence.jdbc.url", "jdbc:h2:file:./H2DB"); + props.setProperty("guard.javax.persistence.jdbc.url", "jdbc:h2:mem:testGuardDbResponse"); guardContext = new GuardContext(props); assertNotNull(guardContext); @@ -167,11 +168,12 @@ public class GuardContextTest { @Test public void testCreateDbEntry() { - Properties mockProperties = Mockito.mock(Properties.class); + Properties props = new Properties(); + props.setProperty(Util.PROP_GUARD_PERSISTENCE_UNIT, Util.JUNITPU); Instant startTime = Instant.now(); Instant endTime = Instant.now(); - guardContext = new GuardContext(mockProperties); + guardContext = new GuardContext(props); assertFalse(guardContext.createDbEntry(startTime, endTime, "testClosedLoopControlName", "testActor", "testRecipe", "testTarget", "testRequestId", "testSubRequestId", "testMessage", "testOutcome")); @@ -180,10 +182,10 @@ public class GuardContextTest { "testRecipe", "testTarget", "testRequestId", "testSubRequestId", "testMessage", "testOutcome")); PolicyEngineConstants.getManager().setEnvironmentProperty("guard.disabled", ""); - PolicyEngineConstants.getManager().setEnvironmentProperty("guard.jdbc.url", "jdbc:h2:file:./H2DB"); + PolicyEngineConstants.getManager().setEnvironmentProperty("guard.jdbc.url", "jdbc:h2:mem:testCreateDbEntry"); PolicyEngineConstants.getManager().setEnvironmentProperty("sql.db.username", "user"); PolicyEngineConstants.getManager().setEnvironmentProperty("sql.db.password", "secret"); - guardContext = new GuardContext(mockProperties); + guardContext = new GuardContext(props); assertTrue(guardContext.createDbEntry(startTime, endTime, "testClosedLoopControlName", "testActor", "testRecipe", "testTarget", "testRequestId", "testSubRequestId", "testMessage", "testOutcome")); diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java new file mode 100644 index 000000000..6fe0f2b50 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class GuardResultTest { + + @Test + public void testGuardResult() { + 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/m2/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java new file mode 100644 index 000000000..e17207634 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.google.common.io.Files; +import java.io.File; +import java.io.IOException; +import org.junit.Test; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.guard.Util.Pair; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class GuardUtilTest { + @Test + public void testLoadYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + tempYamlFile.deleteOnExit(); + + ControlLoopPolicy clPolicy = new ControlLoopPolicy(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clPolicy); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + Pair<ControlLoopPolicy, String> result = Util.loadYaml(tempYamlFile.getCanonicalPath()); + + assertEquals(clPolicy, result.parameterA); + assertEquals(clYamlString, result.parameterB); + } + + @Test + public void testLoadYamlError() throws IOException { + File tempDir = Files.createTempDir(); + tempDir.deleteOnExit(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYaml(tempDir.getCanonicalPath())); + } + + @Test + public void testLoadGuardYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + tempYamlFile.deleteOnExit(); + + ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clGuardPolicy); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + ControlLoopGuard result = Util.loadYamlGuard(tempYamlFile.getCanonicalPath()); + + assertEquals(clGuardPolicy, result); + } + + @Test + public void testLoadGuardYamlError() throws IOException { + File tempDir = Files.createTempDir(); + tempDir.deleteOnExit(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); + } + + @Test + public void testMisc() { + Util.setGuardEnvProp("Actor", "Judy Garland"); + assertEquals("Judy Garland", Util.getGuardProp("Actor")); + + Util.setGuardEnvProps("http://somewhere.over.the.rainbow", "Dorothy", "Toto"); + + 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)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java new file mode 100644 index 000000000..cdc862acb --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; +import org.junit.Test; + +public class PolicyGuardRequestTest { + + private static final String KANSAS = "Kansas"; + private static final String GET_BACK_HOME = "GetBackHome"; + private static final String DOROTHY = "Dorothy"; + + @Test + public void testPolicyGuardRequest() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardRequest(null, null, null, null)); + + PolicyGuardRequest request = new PolicyGuardRequest(DOROTHY, KANSAS, requestId, GET_BACK_HOME); + + request.setRequestId(requestId); + assertEquals(requestId, request.getRequestId()); + + request.setActor(DOROTHY); + assertEquals(DOROTHY, request.getActor()); + + request.setTarget(KANSAS); + assertEquals(KANSAS, request.getTarget()); + + request.setOperation(GET_BACK_HOME); + assertEquals(GET_BACK_HOME, request.getOperation()); + + assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java new file mode 100644 index 000000000..629555297 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; +import org.junit.Test; + +public class PolicyGuardResponseTest { + + private static final String GET_BACK_HOME = "GetBackHome"; + private static final String BACK_HOME = "BackHome"; + + @Test + public void testPolicyGuardResponse() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardResponse(null, null, null)); + + PolicyGuardResponse response = new PolicyGuardResponse(BACK_HOME, requestId, GET_BACK_HOME); + + response.setRequestId(requestId); + assertEquals(requestId, response.getRequestId()); + + response.setResult(BACK_HOME); + assertEquals(BACK_HOME, response.getResult()); + + response.setOperation(GET_BACK_HOME); + assertEquals(GET_BACK_HOME, response.getOperation()); + + assertEquals("PolicyGuardResponse [requestId=", response.toString().substring(0, 31)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java new file mode 100644 index 000000000..47af1fbc6 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Properties; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; +import org.onap.policy.drools.system.PolicyEngineConstants; +import org.onap.policy.drools.utils.logging.LoggerUtil; + +public class PolicyGuardXacmlHelperTest { + + private static final String TARGET = "target"; + private static final String REQUEST_ID = "requestId"; + private static final String RECIPE = "recipe"; + private static final String GUARD_URL = "guard.url"; + private static final String ACTOR = "actor"; + private static final Integer VF_COUNT = 100; + + /** + * Set up test class. + */ + @BeforeClass + public static void setupSimulator() throws Exception { + LoggerUtil.setLevel("ROOT", "INFO"); + LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); + + HttpServletServerFactoryInstance.getServerFactory().destroy(); + org.onap.policy.simulators.Util.buildGuardSim(); + + // + // Set guard properties + // + org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/policy/pdpx/v1/decision", "python", "test"); + } + + /** + * Shuts down simulator and performs 1 more test for the case where the connection fails. + */ + @AfterClass + public static void tearDownSimulator() { + HttpServletServerFactoryInstance.getServerFactory().destroy(); + + // Null/ Bad Connection Case + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, ACTOR, RECIPE, TARGET, + REQUEST_ID, VF_COUNT); + String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); + assertNotNull(rawDecision); + assertEquals(Util.DENY, rawDecision); + } + + @Test + public void testSimulator() { + PolicyGuardXacmlRequestAttributes request = new PolicyGuardXacmlRequestAttributes("clname_id", "actor_id", + "operation_id", "target_id", "request_id", VF_COUNT); + 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, + REQUEST_ID, VF_COUNT); + String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); + assertNotNull(rawDecision); + assertEquals(Util.DENY, rawDecision); + + // Permit Case + xacmlReq = new PolicyGuardXacmlRequestAttributes("clname", ACTOR, RECIPE, TARGET, REQUEST_ID, VF_COUNT); + rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); + assertNotNull(rawDecision); + assertEquals(Util.PERMIT, rawDecision); + + // Indeterminate case is in tearDown for efficiency + } + + @Test + public void testInit() { + final Properties savedEnvironment = (Properties) PolicyEngineConstants.getManager().getEnvironment().clone(); + + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, + "http://localhost:6669/pdp/api/getDecision,Dorothy"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, + "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, + "http://localhost:6969/policy/pdpx/v1/decision"); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.timeout", "1000"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().remove("pdpx.password"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.username", "python"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, "///"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("guard.disabled", ""); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("guard.disabled", "true"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().clear(); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().setEnvironment(savedEnvironment); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java new file mode 100644 index 000000000..3d49d99c1 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2018-2020 AT&T. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; +import org.junit.Test; + +public class PolicyGuardXacmlRequestAttributesTest { + + @Test + public void testPolicyGuardXacmlRequestAttributes() { + PolicyGuardXacmlRequestAttributes attributes = + new PolicyGuardXacmlRequestAttributes(null, null, null, null, null, null); + assertNotNull(attributes); + + UUID requestId = UUID.randomUUID(); + attributes.setRequestId(requestId.toString()); + assertEquals(requestId.toString(), attributes.getRequestId()); + + UUID operationId = UUID.randomUUID(); + attributes.setOperationId(operationId.toString()); + assertEquals(operationId.toString(), attributes.getOperationId()); + + UUID actorId = UUID.randomUUID(); + attributes.setActorId(actorId.toString()); + assertEquals(actorId.toString(), attributes.getActorId()); + + UUID targetId = UUID.randomUUID(); + attributes.setTargetId(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetId()); + + attributes.setTargetId(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetId()); + + UUID controlLoopId = UUID.randomUUID(); + attributes.setClnameId(controlLoopId.toString()); + assertEquals(controlLoopId.toString(), attributes.getClnameId()); + + attributes.setClnameId(null); + assertEquals(null, attributes.getClnameId()); + + Integer vfCount = 20; + attributes.setVfCount(vfCount); + assertEquals(vfCount, attributes.getVfCount()); + + attributes.setVfCount(null); + assertEquals(null, attributes.getVfCount()); + + assertEquals("PolicyGuardXacmlRequestAttributes [actorId=", attributes.toString().substring(0, 43)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java new file mode 100644 index 000000000..a8110ed04 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java @@ -0,0 +1,248 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.MatchParameters; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class PolicyGuardYamlToXacmlTest { + private static final String SOME_START_TIME = "someStartTime"; + private static final String SOME_END_TIME = "someEndTime"; + private static final String HOURS = "hours"; + private static final String TARGET2 = "WickedWitchOfTheWest"; + private static final String TARGET1 = "Wizard"; + private static final String ONAPPF_FILE = "ONAPPF"; + private static final String RECIPE = "GoToOz"; + private static final String TEXT1 = "WestWitches"; + private static final String TEXT2 = "EastWitches"; + private static final String OUT_XACML = ".out.xacml"; + 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(RECIPE); + List<String> targets = new ArrayList<>(); + targets.add(TARGET1); + targets.add(TARGET2); + 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", SOME_START_TIME); + activeTimeRange.put("end", SOME_END_TIME); + 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_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + + File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.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(RECIPE)); + assertTrue(result.contains(TARGET1)); + assertTrue(result.contains(TARGET2)); + assertTrue(result.contains("10")); + assertTrue(result.contains(HOURS)); + assertTrue(result.contains(SOME_START_TIME)); + assertTrue(result.contains(SOME_END_TIME)); + } + + @Test + public void testGenerateXacmlGuardPartial() throws IOException { + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + final File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + MatchParameters matchParameters = clGuard.getGuards().get(0).getMatch_parameters(); + matchParameters.setControlLoopName(null); + matchParameters.setActor(null); + matchParameters.setRecipe(null); + matchParameters.setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.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(RECIPE)); + assertFalse(result.contains(TARGET1)); + assertFalse(result.contains(TARGET2)); + assertTrue(result.contains("10")); + assertTrue(result.contains(HOURS)); + assertTrue(result.contains(SOME_START_TIME)); + assertTrue(result.contains(SOME_END_TIME)); + } + + @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 testGenerateXacmlGuardBlacklist() throws IOException { + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + List<String> blacklist = new ArrayList<>(); + blacklist.add(TEXT1); + blacklist.add(TEXT2); + clGuard.getGuards().get(0).getLimit_constraints().get(0).setBlacklist(blacklist); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains(TEXT1)); + assertTrue(result.contains(TEXT2)); + } + + @Test + public void testGenerateXacmlGuardBlacklistPartial() throws IOException { + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + List<String> blacklist = new ArrayList<>(); + blacklist.add(TEXT1); + blacklist.add(TEXT2); + GuardPolicy guardPolicy = clGuard.getGuards().get(0); + guardPolicy.getLimit_constraints().get(0).setBlacklist(blacklist); + + MatchParameters matchParameters = guardPolicy.getMatch_parameters(); + matchParameters.setControlLoopName(null); + matchParameters.setActor(null); + matchParameters.setRecipe(null); + matchParameters.setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains(TEXT1)); + assertTrue(result.contains(TEXT2)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java new file mode 100644 index 000000000..98c33c761 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import org.drools.core.util.IoUtils; + +/** + * 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) + */ +public class SupportTextFileUtils { + + private SupportTextFileUtils() { + // do nothing + } + + /** + * Method to return the contents of a text file as a string. + * + * @param textFilePath The path to the file as a string + * @return A string containing the contents of the file + * @throws IOException on errors reading text from the file + */ + public static String getTextFileAsString(final String textFilePath) { + return IoUtils.readFileAsString(new File(textFilePath)); + } + + /** + * Method to write contents of a string to a text file. + * + * @param outString The string to write + * @param textFile The file to write the string to + * @throws IOException on errors reading text from the file + */ + public static void putStringAsFile(final String outString, final File textFile) throws IOException { + try (final FileOutputStream textFileOutputStream = new FileOutputStream(textFile)) { + textFileOutputStream.write(outString.getBytes(StandardCharsets.UTF_8)); + } + } +} |