diff options
author | IanHowell <ian.howell@att.com> | 2018-03-29 15:04:28 -0500 |
---|---|---|
committer | IanHowell <ian.howell@att.com> | 2018-03-29 15:04:33 -0500 |
commit | c2390f53793402252ca747ec3d52734e63f6a6b4 (patch) | |
tree | 673847b9fc4fc0e2e4b01196a2d30510ed418146 | |
parent | 3635fc5c8d8409d1c5e0f521469a6aaca4d19ffe (diff) |
Add several JUnits for test coverage
This is several days worth of tests - future commits
will be smaller
Issue-ID: AAF-128
Change-Id: I32d9b76d3ff95b32f96eaaf3d2ab8a36167c5254
Signed-off-by: IanHowell <ian.howell@att.com>
18 files changed, 1697 insertions, 149 deletions
diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java index 89e1aa94..9de907d8 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/common/test/JU_Define.java @@ -7,9 +7,9 @@ * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at - * * + * * * * http://www.apache.org/licenses/LICENSE-2.0 - * * + * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,6 +25,10 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.junit.Before; +import static org.mockito.Mockito.*; +import org.onap.aaf.auth.common.Define; +import org.onap.aaf.cadi.Access; import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.config.Config; import org.onap.aaf.misc.env.Env; @@ -35,32 +39,39 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) -//TODO: Gabe [JUnit] class path/ class Define is missing, com.att.authz.common also missing public class JU_Define { - //Define define; public static String ROOT_NS="NS.Not.Set"; public static String ROOT_COMPANY=ROOT_NS; - - @Mock + Access acc; + @Mock Env envMock; - - -// @Before -// public void setUp(){ -// define = new Define(); -// } -// -// @Test -// public void testSet() throws CadiException { -// PowerMockito.when(envMock.getProperty(Config.AAF_ROOT_NS)).thenReturn("aaf_root_ns"); -// PowerMockito.when(envMock.getProperty(Config.AAF_ROOT_COMPANY)).thenReturn("aaf_root_company"); -// //PowerMockito.when(envMock.init().log()).thenReturn(null); -// //PowerMockito.doNothing().doThrow(new CadiException()).when(envMock).init().log(Matchers.anyString()); -// //define.set(envMock); -// } + + + @Before + public void setUp(){ + acc = mock(Access.class); + } + + @Test + public void testRootNS() { + //Define.ROOT_NS(); + } + + @Test + public void testRootCompany() { + //Define.ROOT_COMPANY(); + } + + @Test + public void testSet() throws CadiException { + when(acc.getProperty(Config.AAF_ROOT_NS,"org.onap.aaf")).thenReturn(".ns_Test"); + //when(acc.getProperty(Config.AAF_ROOT_COMPANY,null)).thenReturn("company_Test"); + //Define.set(acc); + } @Test - public void netYetTested() { - fail("Tests not yet implemented"); + public void testVarReplace() { + Define.varReplace("AAF_NS."); + Define.varReplace("test"); } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java index 1117fce7..f02a9de0 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzEnv.java @@ -7,9 +7,9 @@ * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at - * * + * * * * http://www.apache.org/licenses/LICENSE-2.0 - * * + * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -46,7 +46,7 @@ public class JU_AuthzEnv { private static final org.onap.aaf.cadi.Access.Level DEBUG = null; AuthzEnv authzEnv; enum Level {DEBUG, INFO, AUDIT, INIT, WARN, ERROR}; - + @Before public void setUp(){ PropAccess access = null; @@ -61,49 +61,49 @@ public class JU_AuthzEnv { public void testTransRate() { Long Result = authzEnv.transRate(); System.out.println("value of result " +Result); //Expected 300000 - assertNotNull(Result); + assertNotNull(Result); } - + @Test public void checkNewTransNoAvg() { - + Assert.assertNotNull(authzEnv.newTransNoAvg()); } - + @Test public void checkNewTrans() { Assert.assertNotNull(authzEnv.newTrans()); } - + @Test public void checkPropAccess() { Assert.assertNotNull(authzEnv.access()); } - + @Test public void checkgetProperties() { //TODO:[GABE]No setter for this, add? Assert.assertNotNull(authzEnv.getProperties()); Assert.assertNotNull(authzEnv.getProperties("test")); } - + @Test(expected = APIException.class) public void checkSetLog4JNames() throws APIException {//TODO: Find better way to test instead of just seeing if strings pass authzEnv.setLog4JNames("path", "root","service","audit","init","trace"); authzEnv.setLog4JNames("path", "root",null,"audit","init","trace"); } - + @Test public void checkPropertyGetters(){ authzEnv.setProperty("key","value"); Assert.assertEquals(authzEnv.getProperty("key"), "value"); Assert.assertEquals(authzEnv.getProperty("key","value"), "value"); } - + @Test public void checkPropertySetters(){ Assert.assertEquals(authzEnv.getProperty("key","value"), authzEnv.setProperty("key","value")); } - + @Test(expected = IOException.class) public void testDecryptException() throws IOException{ String encrypted = "enc:"; @@ -111,7 +111,7 @@ public class JU_AuthzEnv { authzEnv.decrypt(encrypted, true); authzEnv.decrypt("", false); } - + @Test public void testDecrypt() throws IOException{ String encrypted = "encrypted"; @@ -119,41 +119,41 @@ public class JU_AuthzEnv { System.out.println("value of res " +Result); assertEquals("encrypted",Result); } - + @Test public void testClassLoader() { ClassLoader cLoad = mock(ClassLoader.class); cLoad = authzEnv.classLoader(); Assert.assertNotNull(cLoad); } - + @Test public void testLoad() throws IOException { InputStream is = mock(InputStream.class); authzEnv.load(is); } - + @Test public void testLog() { Access.Level lvl = Access.Level.DEBUG; Object msgs = null; authzEnv.log(lvl, msgs); } - + @Test public void testLog1() { Exception e = new Exception(); Object msgs = null; authzEnv.log(e, msgs); } - + @Test public void testPrintf() { Access.Level lvl = Access.Level.DEBUG; Object msgs = null; authzEnv.printf(lvl, "Test", msgs); } - + @Test public void testWillLog() { Access.Level lvl = Access.Level.DEBUG; @@ -162,9 +162,9 @@ public class JU_AuthzEnv { Assert.assertFalse(test); test = authzEnv.willLog(lvl1); Assert.assertTrue(test); - + } - + @Test public void testSetLogLevel() { Access.Level lvl = Access.Level.DEBUG; diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java index b29e716a..f1243513 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/env/test/JU_AuthzTransOnlyFilter.java @@ -7,9 +7,9 @@ * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at - * * + * * * * http://www.apache.org/licenses/LICENSE-2.0 - * * + * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,21 +21,20 @@ ******************************************************************************/ package org.onap.aaf.auth.env.test; -import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import static org.mockito.Mockito.*; -import javax.servlet.http.HttpServletRequest; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.servlet.ServletRequest; -import org.onap.aaf.cadi.principal.TaggedPrincipal; -import org.onap.aaf.misc.env.Env; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.onap.aaf.auth.env.AuthzEnv; import org.onap.aaf.auth.env.AuthzTrans; @@ -44,9 +43,8 @@ import org.onap.aaf.auth.env.AuthzTransOnlyFilter; import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.Connector; import org.onap.aaf.cadi.TrustChecker; +import org.onap.aaf.cadi.principal.TaggedPrincipal; import org.onap.aaf.misc.env.LogTarget; -import org.onap.aaf.misc.env.Slot; -import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.env.Trans.Metric; @RunWith(MockitoJUnitRunner.class) @@ -59,20 +57,20 @@ public class JU_AuthzTransOnlyFilter { Object additionalTafLurs = mock(Object.class); ServletRequest servletRequestMock = mock(ServletRequest.class); AuthzTransOnlyFilter authzTransOnlyFilter; - + @Before public void setUp(){ authzTransOnlyFilter = new AuthzTransOnlyFilter(authzEnvMock); } - + /*@Test public void testProtected() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Method newTransMethod = AuthzTransFilter.class.getDeclaredMethod("newTrans"); newTransMethod.setAccessible(true); - + newTransMethod.invoke(authzTransFilter); }*/ - + @Test public void testStart() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); @@ -97,7 +95,7 @@ public class JU_AuthzTransOnlyFilter { authenticatedMethod.setAccessible(true); authenticatedMethod.invoke(aTF,authzTransMock, null); } - + @Test public void testTallyHo() throws CadiException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { AuthzTransOnlyFilter aTF = new AuthzTransOnlyFilter(authzEnvMock); diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java index fc812a2c..3219e476 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/layer/test/JU_Result.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,34 +25,175 @@ import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; +import static org.mockito.Mockito.*; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.servlet.ServletRequest; + +import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.layer.Result; +import junit.framework.Assert; + public class JU_Result { Result result; // @Mock // RV value; int status=0; - String details = "details"; + String details = "details"; String[] variables; - + @SuppressWarnings({ "unchecked", "rawtypes" }) @Before public void setUp(){ - //TODO: Gabe [JUnit] Not visible for junit - //result = new Result(result, status, details, variables); + //result = mock(Result.class); + + } + + @Test + public void testOk() { + Object value = null; + Collection col = new ArrayList(); + List list = mock(List.class); + Set set = mock(Set.class); + Integer[] R = new Integer[1]; + + Assert.assertNotNull(Result.ok()); + Assert.assertNotNull(Result.ok(value)); + Assert.assertNotNull(Result.ok(col)); + Assert.assertNotNull(Result.ok(list)); + Assert.assertNotNull(Result.ok(set)); + Assert.assertNotNull(Result.ok(R)); + + Collection<String> col1 = new ArrayList(); + List<String> list1 = new ArrayList(); + Set<String> set1 = new HashSet<String>(); + Integer[] R1 = new Integer[0]; + set1.add("derp"); + list1.add("test"); + col1.add("TEST"); + + Assert.assertNotNull(Result.ok(col1)); + Assert.assertNotNull(Result.ok(list1)); + Assert.assertNotNull(Result.ok(set1)); + Assert.assertNotNull(Result.ok(R1)); + } + + @Test + public void testErr() { + Result result = Result.create(null, 0, null, null); + Result r = result; + Exception e = mock(Exception.class); + + Assert.assertNotNull(result.err(r)); //Result case + Assert.assertNotNull(result.err(e)); //Exception case + Assert.assertNotNull(result.err(0, "test", "test")); //Multiple case + + } + + @Test + public void testCreate() { + Result result = Result.create(null, 0, null, null); + Assert.assertNotNull(Result.create(null, 0, null, null)); + Assert.assertNotNull(Result.create(null, 0, null, "arg")); + Assert.assertNotNull(result.create(0, result)); + } + + @Test + public void testOks() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNotNull(result.isOK()); + Assert.assertNotNull(result.notOK()); + Assert.assertNotNull(result.isOKhasData()); + Assert.assertNotNull(result.notOKorIsEmpty()); + + Result result1 = Result.create(null, 5, "test", "test"); + Assert.assertNotNull(result1.emptyList(true)); + Assert.assertNotNull(result1.isOK()); + Assert.assertNotNull(result1.notOK()); + Assert.assertNotNull(result1.isOKhasData()); + Assert.assertNotNull(result1.notOKorIsEmpty()); + + Result result2 = Result.create(null, 0, "test", "test"); + Assert.assertNotNull(result2.emptyList(false)); + Assert.assertNotNull(result2.isOKhasData()); + Assert.assertNotNull(result2.notOKorIsEmpty()); } -// @Test -// public void testPartialContent() { -// Result Res = result.partialContent(true); -// System.out.println("Res" +Res); -// assertEquals(details,Res.toString()); -// -// } - @Test - public void netYetTested() { - fail("Tests not yet implemented"); + public void testEmptyList() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNotNull(result.emptyList(true)); + Assert.assertNotNull(result.emptyList(false)); + Assert.assertFalse(result.isEmpty()); + } + + @Test + public void testPartialContent() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNotNull(result.partialContent(true)); + Assert.assertNotNull(result.partialContent(false)); + Assert.assertFalse(result.partialContent()); + + Result result1 = Result.create(null, 1, "test", null); + Assert.assertNotNull(result1.partialContent(true)); + Assert.assertNotNull(result1.partialContent()); } + @Test + public void testToString() { + Result result = Result.create(null, 0, null, null); + + Assert.assertNull(result.toString() ); + + Result result1 = Result.create(null, 5, "test", "test"); + + Assert.assertNotNull(result1.toString()); + + int value = 1; + Result result2 = Result.create(value , 5, "test", "test"); + + Assert.assertNotNull(result2.toString()); + } + + @Test + public void testErrorString() { + Result result = Result.create(null, 0, "test", "test"); + Assert.assertEquals("Error - test", result.errorString()); + Result result1 = Result.create(null, 1, "test", "test"); + Assert.assertEquals("Security - test",result1.errorString()); + Result result2 = Result.create(null, 2, "test", "test"); + Assert.assertEquals("Denied - test",result2.errorString()); + Result result3 = Result.create(null, 3, "test", "test"); + Assert.assertEquals("Policy - test",result3.errorString()); + Result result4 = Result.create(null, 4, "test", "test"); + Assert.assertEquals("BadData - test",result4.errorString()); + Result result5 = Result.create(null, 5, "test", "test"); + Assert.assertEquals("NotImplemented - test",result5.errorString()); + Result result6 = Result.create(null, 6, "test", "test"); + Assert.assertEquals("NotFound - test",result6.errorString()); + Result result7 = Result.create(null, 7, "test", "test"); + Assert.assertEquals("AlreadyExists - test",result7.errorString()); + Result result8 = Result.create(null, 8, "test", "test"); + Assert.assertEquals("ActionNotComplete - test",result8.errorString()); + } + + } + + + + + + + + diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_Organization.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_Organization.java new file mode 100644 index 00000000..9631e326 --- /dev/null +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_Organization.java @@ -0,0 +1,68 @@ +package org.onap.aaf.auth.org.test; + +import static org.mockito.Mockito.mock; + +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.HashSet; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.EmailWarnings; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.Organization.Expiration; +import org.onap.aaf.auth.org.Organization.Identity; +import org.onap.aaf.auth.org.Organization.Notify; +import org.onap.aaf.auth.org.Organization.Policy; +import org.onap.aaf.auth.org.Organization.Response; +import org.onap.aaf.auth.org.OrganizationException; + +import junit.framework.Assert; + +public class JU_Organization { + + AuthzTrans trans; + GregorianCalendar gc; + @Before + public void setUp() { + gc = new GregorianCalendar(1900, 1, 1); + trans = mock(AuthzTrans.class); + } + + @Test + public void test() throws OrganizationException { + //tests for Org null + Assert.assertEquals("n/a",Organization.NULL.getName()); + Assert.assertEquals("n/a",Organization.NULL.getDomain()); + Assert.assertEquals("n/a",Organization.NULL.getRealm()); + Assert.assertTrue(Organization.NULL.getIdentity(trans, "test") instanceof Identity); + Assert.assertEquals("n/a",Organization.NULL.isValidID(trans, null)); + Assert.assertEquals("n/a",Organization.NULL.isValidPassword(trans, null, null, null)); + Assert.assertTrue(Organization.NULL.getIdentityTypes() instanceof HashSet); + Assert.assertTrue(Organization.NULL.notify(trans, Notify.PasswordExpiration, null, null, null, null, null) instanceof Response); + Assert.assertEquals(0,Organization.NULL.sendEmail(trans, null, null, null, null, null)); + Assert.assertEquals(gc.getTime(),Organization.NULL.whenToValidate(null, null)); + Assert.assertEquals(gc,Organization.NULL.expiration(gc, Expiration.Password)); + Assert.assertTrue(Organization.NULL.getApprovers(trans, null) instanceof ArrayList); + Assert.assertEquals("",Organization.NULL.getApproverType()); + Assert.assertEquals(0,Organization.NULL.startOfDay()); + Assert.assertFalse(Organization.NULL.canHaveMultipleCreds(null)); + Assert.assertFalse(Organization.NULL.isValidCred(trans, null)); + Assert.assertEquals("Null Organization rejects all Policies",Organization.NULL.validate(trans, Policy.CHANGE_JOB, null, null)); + Assert.assertFalse(Organization.NULL.isTestEnv()); + Organization.NULL.setTestMode(true); + + //tests for org emailWarnings + Assert.assertTrue(Organization.NULL.emailWarningPolicy() instanceof EmailWarnings); + Assert.assertEquals(604800000L, Organization.NULL.emailWarningPolicy().credEmailInterval()); + Assert.assertEquals(604800000L, Organization.NULL.emailWarningPolicy().roleEmailInterval()); + Assert.assertEquals(259200000L, Organization.NULL.emailWarningPolicy().apprEmailInterval()); + Assert.assertEquals(2592000000L, Organization.NULL.emailWarningPolicy().credExpirationWarning()); + Assert.assertEquals(2592000000L, Organization.NULL.emailWarningPolicy().roleExpirationWarning()); + Assert.assertEquals(1209600000L, Organization.NULL.emailWarningPolicy().emailUrgentWarning()); + Assert.assertTrue(Organization.NULL.getPasswordRules() instanceof String[]); + + } + +} diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java index 01b8256f..79e8a4a1 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationException.java @@ -7,9 +7,9 @@ * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at - * * + * * * * http://www.apache.org/licenses/LICENSE-2.0 - * * + * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,18 +31,21 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_OrganizationException { - + OrganizationException organizationException; - - @Before - public void setUp(){ - organizationException = new OrganizationException(); - } - + OrganizationException organizationException1; + OrganizationException organizationException2; + OrganizationException organizationException3; + OrganizationException organizationException4; @Test - public void test() { - assertTrue(true); + public void testOrganizationException() { + Throwable thr = new Throwable(); + organizationException = new OrganizationException(); + organizationException1 = new OrganizationException("test"); + organizationException2 = new OrganizationException(thr); + organizationException3 = new OrganizationException("test", thr); + organizationException4 = new OrganizationException("test", thr, true, true); } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java index 2136e786..9723cd9e 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java @@ -7,9 +7,9 @@ * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at - * * + * * * * http://www.apache.org/licenses/LICENSE-2.0 - * * + * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,6 +27,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import static org.mockito.Mockito.mock; import org.onap.aaf.auth.env.AuthzEnv; +import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.org.OrganizationException; import org.onap.aaf.auth.org.OrganizationFactory; import org.onap.aaf.misc.env.APIException; @@ -54,11 +55,17 @@ public class JU_OrganizationFactory { public void testInit() throws OrganizationException { organizationFactory.init(bEnv); } - -// @SuppressWarnings("static-access") TODO:Fix this AAF-111 -// @Test(expected = OrganizationException.class) -// public void testObtain() throws OrganizationException{ -// PowerMockito.when(authzEnvMock.getProperty("Organization."+orgNS)).thenReturn("notnull"); -// organizationFactory.obtain(authzEnvMock, orgNS); -// } + + @SuppressWarnings("static-access") //TODO:Fix this once real input is available AAF-111 + @Test(expected = OrganizationException.class) + public void testObtain() throws OrganizationException{ + PowerMockito.when(authzEnvMock.getProperty("Organization."+orgNS)).thenReturn("notnull"); + //organizationFactory.obtain(authzEnvMock, orgNS); + } + + @Test + public void testGet() throws OrganizationException { //TODO: Fix with when then return on fail + AuthzTrans trans = mock(AuthzTrans.class); + //organizationFactory.get(trans); + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java index 26e9717f..e9c382d5 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/rserv/test/JU_CachingFileAccess.java @@ -7,9 +7,9 @@ * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at - * * + * * * * http://www.apache.org/licenses/LICENSE-2.0 - * * + * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,39 +21,34 @@ ******************************************************************************/ package org.onap.aaf.auth.rserv.test; -import static org.junit.Assert.*; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; -import static org.mockito.Matchers.*; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Field; -import java.nio.file.Files; -import java.nio.file.Paths; import java.util.NavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.onap.aaf.auth.rserv.CachingFileAccess; import org.onap.aaf.auth.rserv.HttpCode; import org.onap.aaf.auth.rserv.Match; - -//import org.onap.aaf.auth.rserv.CachingFileAccess.Content; -import java.util.NavigableMap; import org.onap.aaf.misc.env.EnvJAXB; import org.onap.aaf.misc.env.LogTarget; -import org.onap.aaf.misc.env.StaticSlot; import org.onap.aaf.misc.env.Store; import org.onap.aaf.misc.env.Trans; import org.powermock.modules.junit4.PowerMockRunner; @@ -67,8 +62,8 @@ public class JU_CachingFileAccess { HttpCode httpCode; EnvJAXB envJ; Trans trans; - - + + @Before public void setUp() throws IOException{ trans = mock(Trans.class); @@ -85,7 +80,7 @@ public class JU_CachingFileAccess { cachingFileAccess = new CachingFileAccess(envJ,"test"); - + } @Test @@ -100,14 +95,14 @@ public class JU_CachingFileAccess { cachingFileAccess.setEnv(store1, test1); //These don't reach all the branches for some reason cachingFileAccess.setEnv(store2, test2); } - + @Test public void testHandle() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { HttpServletRequest req = mock(HttpServletRequest.class); Trans trans = mock(Trans.class); HttpServletResponse resp = mock(HttpServletResponse.class); when(req.getPathInfo()).thenReturn("path/to/file"); - + Field matchField = HttpCode.class.getDeclaredField("match"); matchField.setAccessible(true); Match match = mock(Match.class); @@ -117,27 +112,27 @@ public class JU_CachingFileAccess { when(match.param(anyString(), anyString())).thenReturn("clear"); cachingFileAccess.handle(trans, req, resp); } - + @Test public void testWebPath() { EnvJAXB envJ = mock(EnvJAXB.class); String web_path_test = "TEST"; Assert.assertEquals(web_path_test, cachingFileAccess.webPath()); } - + @Test public void testCleanupParams() { NavigableMap<String,org.onap.aaf.auth.rserv.Content> content = new ConcurrentSkipListMap<String,org.onap.aaf.auth.rserv.Content>(); - cachingFileAccess.cleanupParams(50, 500); //TODO: find right input + cachingFileAccess.cleanupParams(50, 500); //TODO: find right input } - + @Test public void testLoad() throws IOException { cachingFileAccess.load(null, null, "1220227200L/1220227200L", null, 1320227200L ); String filePath = "test/output_key"; File keyfile = new File(filePath); RandomAccessFile randFile = new RandomAccessFile (keyfile,"rw"); - + String dPath = "test/"; File directoryPath = new File(dPath); directoryPath.mkdir(); @@ -152,14 +147,14 @@ public class JU_CachingFileAccess { cachingFileAccess.load(null, filePath1, "-", "test", -1); keyfile1.delete(); } - + @Test public void testLoadOrDefault() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException, InstantiationException { String filePath = "test/output_key"; File keyfile = new File(filePath); cachingFileAccess.loadOrDefault(trans, filePath, "-", null, null); keyfile.delete(); - + Trans trans = mock(Trans.class); String filePath1 = "test/output_key.txt"; @@ -172,7 +167,7 @@ public class JU_CachingFileAccess { //cachingFileAccess.loadOrDefault(trans, "bs", "also bs", "test", null); //TODO: Needs more testing AAF-111 //keyfile1.delete(); } - + @Test public void testInvalidate() { //NavigableMap<String,org.onap.aaf.auth.rserv.Content> content = new ConcurrentSkipListMap<String,org.onap.aaf.auth.rserv.Content>(); diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java index fb59a54d..11aaa424 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java @@ -7,9 +7,9 @@ * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at - * * + * * * * http://www.apache.org/licenses/LICENSE-2.0 - * * + * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -36,32 +36,36 @@ import org.junit.Test; import org.junit.Test; import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.env.AuthzTransOnlyFilter; +import org.onap.aaf.auth.layer.Result; import org.onap.aaf.auth.validation.Validator; import org.onap.aaf.cadi.principal.TaggedPrincipal; +import junit.framework.Assert; + public class JU_Validator { - + Validator validator; - + String base = "\\x25\\x28\\x29\\x2C-\\x2E\\x30-\\x39\\x3D\\x40-\\x5A\\x5F\\x61-\\x7A"; + @Before public void setUp() { validator = new Validator(); } - + @Test public void testNullOrBlank() { validator.nullOrBlank(null, "str"); validator.nullOrBlank("test", ""); validator.nullOrBlank("test", null); } - + @Test public void testIsNull() { Object o = new Object(); validator.isNull(null, null); validator.isNull(null, o); } - + @Test public void testDescription() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class c = validator.getClass(); @@ -74,7 +78,122 @@ public class JU_Validator { descriptionMethod.invoke(validator,null, null); descriptionMethod.invoke(validator,null, "[\\\\x25\\\\x28\\\\x29\\\\x2C-\\\\x2E\\\\x30-\\\\x39\\\\x3D\\\\x40-\\\\x5A\\\\x5F\\\\x61-\\\\x7A\\\\x20]+"); - + + } + + @Test + public void testPermType() { + Assert.assertNotNull(validator.permType("[\\\\w.-]+")); + Assert.assertNotNull(validator.permType(null)); + Assert.assertNotNull(validator.permType("")); + Assert.assertNotNull(validator.permType("aewfew")); + } + + @Test + public void testPermType1() { + Assert.assertNotNull(validator.permType("[\\\\w.-]+",null)); + Assert.assertNotNull(validator.permType(null,null)); + Assert.assertNotNull(validator.permType("","test")); + Assert.assertNotNull(validator.permType("aewfew","test")); + } + + @Test + public void testPermInstance() { + + String middle = "]+[\\\\*]*|\\\\*|(([:/]\\\\*)|([:/][!]{0,1}["; + Assert.assertNotNull(validator.permInstance("[" + base + middle + base + "]+[\\\\*]*[:/]*))+")); + Assert.assertNotNull(validator.permInstance(null)); + Assert.assertNotNull(validator.permInstance("")); + Assert.assertNotNull(validator.permInstance("test")); + } + + @Test + public void testErr() { + Assert.assertFalse(validator.err()); + validator.isNull("test", null); + Assert.assertTrue(validator.err()); + } + + @Test + public void testErrs() { + validator.isNull("test", null); + Assert.assertNotNull(validator.errs()); + } + + @Test + public void testPermAction() { + Assert.assertNotNull(validator.permAction("[" + base + "]+" + "|\\\\*")); + Assert.assertNotNull(validator.permAction("test")); + } + + @Test + public void testRole() { + Assert.assertNotNull(validator.role("[\\\\w.-]+")); + Assert.assertNotNull(validator.role(null)); + Assert.assertNotNull(validator.role("")); + Assert.assertNotNull(validator.role("aewfew")); + } + + @Test + public void testNs() { + Assert.assertNotNull(validator.ns("[\\\\w.-]+")); + Assert.assertNotNull(validator.ns("")); + Assert.assertNotNull(validator.ns(".access")); + } + + @Test + public void testKey() { + Assert.assertNotNull(validator.key("[\\\\w.-]+")); + Assert.assertNotNull(validator.key("")); + Assert.assertNotNull(validator.key(".access")); + } + + @Test + public void testValue() { + Assert.assertNotNull(validator.value(base)); + Assert.assertNotNull(validator.value("")); + Assert.assertNotNull(validator.value(".access")); + } + + @Test + public void testNotOK() { + Result<?> test = mock(Result.class); + validator.isNull("test", null); + when(test.notOK()).thenReturn(true); + Assert.assertNotNull(validator.notOK(null)); + Assert.assertNotNull(validator.notOK(test)); + } + + @Test + public void testIntRange() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class c = validator.getClass(); + Class[] cArg = new Class[4]; + cArg[0] = String.class; + cArg[1] = int.class; + cArg[2] = int.class; + cArg[3] = int.class; //Steps to test a protected method + Method intRangeMethod = c.getDeclaredMethod("intRange", cArg); + intRangeMethod.setAccessible(true); + intRangeMethod.invoke(validator,"Test",5,1,10); + intRangeMethod.invoke(validator,"Test",1,5,10); + intRangeMethod.invoke(validator,"Test",11,5,10); + intRangeMethod.invoke(validator,"Test",5,6,4); + } + + @Test + public void testFloatRange() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class c = validator.getClass(); + Class[] cArg = new Class[4]; + cArg[0] = String.class; + cArg[1] = float.class; + cArg[2] = float.class; + cArg[3] = float.class; //Steps to test a protected method + Method floatRangeMethod = c.getDeclaredMethod("floatRange", cArg); + floatRangeMethod.setAccessible(true); + floatRangeMethod.invoke(validator,"Test",5f,1f,10f); + floatRangeMethod.invoke(validator,"Test",1f,5f,10f); + floatRangeMethod.invoke(validator,"Test",11f,5f,10f); + floatRangeMethod.invoke(validator,"Test",5f,6f,4f); } @Test @@ -86,14 +205,14 @@ public class JU_Validator { assertFalse(Validator.INST_CHARS.matcher("Howd?yDoody").matches()); assertTrue(Validator.INST_CHARS.matcher("_HowdyDoody").matches()); - // + // assertTrue(Validator.ACTION_CHARS.matcher("*").matches()); assertTrue(Validator.INST_CHARS.matcher("*").matches()); assertFalse(Validator.ACTION_CHARS.matcher(":*").matches()); assertTrue(Validator.INST_CHARS.matcher(":*").matches()); assertFalse(Validator.ACTION_CHARS.matcher(":*:*").matches()); assertTrue(Validator.INST_CHARS.matcher(":*:*").matches()); - + assertFalse(Validator.ACTION_CHARS.matcher(":hello").matches()); assertTrue(Validator.INST_CHARS.matcher(":hello").matches()); assertFalse(Validator.INST_CHARS.matcher("hello:").matches()); @@ -120,7 +239,7 @@ public class JU_Validator { assertFalse(Validator.INST_CHARS.matcher(":h:*:*h").matches()); assertTrue(Validator.INST_CHARS.matcher(":com.test.*:ns:*").matches()); - + assertFalse(Validator.ACTION_CHARS.matcher("1234+235gd").matches()); assertTrue(Validator.ACTION_CHARS.matcher("1234-235gd").matches()); assertTrue(Validator.ACTION_CHARS.matcher("1234-23_5gd").matches()); @@ -134,7 +253,7 @@ public class JU_Validator { assertFalse(Validator.ACTION_CHARS.matcher("").matches()); assertFalse(Validator.ACTION_CHARS.matcher(" ").matches()); - // Allow % and = (Needed for Escaping & Base64 usages) jg + // Allow % and = (Needed for Escaping & Base64 usages) jg assertTrue(Validator.ACTION_CHARS.matcher("1234%235g=d").matches()); assertFalse(Validator.ACTION_CHARS.matcher(":1234%235g=d").matches()); assertTrue(Validator.INST_CHARS.matcher("1234%235g=d").matches()); @@ -145,7 +264,7 @@ public class JU_Validator { assertTrue(Validator.INST_CHARS.matcher(":1234%235g=d:==%20:*").matches()); assertTrue(Validator.INST_CHARS.matcher(":*:==%20:*").matches()); - // Allow / instead of : (more natural instance expression) jg + // Allow / instead of : (more natural instance expression) jg assertFalse(Validator.INST_CHARS.matcher("1234/a").matches()); assertTrue(Validator.INST_CHARS.matcher("/1234/a").matches()); assertTrue(Validator.INST_CHARS.matcher("/1234/*/a/").matches()); @@ -165,7 +284,7 @@ public class JU_Validator { assertFalse(Validator.INST_CHARS.matcher("123#4-23@5g:d").matches()); assertFalse(Validator.INST_CHARS.matcher("").matches()); - + for( char c=0x20;c<0x7F;++c) { boolean b; switch(c) { @@ -181,18 +300,18 @@ public class JU_Validator { b=true; } } - + assertFalse(Validator.ID_CHARS.matcher("abc").matches()); assertFalse(Validator.ID_CHARS.matcher("").matches()); assertTrue(Validator.ID_CHARS.matcher("abc@att.com").matches()); assertTrue(Validator.ID_CHARS.matcher("ab-me@att.com").matches()); assertTrue(Validator.ID_CHARS.matcher("ab-me_.x@att._-com").matches()); - + assertFalse(Validator.NAME_CHARS.matcher("ab-me_.x@att._-com").matches()); assertTrue(Validator.NAME_CHARS.matcher("ab-me").matches()); assertTrue(Validator.NAME_CHARS.matcher("ab-me_.xatt._-com").matches()); - + // 7/22/2016 assertTrue(Validator.INST_CHARS.matcher( "/!com.att.*/role/write").matches()); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java index 05ee90cd..b44de05f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java @@ -48,12 +48,7 @@ public class GetAccess extends PropAccess { */ @Override public String getProperty(String tag) { - String rv; - rv = super.getProperty(tag, null); - if(rv==null && getter!=null) { - rv = getter.get(tag, null, true); - } - return rv; + return getProperty(tag, null); } public Get get() { diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java new file mode 100644 index 00000000..441765a6 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java @@ -0,0 +1,363 @@ +/******************************************************************************* + * * org.onap.aaf + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.aaf.cadi.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; +import org.mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.reflect.Field; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; + +import org.onap.aaf.cadi.AbsUserCache; +import org.onap.aaf.cadi.AbsUserCache.*; +import org.onap.aaf.cadi.Access; +import org.onap.aaf.cadi.CachedPrincipal.Resp; +import org.onap.aaf.cadi.CachingLur; +import org.onap.aaf.cadi.GetCred; +import org.onap.aaf.cadi.Hash; +import org.onap.aaf.cadi.Permission; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.User; +import org.onap.aaf.cadi.lur.LocalPermission; +import org.onap.aaf.cadi.principal.CachedBasicPrincipal; + +public class JU_AbsUserCache { + + @Mock private CachingLur<Permission> cl; + + @Mock private Principal principal; + + @Mock private CachedBasicPrincipal cbp; + + @Mock private LocalPermission permission1; + @Mock private LocalPermission permission2; + + + private Access access; + + private ByteArrayOutputStream outStream; + + private String name1 = "name1"; + private String name2 = "name2"; + private byte[] password = "password".getBytes(); + + private static Field timerField; + + @BeforeClass + public static void setupOnce() throws Exception { + timerField = AbsUserCache.class.getDeclaredField("timer"); + timerField.setAccessible(true); + } + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + + // This must happen after changing System.out + access = new PropAccess(); + + when(permission1.getKey()).thenReturn("NewKey1"); + when(permission2.getKey()).thenReturn("NewKey2"); + + timerField.set(null, null); + } + + @After + public void tearDown() throws Exception { + System.setOut(System.out); + timerField.set(null, null); + } + + @SuppressWarnings("unused") + @Test + public void constructorTest() { + int cleanInterval = 65000; + int maxInterval = 70000; + + AbsUserCacheStub<Permission> aucs1 = new AbsUserCacheStub<Permission>(access, cleanInterval, maxInterval, Integer.MAX_VALUE); + String output = outStream.toString().split(" ", 2)[1]; + StringBuilder expected = new StringBuilder(); + expected.append("INIT [cadi] Cleaning Thread initialized with interval of "); + expected.append(String.valueOf(cleanInterval)); + expected.append(" ms and max objects of "); + expected.append(String.valueOf(maxInterval)); + expected.append("\n"); + assertThat(output, is(expected.toString())); + + outStream.reset(); + AbsUserCacheStub<Permission> aucs2 = new AbsUserCacheStub<Permission>(access, cleanInterval, maxInterval, Integer.MAX_VALUE); + output = outStream.toString().split(" ", 2)[1]; + expected = new StringBuilder(); + expected.append("INIT [cadi] Cleaning Thread initialized with interval of "); + expected.append(String.valueOf(cleanInterval)); + expected.append(" ms and max objects of "); + expected.append(String.valueOf(maxInterval)); + expected.append("\n"); + assertThat(output, is(expected.toString())); + + AbsUserCacheStub<Permission> aucs3 = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + AbsUserCacheStub<Permission> aucs4 = new AbsUserCacheStub<Permission>(aucs1); + + // For coverage + AbsUserCacheCLStub<Permission> auccls1 = new AbsUserCacheCLStub<Permission>(aucs1); + aucs1.setLur(cl); + auccls1 = new AbsUserCacheCLStub<Permission>(aucs1); + AbsUserCacheCLStub<Permission> auccls2 = new AbsUserCacheCLStub<Permission>(aucs3); + } + + @Test + public void setLurTest() { + AbsUserCacheStub<Permission> aucs1 = new AbsUserCacheStub<Permission>(access, 65000, 70000, Integer.MAX_VALUE); + AbsUserCacheStub<Permission> aucs2 = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + aucs1.setLur(cl); + aucs2.setLur(cl); + } + + @Test + public void addUserGetUserTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user; + + // Test adding a user with a principal (non-GetCred). user does not have a cred + // Then test getting that user + when(principal.getName()).thenReturn(name1); + user = new User<Permission>(principal, 0); + aucs.addUser(user); + assertThat(aucs.getUser(principal), is(user)); + + // Test adding a user with a principal (GetCred). user does not have a cred + // Then test getting that user + GetCredStub gc = new GetCredStub(); + user = new User<Permission>(gc, 0); + aucs.addUser(user); + assertThat(aucs.getUser(gc), is(user)); + + // Test adding a user with no principal + // Then test getting that user via his name and cred + user = new User<Permission>(name2, password); + aucs.addUser(user); + assertThat(aucs.getUser(name2, password), is(user)); + + // Test getting a user by a CachedBasicPrincipal + when(cbp.getName()).thenReturn(name2); + when(cbp.getCred()).thenReturn(password); + assertThat(aucs.getUser(cbp), is(user)); + + // Force the user to expire, then test that he is no longer in the cache + Field permExpiresField = User.class.getDeclaredField("permExpires"); + permExpiresField.setAccessible(true); + permExpiresField.set(user, 0); + assertThat(aucs.getUser(name2, password), is(nullValue())); + + // Test adding a user with a custom key + // Then test gettin that user + user = new User<Permission>(principal, 0); + String key = principal.getName() + "NoCred"; + aucs.addUser(key, user); + assertThat(aucs.getUser(principal), is(user)); + + // Test that getUser returns null for principals that don't match any users + when(principal.getName()).thenReturn("not in the cache"); + assertThat(aucs.getUser(principal), is(nullValue())); + + // That that getUser returns null for name/creds that are not in the cache + assertThat(aucs.getUser("not a real user", "not in the cache".getBytes()), is(nullValue())); + } + + @Test + public void removeTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user; + + when(principal.getName()).thenReturn(name1); + user = new User<Permission>(principal); + // Add a user with a principal + aucs.addUser(user); + // Check that the user is in the cache + assertThat(aucs.getUser(principal), is(user)); + // Remove the user + when(principal.getName()).thenReturn(name1 + "NoCred"); + aucs.remove(user); + // Check that the user is no longer in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(nullValue())); + + // Add the user again + aucs.addUser(user); + // Check that the user is in the cache + assertThat(aucs.getUser(principal), is(user)); + // Remove the user by name + aucs.remove(name1 + "NoCred"); + // Check that the user is no longer in the cache + assertThat(aucs.getUser(principal), is(nullValue())); + + // Coverage test - attempt to remove a user that is not in the cache + aucs.remove(name1 + "NoCred"); + assertThat(aucs.getUser(principal), is(nullValue())); + } + + @Test + public void clearAllTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user1; + User<Permission> user2; + + // Add some users to the cache + when(principal.getName()).thenReturn(name1); + user1 = new User<Permission>(principal); + when(principal.getName()).thenReturn(name2); + user2 = new User<Permission>(principal); + aucs.addUser(user1); + aucs.addUser(user2); + + // Check that the users are in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(user1)); + when(principal.getName()).thenReturn(name2); + assertThat(aucs.getUser(principal), is(user2)); + + // Clear the cache + aucs.clearAll(); + + // Check that the users are no longer in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(nullValue())); + when(principal.getName()).thenReturn(name2); + assertThat(aucs.getUser(principal), is(nullValue())); + } + + @Test + public void dumpInfoTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user1; + User<Permission> user2; + + Principal principal1 = mock(Principal.class); + Principal principal2 = mock(Principal.class); + when(principal1.getName()).thenReturn(name1); + when(principal2.getName()).thenReturn(name2); + + // Add some users with permissions to the cache + user1 = new User<Permission>(principal1); + user1.add(permission1); + user1.add(permission2); + user2 = new User<Permission>(principal2); + user2.add(permission1); + user2.add(permission2); + aucs.addUser(user1); + aucs.addUser(user2); + + // Dump the info + List<AbsUserCache<Permission>.DumpInfo> dumpInfo = aucs.dumpInfo(); + assertThat(dumpInfo.size(), is(2)); + + // Utility lists + List<String> names = new ArrayList<String>(); + names.add(name1); + names.add(name2); + List<String> permissions = new ArrayList<String>(); + permissions.add("NewKey1"); + permissions.add("NewKey2"); + + // We need to use "contains" because the dumpInfo was created from a list, so we don't know it's order + for (AbsUserCache<Permission>.DumpInfo di : dumpInfo) { + assertTrue(names.contains(di.user)); + for (String perm : di.perms) { + assertTrue(permissions.contains(perm)); + } + } + } + + @Test + public void handlesExclusivelyTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + assertFalse(aucs.handlesExclusively(permission1)); + assertFalse(aucs.handlesExclusively(permission2)); + } + + @Test + public void destroyTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + aucs.destroy(); + aucs = new AbsUserCacheStub<Permission>(access, 1, 1, Integer.MAX_VALUE); + aucs.destroy(); + } + + @Test + public void missTest() throws IOException { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + // Add the Miss to the missmap + assertTrue(aucs.addMiss("key", password)); // This one actually adds it + assertTrue(aucs.addMiss("key", password)); // this one doesn't really do anything + assertTrue(aucs.addMiss("key", password)); // neither does this one + assertFalse(aucs.addMiss("key", password)); // By this time, the missMap is tired of this nonsense, and retaliates + assertFalse(aucs.addMiss("key", password)); // Oh yea. He's angry + + // Can't really test this due to visibility + aucs.missed("key", password); + + // Coverage + AbsUserCacheStub<Permission> aucs1 = new AbsUserCacheStub<Permission>(access, 1, 1, Integer.MAX_VALUE); + aucs1.addMiss("key", password); + } + + class AbsUserCacheStub<PERM extends Permission> extends AbsUserCache<PERM> { + public AbsUserCacheStub(Access access, long cleanInterval, int highCount, int usageCount) { super(access, cleanInterval, highCount, usageCount); } + public AbsUserCacheStub(AbsUserCache<PERM> cache) { super(cache); } + @Override public void setLur(CachingLur<PERM> lur) { super.setLur(lur); } + @Override public void addUser(User<PERM> user) { super.addUser(user); } + @Override public void addUser(String key, User<PERM> user) { super.addUser(key, user); } + @Override public User<PERM> getUser(Principal p) { return super.getUser(p); } + @Override public User<PERM> getUser(CachedBasicPrincipal p) { return super.getUser(p); } + @Override public User<PERM> getUser(String user, byte[] cred) { return super.getUser(user, cred); } + @Override public void remove(User<PERM> user) { super.remove(user); } + @Override public boolean addMiss(String key, byte[] bs) { return super.addMiss(key, bs); } + @Override public Miss missed(String key, byte[] bs) throws IOException { return super.missed(key, bs); } + } + + class AbsUserCacheCLStub<PERM extends Permission> extends AbsUserCache<PERM> implements CachingLur<PERM> { + public AbsUserCacheCLStub(AbsUserCache<PERM> cache) { super(cache); } + @Override public Permission createPerm(String p) { return null; } + @Override public boolean fish(Principal bait, Permission pond) { return false; } + @Override public void fishAll(Principal bait, List<Permission> permissions) { } + @Override public boolean handles(Principal principal) { return false; } + @Override public Resp reload(User<PERM> user) { return null; } + @Override public void setDebug(String commaDelimIDsOrNull) { } + } + + class GetCredStub implements Principal, GetCred { + @Override public byte[] getCred() { return password; } + @Override public String getName() { return name1; } + } + +} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiException.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiException.java new file mode 100644 index 00000000..fa3b5cc4 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiException.java @@ -0,0 +1,121 @@ +/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * *
+ ******************************************************************************/
+package org.onap.aaf.cadi.test;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.onap.aaf.cadi.CadiException;
+
+import static org.hamcrest.CoreMatchers.is;
+
+public class JU_CadiException {
+ @Test
+ public void testCadiException() {
+ CadiException exception = new CadiException();
+
+ assertNotNull(exception);
+ }
+
+ @Test
+ public void testCadiExceptionString() {
+ CadiException exception = new CadiException("New Exception");
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("New Exception"));
+ }
+
+ @Test
+ public void testCadiExceptionThrowable() {
+ CadiException exception = new CadiException(new Throwable("New Exception"));
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception"));
+ }
+
+ @Test
+ public void testCadiExceptionStringThrowable() {
+ CadiException exception = new CadiException("New Exception",new Throwable("New Exception"));
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("New Exception"));
+
+ }
+
+ @Test
+ public void testCadiException1() {
+ CadiException exception = new CadiException();
+
+ assertNotNull(exception);
+ }
+
+ @Test
+ public void testCadiExceptionString1() {
+ CadiException exception = new CadiException("New Exception");
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("New Exception"));
+ }
+
+ @Test
+ public void testCadiExceptionThrowable1() {
+ CadiException exception = new CadiException(new Throwable("New Exception"));
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception"));
+ }
+
+ @Test
+ public void testCadiExceptionStringThrowable1() {
+ CadiException exception = new CadiException("New Exception",new Throwable("New Exception"));
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("New Exception"));
+
+ }
+
+ @Test
+ public void testCadiException2() {
+ CadiException exception = new CadiException();
+
+ assertNotNull(exception);
+ }
+
+ @Test
+ public void testCadiExceptionString2() {
+ CadiException exception = new CadiException("New Exception");
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("New Exception"));
+ }
+
+ @Test
+ public void testCadiExceptionThrowable2() {
+ CadiException exception = new CadiException(new Throwable("New Exception"));
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception"));
+ }
+
+ @Test
+ public void testCadiExceptionStringThrowable2() {
+ CadiException exception = new CadiException("New Exception",new Throwable("New Exception"));
+ assertNotNull(exception);
+ assertThat(exception.getMessage(), is("New Exception"));
+
+ }
+
+
+
+}
diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiWrap.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiWrap.java new file mode 100644 index 00000000..8bcb6329 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CadiWrap.java @@ -0,0 +1,161 @@ +/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * *
+ ******************************************************************************/
+package org.onap.aaf.cadi.test;
+
+import org.junit.*;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.security.Principal;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.CachingLur;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.CadiWrap;
+import org.onap.aaf.cadi.Lur;
+import org.onap.aaf.cadi.Permission;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.User;
+import org.onap.aaf.cadi.CachedPrincipal.Resp;
+import org.onap.aaf.cadi.filter.MapPermConverter;
+import org.onap.aaf.cadi.lur.EpiLur;
+import org.onap.aaf.cadi.principal.TaggedPrincipal;
+import org.onap.aaf.cadi.taf.TafResp;
+
+public class JU_CadiWrap {
+
+ @Mock
+ private HttpServletRequest request;
+
+ @Mock
+ private TafResp tafResp;
+
+ @Mock
+ private TaggedPrincipal principle;
+
+ @Mock
+ private Lur lur;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
+ }
+
+ @After
+ public void tearDown() {
+ System.setOut(System.out);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testInstantiate() throws CadiException {
+ Access a = new PropAccess();
+ when(tafResp.getAccess()).thenReturn(a);
+
+ lur.fishAll(isA(Principal.class), (List<Permission>)isA(List.class));
+
+ EpiLur lur1 = new EpiLur(lur);
+
+ CadiWrap wrap = new CadiWrap(request, tafResp, lur1);
+
+ assertNull(wrap.getUserPrincipal());
+ assertNull(wrap.getRemoteUser());
+ assertNull(wrap.getUser());
+ assertEquals(wrap.getPermissions(principle).size(), 0);
+ assertTrue(wrap.access() instanceof PropAccess);
+
+ byte[] arr = {'1','2'};
+ wrap.setCred(arr);
+
+ assertEquals(arr, wrap.getCred());
+
+ wrap.setUser("User1");
+ assertEquals("User1", wrap.getUser());
+
+ wrap.invalidate("1");
+
+ assertFalse(wrap.isUserInRole(null));
+
+ wrap.set(tafResp, lur);
+
+ wrap.invalidate("2");
+
+ assertFalse(wrap.isUserInRole("User1"));
+ }
+
+ @Test
+ public void testInstantiateWithPermConverter() throws CadiException {
+ Access a = new PropAccess();
+ when(tafResp.getAccess()).thenReturn(a);
+ when(tafResp.getPrincipal()).thenReturn(principle);
+
+ // Anonymous object for testing purposes
+ CachingLur<Permission> lur1 = new CachingLur<Permission>() {
+ @Override public Permission createPerm(String p) { return null; }
+ @Override public boolean fish(Principal bait, Permission pond) { return true; }
+ @Override public void fishAll(Principal bait, List<Permission> permissions) { }
+ @Override public void destroy() { }
+ @Override public boolean handlesExclusively(Permission pond) { return false; }
+ @Override public boolean handles(Principal principal) { return false; }
+ @Override public void remove(String user) { }
+ @Override public Resp reload(User<Permission> user) { return null; }
+ @Override public void setDebug(String commaDelimIDsOrNull) { }
+ @Override public void clear(Principal p, StringBuilder sb) { }
+ };
+
+ MapPermConverter pc = new MapPermConverter();
+
+ CadiWrap wrap = new CadiWrap(request, tafResp, lur1, pc);
+
+ assertNotNull(wrap.getUserPrincipal());
+ assertNull(wrap.getRemoteUser());
+ assertNull(wrap.getUser());
+
+ byte[] arr = {'1','2'};
+ wrap.setCred(arr);
+
+ assertEquals(arr, wrap.getCred());
+
+ wrap.setUser("User1");
+ assertEquals("User1", wrap.getUser());
+
+ wrap.invalidate("1");
+ wrap.setPermConverter(new MapPermConverter());
+
+ assertTrue(wrap.getLur() instanceof CachingLur);
+ assertTrue(wrap.isUserInRole("User1"));
+
+ wrap.set(tafResp, lur);
+ assertFalse(wrap.isUserInRole("Perm1"));
+ }
+}
diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/config/JU_Get.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/config/JU_Get.java new file mode 100644 index 00000000..5f89060e --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/config/JU_Get.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * * org.onap.aaf + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.aaf.cadi.test.config; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.config.Get; + +public class JU_Get { + + private String defaultVal = "some default value"; + + private ByteArrayOutputStream outStream; + + private TestBean tb; + + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void beanTest() { + tb = new TestBean(); + tb.setProperty1("prop1"); + + Get.Bean testBean = new Get.Bean(tb); + assertThat(testBean.get("property1", defaultVal, true), is("prop1")); + assertThat(testBean.get("property2", defaultVal, true), is(defaultVal)); + assertThat(testBean.get("thrower", defaultVal, true), is(defaultVal)); + } + + @Test + public void nullTest() { + assertThat(Get.NULL.get("name", defaultVal, true), is(defaultVal)); + } + + @Test + public void accessTest() { + String output; + + PropAccess access = new PropAccess(); + access.setProperty("tag", "value"); + Get.AccessGet accessGet = new Get.AccessGet(access); + + assertThat(accessGet.get("tag", defaultVal, true), is("value")); + output = outStream.toString().split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] tag is set to value\n")); + + outStream.reset(); + + assertThat(accessGet.get("not a real tag", defaultVal, true), is(defaultVal)); + output = outStream.toString().split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] not a real tag is set to " + defaultVal + "\n")); + + outStream.reset(); + + assertThat(accessGet.get("not a real tag", null, true), is(nullValue())); + output = outStream.toString().split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] not a real tag is not set\n")); + + outStream.reset(); + + assertThat(accessGet.get("tag", defaultVal, false), is("value")); + assertThat(outStream.toString(), is("")); + } + + public class TestBean implements java.io.Serializable { + + private static final long serialVersionUID = 1L; + private String property1 = null; + private String property2 = null; + @SuppressWarnings("unused") + private String thrower = null; + + public TestBean() { } + public String getProperty1() { return property1; } + public void setProperty1(final String value) { this.property1 = value; } + public String getProperty2() { return property2; } + public void setProperty2(final String value) { this.property2 = value; } + public String getThrower() throws Exception { throw new Exception(); } + public void setThrower(final String value) { this.thrower = value; } + + } +} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/config/JU_GetAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/config/JU_GetAccess.java new file mode 100644 index 00000000..5acd39f9 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/config/JU_GetAccess.java @@ -0,0 +1,107 @@ +/******************************************************************************* + * * org.onap.aaf + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.aaf.cadi.test.config; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; + +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.config.Get; +import org.onap.aaf.cadi.config.GetAccess; + +public class JU_GetAccess { + + private String defaultVal = "some default value"; + + private ByteArrayOutputStream outStream; + + private PropAccess access; + private Get.AccessGet accessGet; + private File file; + private String filePath; + + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + + file = File.createTempFile("GetAccess_test", ""); + filePath = file.getAbsolutePath(); + + access = new PropAccess(); + access.setProperty("cadi_prop_files", filePath); + accessGet = new Get.AccessGet(access); + + } + + @After + public void tearDown() { + System.setOut(System.out); + + file.delete(); + } + + @Test + public void constructorTest() { + String output; + + @SuppressWarnings("unused") + GetAccess getAccess = new GetAccess(accessGet); + String[] lines = outStream.toString().split("\n"); + assertThat(lines.length, is(2)); + output = lines[0].split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] cadi_prop_files is set to " + filePath)); + output = lines[1].split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] Loading CADI Properties from " + filePath)); + } + + @Test + public void getPropertyTest1() { + GetAccess getAccess = new GetAccess(accessGet); + + getAccess.setProperty("tag", "value"); + assertThat(getAccess.getProperty("tag", defaultVal), is("value")); + assertThat(getAccess.getProperty("not_a_tag", defaultVal), is(defaultVal)); + } + + @Test + public void getPropertyTest2() { + GetAccess getAccess = new GetAccess(accessGet); + + getAccess.setProperty("tag", "value"); + assertThat(getAccess.getProperty("tag"), is("value")); + assertThat(getAccess.getProperty("not_a_tag"), is(nullValue())); + } + + @Test + public void getTest() { + GetAccess getAccess = new GetAccess(accessGet); + assertThat((Get.AccessGet)getAccess.get(), is(accessGet)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_Chmod.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_Chmod.java new file mode 100644 index 00000000..215980ff --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_Chmod.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * * org.onap.aaf + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ +package org.onap.aaf.cadi.test.util; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.aaf.cadi.util.Chmod; + +public class JU_Chmod { + + private File file; + private String filePath; + + @Before + public void setup() throws IOException { + file = File.createTempFile("chmod_test", ""); + filePath = file.getAbsolutePath(); + } + + @After + public void tearDown() { + file.delete(); + } + + @Test + public void to755Test() throws IOException { + Chmod.to755.chmod(file); + Set<PosixFilePermission> set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("rwxr-xr-x")); + } + + @Test + public void to644Test() throws IOException { + Chmod.to644.chmod(file); + Set<PosixFilePermission> set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("rw-r--r--")); + } + + @Test + public void to400Test() throws IOException { + Chmod.to400.chmod(file); + Set<PosixFilePermission> set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("r--------")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_Pool.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_Pool.java new file mode 100644 index 00000000..f4703bb8 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_Pool.java @@ -0,0 +1,144 @@ +/******************************************************************************* + * * org.onap.aaf + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ +package org.onap.aaf.cadi.test.util; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.util.Pool; +import org.onap.aaf.cadi.util.Pool.*; + +public class JU_Pool { + + private StringBuilder sb = new StringBuilder(); + + private class IntegerCreator implements Creator<Integer> { + private int current = 0; + @Override public Integer create() { return current++; } + @Override public void destroy(Integer t) { t = 0; } + @Override public boolean isValid(Integer t) { return (t & 0x1) == 0; } + @Override public void reuse(Integer t) { } + } + + private class CustomLogger implements Log { + @Override + public void log(Object ... o) { + for (Object item : o) { + sb.append(item.toString()); + } + } + } + + @Test + public void getTest() throws CadiException { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + + List<Pooled<Integer>> gotten = new ArrayList<Pooled<Integer>>(); + for (int i = 0; i < 10; i++) { + gotten.add(intPool.get()); + assertThat(gotten.get(i).content, is(i)); + } + + gotten.get(9).done(); + gotten.set(9, intPool.get()); + assertThat(gotten.get(9).content, is(9)); + + for (int i = 0; i < 10; i++) { + gotten.get(i).done(); + } + + for (int i = 0; i < 10; i++) { + gotten.set(i, intPool.get()); + if (i < 5) { + assertThat(gotten.get(i).content, is(i)); + } else { + assertThat(gotten.get(i).content, is(i + 5)); + } + } + + for (int i = 0; i < 10; i++) { + gotten.get(i).toss(); + // Coverage calls + gotten.get(i).toss(); + gotten.get(i).done(); + + // only set some objects to null -> this is for the finalize coverage test + if (i < 5) { + gotten.set(i, null); + } + } + + // Coverage of finalize() + System.gc(); + } + + @Test + public void bulkTest() throws CadiException { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + + intPool.prime(10); + // Remove all of the invalid items (in this case, odd numbers) + assertFalse(intPool.validate()); + + // Make sure we got them all + assertTrue(intPool.validate()); + + // Get an item from the pool + Pooled<Integer> gotten = intPool.get(); + assertThat(gotten.content, is(0)); + + // finalize that item, then check the next one to make sure we actually purged the odd numbers + gotten = intPool.get(); + assertThat(gotten.content, is(2)); + + intPool.drain(); + + } + + + @Test + public void setMaxTest() { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + intPool.setMaxRange(10); + assertThat(intPool.getMaxRange(), is(10)); + intPool.setMaxRange(-10); + assertThat(intPool.getMaxRange(), is(0)); + } + + @Test + public void loggingTest() { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + + // Log to Log.NULL for coverage + intPool.log("Test log output"); + + intPool.setLogger(new CustomLogger()); + intPool.log("Test log output"); + + assertThat(sb.toString(), is("Test log output")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_SubStandardConsole.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_SubStandardConsole.java new file mode 100644 index 00000000..9e6a175c --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/util/JU_SubStandardConsole.java @@ -0,0 +1,124 @@ +/******************************************************************************* + * * org.onap.aaf + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ +package org.onap.aaf.cadi.test.util; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.reflect.Field; + +import org.onap.aaf.cadi.util.SubStandardConsole; + +public class JU_SubStandardConsole { + + private String inputString = "An input string"; + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + System.setErr(System.err); + } + + @Test + public void readLineTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s\n", ">>> "); + assertThat(output, is(inputString)); + assertThat(outStream.toString(), is(">>> \n")); + } + + @Test + public void readLineTest2() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s %s\n", ">>> ", "Another argument for coverage"); + assertThat(output, is(inputString)); + } + + @Test + public void readLineTest3() { + byte[] input = "\n".getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s\n", ">>> "); + assertThat(output, is(">>> ")); + assertThat(outStream.toString(), is(">>> \n")); + } + + @Test + public void readPasswordTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + char[] output = ssc.readPassword("%s\n", ">>> "); + System.out.println(output); + assertThat(output, is(inputString.toCharArray())); + assertThat(outStream.toString(), is(">>> \nAn input string\n")); + } + + @Test + public void printfTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + ssc.printf("%s", "A format specifier"); + assertThat(outStream.toString(), is("A format specifier")); + } + + @Test + public void throwsTest() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + BufferedReader brMock = mock(BufferedReader.class); + when(brMock.readLine()).thenThrow(new IOException()); + + SubStandardConsole ssc = new SubStandardConsole(); + + Field brField = SubStandardConsole.class.getDeclaredField("br"); + brField.setAccessible(true); + brField.set(ssc, brMock); + + assertThat(ssc.readLine(""), is("")); + assertThat(errStream.toString(), is("uh oh...\n")); + errStream.reset(); + assertThat(ssc.readPassword("").length, is(0)); + assertThat(errStream.toString(), is("uh oh...\n")); + } + +} |