diff options
author | Instrumental <jonathan.gathman@att.com> | 2018-09-07 12:21:34 -0500 |
---|---|---|
committer | Instrumental <jonathan.gathman@att.com> | 2018-09-07 12:22:50 -0500 |
commit | 4b5a7d721d994a49057e9bfb403c7bff1b376660 (patch) | |
tree | a36d03227b63a3e60346d6c3ca87b061087dae85 /cadi/core/src/test/java | |
parent | 824dc7b5fc0e1ccdf7f460479aff344727f0f01e (diff) |
Mass removal of all Tabs (Style Warnings)
Issue-ID: AAF-473
Change-Id: Iaf0ef8120882937959bb0065f2f6ba74a021940f
Signed-off-by: Instrumental <jonathan.gathman@att.com>
Diffstat (limited to 'cadi/core/src/test/java')
68 files changed, 4571 insertions, 4571 deletions
diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java index eaa3376d..982a29e5 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_Get.java @@ -33,84 +33,84 @@ import org.onap.aaf.cadi.config.Get; public class JU_Get { - private String defaultVal = "some default value"; + private String defaultVal = "some default value"; - private ByteArrayOutputStream outStream; + private ByteArrayOutputStream outStream; - private TestBean tb; + private TestBean tb; - @Before - public void setup() { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - } + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } - @After - public void tearDown() { - System.setOut(System.out); - } + @After + public void tearDown() { + System.setOut(System.out); + } - @Test - public void beanTest() { - tb = new TestBean(); - tb.setProperty1("prop1"); + @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)); - } + 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 nullTest() { + assertThat(Get.NULL.get("name", defaultVal, true), is(defaultVal)); + } - @Test - public void accessTest() { - String output; + @Test + public void accessTest() { + String output; - PropAccess access = new PropAccess(); - access.setProperty("tag", "value"); - Get.AccessGet accessGet = new Get.AccessGet(access); + 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" + System.lineSeparator())); + assertThat(accessGet.get("tag", defaultVal, true), is("value")); + output = outStream.toString().split(" ", 2)[1]; + assertThat(output, is("INIT [cadi] tag is set to value" + System.lineSeparator())); - outStream.reset(); + 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 + System.lineSeparator())); + 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 + System.lineSeparator())); - outStream.reset(); + 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" + System.lineSeparator())); + 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" + System.lineSeparator())); - outStream.reset(); + outStream.reset(); - assertThat(accessGet.get("tag", defaultVal, false), is("value")); - assertThat(outStream.toString(), is("")); - } + assertThat(accessGet.get("tag", defaultVal, false), is("value")); + assertThat(outStream.toString(), is("")); + } - public class TestBean implements java.io.Serializable { + 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; + 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; } + 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/config/test/JU_GetAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_GetAccess.java index d50f9e8c..568a820c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_GetAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_GetAccess.java @@ -36,72 +36,72 @@ import org.onap.aaf.cadi.config.GetAccess; public class JU_GetAccess { - private String defaultVal = "some default value"; + private String defaultVal = "some default value"; - private ByteArrayOutputStream outStream; + private ByteArrayOutputStream outStream; - private PropAccess access; - private Get.AccessGet accessGet; - private File file; - private String filePath; + 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)); + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); - file = File.createTempFile("GetAccess_test", ""); - filePath = file.getAbsolutePath(); + file = File.createTempFile("GetAccess_test", ""); + filePath = file.getAbsolutePath(); - access = new PropAccess(); + access = new PropAccess(); access.setProperty("cadi_prop_files", filePath); - accessGet = new Get.AccessGet(access); + accessGet = new Get.AccessGet(access); - } + } - @After - public void tearDown() { - System.setOut(System.out); + @After + public void tearDown() { + System.setOut(System.out); - file.delete(); - } + file.delete(); + } @Test public void constructorTest() { String output; @SuppressWarnings("unused") - GetAccess getAccess = new GetAccess(accessGet); - String[] lines = outStream.toString().split(System.lineSeparator()); - assertThat(lines.length, is(2)); + GetAccess getAccess = new GetAccess(accessGet); + String[] lines = outStream.toString().split(System.lineSeparator()); + 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]; + 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)); - } + 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())); - } + getAccess.setProperty("tag", "value"); + assertThat(getAccess.getProperty("tag"), is("value")); + assertThat(getAccess.getProperty("not_a_tag"), is(nullValue())); + } - @Test - public void getTest() { + @Test + public void getTest() { GetAccess getAccess = new GetAccess(accessGet); - assertThat((Get.AccessGet)getAccess.get(), is(accessGet)); - } + assertThat((Get.AccessGet)getAccess.get(), is(accessGet)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java index 6510bdcd..3fbae769 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MultiGet.java @@ -35,34 +35,34 @@ import org.onap.aaf.cadi.config.MultiGet; public class JU_MultiGet { - private String defaultVal = "some default value"; + private String defaultVal = "some default value"; - private ByteArrayOutputStream outStream; + private ByteArrayOutputStream outStream; - private MultiGet multiGet; - private Get.AccessGet accessGet; - private PropAccess access; + private MultiGet multiGet; + private Get.AccessGet accessGet; + private PropAccess access; - @Before - public void setup() throws IOException { - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); - access = new PropAccess(); - access.setProperty("tag", "value"); - accessGet = new Get.AccessGet(access); - multiGet = new MultiGet(accessGet, Get.NULL); - } + access = new PropAccess(); + access.setProperty("tag", "value"); + accessGet = new Get.AccessGet(access); + multiGet = new MultiGet(accessGet, Get.NULL); + } - @After - public void tearDown() { - System.setOut(System.out); - } + @After + public void tearDown() { + System.setOut(System.out); + } @Test public void getTest() { - assertThat(multiGet.get("tag", defaultVal, false), is("value")); - assertThat(multiGet.get("not_a_tag", defaultVal, false), is(defaultVal)); - } + assertThat(multiGet.get("tag", defaultVal, false), is("value")); + assertThat(multiGet.get("not_a_tag", defaultVal, false), is(defaultVal)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java index 001d0fe6..98c1a292 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java @@ -45,92 +45,92 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.config.SecurityInfo; public class JU_SecurityInfo { - - private static PropAccess access; - - private static final String keyStoreFileName = "src/test/resources/keystore.p12"; - private static final String keyStorePassword = "Password for the keystore"; - private static final String keyPassword = "Password for the key"; - - private static final String trustStoreFileName = "src/test/resources/truststore.jks"; - private static final String trustStorePasswd = "Password for the truststore"; - - @BeforeClass - public static void setupOnce() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - keyStore.load(null, null); - keyStore.store(new FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray()); - - KeyStore trustStore = KeyStore.getInstance("JKS"); - trustStore.load(null, null); - trustStore.store(new FileOutputStream(trustStoreFileName), trustStorePasswd.toCharArray()); - } - - @Before - public void setup() throws IOException { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - - access.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); - access.setProperty(Config.CADI_KEYSTORE_PASSWORD, access.encrypt(keyStorePassword)); - access.setProperty(Config.CADI_KEY_PASSWORD, access.encrypt(keyPassword)); - - access.setProperty(Config.CADI_TRUSTSTORE, trustStoreFileName); - access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, access.encrypt(trustStorePasswd)); - } - - @AfterClass - public static void tearDownOnce() { - File keyStoreFile = new File(keyStoreFileName); - if (keyStoreFile.exists()) { - keyStoreFile.delete(); - } - File trustStoreFile = new File(trustStoreFileName); - if (trustStoreFile.exists()) { - trustStoreFile.delete(); - } - } - - @Test - public void test() throws CadiException { - SecurityInfo si = new SecurityInfo(access); - - assertNotNull(si.getSSLSocketFactory()); - assertNotNull(si.getSSLContext()); - assertNotNull(si.getKeyManagers()); - - access.setProperty(Config.CADI_TRUST_MASKS, "123.123.123.123"); - si = new SecurityInfo(access); - } - - @Test(expected = CadiException.class) - public void nullkeyStoreTest() throws CadiException { - access.setProperty(Config.CADI_KEYSTORE, "passwords.txt"); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(access); - } - - @Test(expected = CadiException.class) - public void nullTrustStoreTest() throws CadiException { - access.setProperty(Config.CADI_TRUSTSTORE, "passwords.txt"); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(access); - } - - - @Test(expected = NumberFormatException.class) - public void badTrustMaskTest() throws CadiException { - access.setProperty(Config.CADI_TRUST_MASKS, "trustMask"); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(access); - } - - @Test - public void coverageTest() throws CadiException { - PropAccess badAccess = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - @SuppressWarnings("unused") - SecurityInfo si = new SecurityInfo(badAccess); - badAccess.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); - si = new SecurityInfo(badAccess); - } + + private static PropAccess access; + + private static final String keyStoreFileName = "src/test/resources/keystore.p12"; + private static final String keyStorePassword = "Password for the keystore"; + private static final String keyPassword = "Password for the key"; + + private static final String trustStoreFileName = "src/test/resources/truststore.jks"; + private static final String trustStorePasswd = "Password for the truststore"; + + @BeforeClass + public static void setupOnce() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(null, null); + keyStore.store(new FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray()); + + KeyStore trustStore = KeyStore.getInstance("JKS"); + trustStore.load(null, null); + trustStore.store(new FileOutputStream(trustStoreFileName), trustStorePasswd.toCharArray()); + } + + @Before + public void setup() throws IOException { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + + access.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); + access.setProperty(Config.CADI_KEYSTORE_PASSWORD, access.encrypt(keyStorePassword)); + access.setProperty(Config.CADI_KEY_PASSWORD, access.encrypt(keyPassword)); + + access.setProperty(Config.CADI_TRUSTSTORE, trustStoreFileName); + access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, access.encrypt(trustStorePasswd)); + } + + @AfterClass + public static void tearDownOnce() { + File keyStoreFile = new File(keyStoreFileName); + if (keyStoreFile.exists()) { + keyStoreFile.delete(); + } + File trustStoreFile = new File(trustStoreFileName); + if (trustStoreFile.exists()) { + trustStoreFile.delete(); + } + } + + @Test + public void test() throws CadiException { + SecurityInfo si = new SecurityInfo(access); + + assertNotNull(si.getSSLSocketFactory()); + assertNotNull(si.getSSLContext()); + assertNotNull(si.getKeyManagers()); + + access.setProperty(Config.CADI_TRUST_MASKS, "123.123.123.123"); + si = new SecurityInfo(access); + } + + @Test(expected = CadiException.class) + public void nullkeyStoreTest() throws CadiException { + access.setProperty(Config.CADI_KEYSTORE, "passwords.txt"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + @Test(expected = CadiException.class) + public void nullTrustStoreTest() throws CadiException { + access.setProperty(Config.CADI_TRUSTSTORE, "passwords.txt"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + + @Test(expected = NumberFormatException.class) + public void badTrustMaskTest() throws CadiException { + access.setProperty(Config.CADI_TRUST_MASKS, "trustMask"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + @Test + public void coverageTest() throws CadiException { + PropAccess badAccess = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(badAccess); + badAccess.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); + si = new SecurityInfo(badAccess); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java index 111f8769..735edef9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfoC.java @@ -39,71 +39,71 @@ import org.onap.aaf.cadi.config.SecurityInfoC; public class JU_SecurityInfoC { - ByteArrayOutputStream outStream; - ByteArrayOutputStream errStream; + ByteArrayOutputStream outStream; + ByteArrayOutputStream errStream; - @Before - public void setup() { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - } + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + } - @After - public void tearDown() { - System.setOut(System.out); - System.setErr(System.err); - } + @After + public void tearDown() { + System.setOut(System.out); + System.setErr(System.err); + } -// @Test -// public void instanceTest() throws CadiException, MalformedURLException { -// SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class ); -// assertThat(si.defSS.getID(), is(SecurityInfoC.DEF_ID)); -// try { -// si.defSS.setSecurity(new HttpURLConnectionStub()); -// fail("Should have thrown an exception"); -// } catch (CadiException e) { -// assertTrue(e instanceof CadiException); -// assertThat(e.getMessage(), is("No Client Credentials set.")); -// } -// assertThat(si.defSS.setLastResponse(0), is(0)); +// @Test +// public void instanceTest() throws CadiException, MalformedURLException { +// SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class ); +// assertThat(si.defSS.getID(), is(SecurityInfoC.DEF_ID)); +// try { +// si.defSS.setSecurity(new HttpURLConnectionStub()); +// fail("Should have thrown an exception"); +// } catch (CadiException e) { +// assertTrue(e instanceof CadiException); +// assertThat(e.getMessage(), is("No Client Credentials set.")); +// } +// assertThat(si.defSS.setLastResponse(0), is(0)); // -// // Try it again for coverage -// SecurityInfoC<HttpURLConnection> siClone = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class); -// assertThat(siClone, is(si)); -// } - - @Test - public void setTest() throws MalformedURLException, CadiException { - SecurityInfoC<HttpURLConnectionStub> si = SecurityInfoC.instance(new PropAccess(), HttpURLConnectionStub.class); - SecuritySetter<HttpURLConnectionStub> ss = new SecuritySetterStub<HttpURLConnectionStub>(); - assertThat(si.set(ss), is(si)); - assertThat(si.defSS.getID(), is("Example ID")); - try { - si.defSS.setSecurity(new HttpURLConnectionStub()); - fail("Should have thrown an exception"); - } catch (CadiException e) { - assertTrue(e instanceof CadiException); - assertThat(e.getMessage(), is("Example exception")); - } - assertThat(si.defSS.setLastResponse(0), is(0)); - assertThat(si.defSS.setLastResponse(1), is(1)); - assertThat(si.defSS.setLastResponse(-1), is(-1)); - } +// // Try it again for coverage +// SecurityInfoC<HttpURLConnection> siClone = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class); +// assertThat(siClone, is(si)); +// } + + @Test + public void setTest() throws MalformedURLException, CadiException { + SecurityInfoC<HttpURLConnectionStub> si = SecurityInfoC.instance(new PropAccess(), HttpURLConnectionStub.class); + SecuritySetter<HttpURLConnectionStub> ss = new SecuritySetterStub<HttpURLConnectionStub>(); + assertThat(si.set(ss), is(si)); + assertThat(si.defSS.getID(), is("Example ID")); + try { + si.defSS.setSecurity(new HttpURLConnectionStub()); + fail("Should have thrown an exception"); + } catch (CadiException e) { + assertTrue(e instanceof CadiException); + assertThat(e.getMessage(), is("Example exception")); + } + assertThat(si.defSS.setLastResponse(0), is(0)); + assertThat(si.defSS.setLastResponse(1), is(1)); + assertThat(si.defSS.setLastResponse(-1), is(-1)); + } - public static class HttpURLConnectionStub extends HttpURLConnection { - public HttpURLConnectionStub() throws MalformedURLException { super(new URL("http://www.example.com")); } - @Override public void disconnect() { } - @Override public boolean usingProxy() { return false; } - @Override public void connect() throws IOException { } - } + public static class HttpURLConnectionStub extends HttpURLConnection { + public HttpURLConnectionStub() throws MalformedURLException { super(new URL("http://www.example.com")); } + @Override public void disconnect() { } + @Override public boolean usingProxy() { return false; } + @Override public void connect() throws IOException { } + } - private class SecuritySetterStub<CT> implements SecuritySetter<CT> { - public String getID() { return "Example ID"; } - public void setSecurity(CT client) throws CadiException { throw new CadiException("Example exception"); } - public int setLastResponse(int respCode) { return respCode; } - } + private class SecuritySetterStub<CT> implements SecuritySetter<CT> { + public String getID() { return "Example ID"; } + public void setSecurity(CT client) throws CadiException { throw new CadiException("Example exception"); } + public int setLastResponse(int respCode) { return respCode; } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java index 7d7ca77c..86a12ca0 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java @@ -43,103 +43,103 @@ import org.onap.aaf.cadi.util.Split; public class JU_UsersDump { - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream stdoutSuppressor; - - private static final String expected = "<?xml version='1.0' encoding='utf-8'?>\n" + - "<!--\n" + - " Code Generated Tomcat Users and Roles from AT&T LUR on ...\n" + - "-->\n" + - "<tomcat-users>\n" + - " <role rolename=\"suser\"/>\n" + - " <role rolename=\"admin\"/>\n" + - " <role rolename=\"groupB\"/>\n" + - " <role rolename=\"groupA\"/>\n" + - " \n" + - " <user username=\"yourname@none\" roles=\"admin\"/>\n" + - " <user username=\"m1234@none\" roles=\"suser\"/>\n" + - " <user username=\"hisname@none\" roles=\"suser\"/>\n" + - " <user username=\"hername@none\" roles=\"suser\"/>\n" + - " <user username=\"myname\" roles=\"groupB,groupA\"/>\n" + - " <user username=\"myname@none\" roles=\"admin\"/>\n" + - "</tomcat-users>\n"; - - private final static String groups = "myname:groupA,groupB"; - private final static String names = "admin:myname,yourname;suser:hisname,hername,m1234"; - - private AbsUserCache<LocalPermission> lur; - - @Before - public void setup() throws IOException { - outStream = new ByteArrayOutputStream(); - stdoutSuppressor = new ByteArrayOutputStream(); - - System.setOut(new PrintStream(stdoutSuppressor)); - - lur = new LocalLur(new PropAccess(), groups, names); - } - - @After - public void tearDown() { - System.setOut(System.out); - } - - @Test - public void writeTest() throws IOException { - UsersDump.write(outStream, lur); - String[] actualLines = Split.splitTrim('\n', outStream.toString()); - String[] expectedLines = Split.splitTrim('\n', expected); - for (String s : actualLines) { - System.out.println(s); - } - - assertThat(actualLines.length, is(expectedLines.length)); - - // Check that the output starts with an XML tag - assertThat(actualLines[0], is(expectedLines[0])); - // Check that lines 2-4 are a comment - assertThat(actualLines[1], is(expectedLines[1])); - assertThat(actualLines[3], is(expectedLines[3])); - - // Check that the rest of the output matches the expected output - for (int i = 4; i < actualLines.length; i++) { - assertThat(actualLines[i], is(expectedLines[i])); - } - - // Run the test again with outStream as a PrintStream (for coverage) - outStream.reset(); - UsersDump.write(new PrintStream(outStream), lur); - actualLines = Split.splitTrim('\n', outStream.toString()); - - assertThat(actualLines.length, is(expectedLines.length)); - - // Check that the output starts with an XML tag - assertThat(actualLines[0], is(expectedLines[0])); - // Check that lines 2-4 are a comment - assertThat(actualLines[1], is(expectedLines[1])); - assertThat(actualLines[3], is(expectedLines[3])); - - // Check that the rest of the output matches the expected output - for (int i = 4; i < actualLines.length; i++) { - assertThat(actualLines[i], is(expectedLines[i])); - } - } - - @Test - public void updateUsersTest() { - String output; - File outputFile = new File("src/test/resources/userdump.xml"); - assertThat(outputFile.exists(), is(false)); - - output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); - assertThat(output, is(nullValue())); - assertThat(outputFile.exists(), is(true)); - - output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); - assertThat(output, is(nullValue())); - assertThat(outputFile.exists(), is(true)); - - outputFile.delete(); - } + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream stdoutSuppressor; + + private static final String expected = "<?xml version='1.0' encoding='utf-8'?>\n" + + "<!--\n" + + " Code Generated Tomcat Users and Roles from AT&T LUR on ...\n" + + "-->\n" + + "<tomcat-users>\n" + + " <role rolename=\"suser\"/>\n" + + " <role rolename=\"admin\"/>\n" + + " <role rolename=\"groupB\"/>\n" + + " <role rolename=\"groupA\"/>\n" + + " \n" + + " <user username=\"yourname@none\" roles=\"admin\"/>\n" + + " <user username=\"m1234@none\" roles=\"suser\"/>\n" + + " <user username=\"hisname@none\" roles=\"suser\"/>\n" + + " <user username=\"hername@none\" roles=\"suser\"/>\n" + + " <user username=\"myname\" roles=\"groupB,groupA\"/>\n" + + " <user username=\"myname@none\" roles=\"admin\"/>\n" + + "</tomcat-users>\n"; + + private final static String groups = "myname:groupA,groupB"; + private final static String names = "admin:myname,yourname;suser:hisname,hername,m1234"; + + private AbsUserCache<LocalPermission> lur; + + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + stdoutSuppressor = new ByteArrayOutputStream(); + + System.setOut(new PrintStream(stdoutSuppressor)); + + lur = new LocalLur(new PropAccess(), groups, names); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void writeTest() throws IOException { + UsersDump.write(outStream, lur); + String[] actualLines = Split.splitTrim('\n', outStream.toString()); + String[] expectedLines = Split.splitTrim('\n', expected); + for (String s : actualLines) { + System.out.println(s); + } + + assertThat(actualLines.length, is(expectedLines.length)); + + // Check that the output starts with an XML tag + assertThat(actualLines[0], is(expectedLines[0])); + // Check that lines 2-4 are a comment + assertThat(actualLines[1], is(expectedLines[1])); + assertThat(actualLines[3], is(expectedLines[3])); + + // Check that the rest of the output matches the expected output + for (int i = 4; i < actualLines.length; i++) { + assertThat(actualLines[i], is(expectedLines[i])); + } + + // Run the test again with outStream as a PrintStream (for coverage) + outStream.reset(); + UsersDump.write(new PrintStream(outStream), lur); + actualLines = Split.splitTrim('\n', outStream.toString()); + + assertThat(actualLines.length, is(expectedLines.length)); + + // Check that the output starts with an XML tag + assertThat(actualLines[0], is(expectedLines[0])); + // Check that lines 2-4 are a comment + assertThat(actualLines[1], is(expectedLines[1])); + assertThat(actualLines[3], is(expectedLines[3])); + + // Check that the rest of the output matches the expected output + for (int i = 4; i < actualLines.length; i++) { + assertThat(actualLines[i], is(expectedLines[i])); + } + } + + @Test + public void updateUsersTest() { + String output; + File outputFile = new File("src/test/resources/userdump.xml"); + assertThat(outputFile.exists(), is(false)); + + output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); + assertThat(output, is(nullValue())); + assertThat(outputFile.exists(), is(true)); + + output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); + assertThat(output, is(nullValue())); + assertThat(outputFile.exists(), is(true)); + + outputFile.delete(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java index 6daa2720..f57bb93e 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java @@ -44,64 +44,64 @@ import javax.servlet.http.HttpServletResponse; public class JU_AUTHZServlet { - @Mock private Servlet servletMock; - @Mock private ServletConfig servletConfigMock; - @Mock private HttpServletRequest reqMock; - @Mock private HttpServletResponse respMock; - @Mock private ServletRequestWrapper servletWrapperMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test() throws ServletException, IOException { - AUTHZServletStub servlet = new AUTHZServletStub(Servlet.class); - - try { - servlet.init(servletConfigMock); - fail("Should've thrown an exception"); - } catch (ServletException e) { - assertThat(e.getMessage(), is("Invalid Servlet Delegate")); - } - - setPrivateField(AUTHZServlet.class, "delegate", servlet, servletMock); - servlet.init(servletConfigMock); - servlet.getServletConfig(); - servlet.getServletInfo(); - - servlet.service(reqMock, respMock); - - String[] roles = new String[] {"role1", "role2"}; - setPrivateField(AUTHZServlet.class, "roles", servlet, roles); - servlet.service(reqMock, respMock); - - when(reqMock.isUserInRole("role1")).thenReturn(true); - servlet.service(reqMock, respMock); - - try { - servlet.service(servletWrapperMock, respMock); - fail("Should've thrown an exception"); - } catch (ServletException e) { - assertThat(e.getMessage(), is("JASPIServlet only supports HTTPServletRequest/HttpServletResponse")); - } - servlet.destroy(); - } - - private class AUTHZServletStub extends AUTHZServlet<Servlet> { - public AUTHZServletStub(Class<Servlet> cls) { super(cls); } - } - - private void setPrivateField(Class<?> clazz, String fieldName, Object target, Object value) { - try { - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(target, value); - field.setAccessible(false); - } catch(Exception e) { - System.err.println("Could not set field [" + fieldName + "] to " + value); - } - } + @Mock private Servlet servletMock; + @Mock private ServletConfig servletConfigMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private ServletRequestWrapper servletWrapperMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws ServletException, IOException { + AUTHZServletStub servlet = new AUTHZServletStub(Servlet.class); + + try { + servlet.init(servletConfigMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("Invalid Servlet Delegate")); + } + + setPrivateField(AUTHZServlet.class, "delegate", servlet, servletMock); + servlet.init(servletConfigMock); + servlet.getServletConfig(); + servlet.getServletInfo(); + + servlet.service(reqMock, respMock); + + String[] roles = new String[] {"role1", "role2"}; + setPrivateField(AUTHZServlet.class, "roles", servlet, roles); + servlet.service(reqMock, respMock); + + when(reqMock.isUserInRole("role1")).thenReturn(true); + servlet.service(reqMock, respMock); + + try { + servlet.service(servletWrapperMock, respMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("JASPIServlet only supports HTTPServletRequest/HttpServletResponse")); + } + servlet.destroy(); + } + + private class AUTHZServletStub extends AUTHZServlet<Servlet> { + public AUTHZServletStub(Class<Servlet> cls) { super(cls); } + } + + private void setPrivateField(Class<?> clazz, String fieldName, Object target, Object value) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(target, value); + field.setAccessible(false); + } catch(Exception e) { + System.err.println("Could not set field [" + fieldName + "] to " + value); + } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java index b53a9ea9..d3b28dc4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java @@ -34,21 +34,21 @@ import org.onap.aaf.cadi.filter.AccessGetter; public class JU_AccessGetter { - private static final String tag = "tag"; - private static final String value = "value"; - - private PropAccess access; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(tag, value); - } - - @Test - public void test() { - AccessGetter getter = new AccessGetter(access); - assertThat(getter.get(tag, null, false), is(value)); - } + private static final String tag = "tag"; + private static final String value = "value"; + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(tag, value); + } + + @Test + public void test() { + AccessGetter getter = new AccessGetter(access); + assertThat(getter.get(tag, null, false), is(value)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java index 9fb951a2..397424a0 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java @@ -29,17 +29,17 @@ import org.onap.aaf.cadi.filter.MapPermConverter; public class JU_MapPermConverter { - private static final String tag = "tag"; - private static final String value = "value"; - private static final String nontag = "nontag"; + private static final String tag = "tag"; + private static final String value = "value"; + private static final String nontag = "nontag"; - @Test - public void test() { - MapPermConverter converter = new MapPermConverter(); - assertThat(converter.map().isEmpty(), is(true)); - converter.map().put(tag, value); - assertThat(converter.convert(tag), is(value)); - assertThat(converter.convert(nontag), is(nontag)); - } + @Test + public void test() { + MapPermConverter converter = new MapPermConverter(); + assertThat(converter.map().isEmpty(), is(true)); + converter.map().put(tag, value); + assertThat(converter.convert(tag), is(value)); + assertThat(converter.convert(nontag), is(nontag)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java index 0a6dc2d5..fd6d22e9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java @@ -29,10 +29,10 @@ import org.onap.aaf.cadi.filter.NullPermConverter; public class JU_NullPermConverter { - @Test - public void test() { - NullPermConverter converter = NullPermConverter.singleton(); - assertThat(converter.convert("test"), is("test")); - } + @Test + public void test() { + NullPermConverter converter = NullPermConverter.singleton(); + assertThat(converter.convert("test"), is("test")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java index a36dd462..78b0fbc6 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java @@ -48,58 +48,58 @@ import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.filter.PathFilter; public class JU_PathFilter { - - private PropAccess access; - - @Mock private FilterConfig filterConfigMock; - @Mock private ServletContext contextMock; - @Mock private HttpServletRequest reqMock; - @Mock private HttpServletResponse respMock; - @Mock private FilterChain chainMock; - @Mock private Principal princMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(filterConfigMock.getServletContext()).thenReturn(contextMock); - when(reqMock.getUserPrincipal()).thenReturn(princMock); - when(princMock.getName()).thenReturn("name"); + + private PropAccess access; + + @Mock private FilterConfig filterConfigMock; + @Mock private ServletContext contextMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private FilterChain chainMock; + @Mock private Principal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(filterConfigMock.getServletContext()).thenReturn(contextMock); + when(reqMock.getUserPrincipal()).thenReturn(princMock); + when(princMock.getName()).thenReturn("name"); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } - @Test - public void test() throws ServletException, IOException { - PathFilter pathFilter = new PathFilter(access); - try { - pathFilter.init(filterConfigMock); - fail("Should've thrown an exception"); - } catch (ServletException e) { - assertThat(e.getMessage(), is("PathFilter - pathfilter_ns is not set")); - } - - when(contextMock.getAttribute(Config.PATHFILTER_NS)).thenReturn(5); - when(contextMock.getAttribute(Config.PATHFILTER_STACK)).thenReturn(5); - when(contextMock.getAttribute(Config.PATHFILTER_URLPATTERN)).thenReturn(5); - when(contextMock.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG)).thenReturn(5); - pathFilter.init(filterConfigMock); - - pathFilter.doFilter(reqMock, respMock, chainMock); + @Test + public void test() throws ServletException, IOException { + PathFilter pathFilter = new PathFilter(access); + try { + pathFilter.init(filterConfigMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("PathFilter - pathfilter_ns is not set")); + } + + when(contextMock.getAttribute(Config.PATHFILTER_NS)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_STACK)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_URLPATTERN)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG)).thenReturn(5); + pathFilter.init(filterConfigMock); + + pathFilter.doFilter(reqMock, respMock, chainMock); - when(reqMock.isUserInRole(anyString())).thenReturn(true); - pathFilter.doFilter(reqMock, respMock, chainMock); - - pathFilter.destroy(); + when(reqMock.isUserInRole(anyString())).thenReturn(true); + pathFilter.doFilter(reqMock, respMock, chainMock); + + pathFilter.destroy(); - pathFilter = new PathFilter(); - pathFilter.init(filterConfigMock); - - pathFilter.doFilter(reqMock, respMock, chainMock); + pathFilter = new PathFilter(); + pathFilter.init(filterConfigMock); + + pathFilter.doFilter(reqMock, respMock, chainMock); - when(reqMock.isUserInRole(anyString())).thenReturn(false); - pathFilter.doFilter(reqMock, respMock, chainMock); - - pathFilter.destroy(); - } + when(reqMock.isUserInRole(anyString())).thenReturn(false); + pathFilter.doFilter(reqMock, respMock, chainMock); + + pathFilter.destroy(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java index 9853f88e..88301a6c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_ConfigPrincipal.java @@ -32,48 +32,48 @@ import org.onap.aaf.cadi.lur.ConfigPrincipal; public class JU_ConfigPrincipal { - private final String name = "User"; - private final String pass = "pass"; + private final String name = "User"; + private final String pass = "pass"; - // Expected output of base64("User:pass") - private final String b64encoded = "VXNlcjpwYXNz"; + // Expected output of base64("User:pass") + private final String b64encoded = "VXNlcjpwYXNz"; - private Field content_field; - - @Before - public void setup() throws NoSuchFieldException { - content_field = ConfigPrincipal.class.getDeclaredField("content"); - content_field.setAccessible(true); - } + private Field content_field; + + @Before + public void setup() throws NoSuchFieldException { + content_field = ConfigPrincipal.class.getDeclaredField("content"); + content_field.setAccessible(true); + } - @Test - public void testConfigPrincipalStringString() throws IOException, IllegalArgumentException, IllegalAccessException { - ConfigPrincipal p = new ConfigPrincipal(name, pass); - - assertThat(p.getName(), is(name)); - assertThat(p.toString(), is(name)); - assertThat(p.getCred(), is(pass.getBytes())); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - content_field.set(p, "pass"); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + @Test + public void testConfigPrincipalStringString() throws IOException, IllegalArgumentException, IllegalAccessException { + ConfigPrincipal p = new ConfigPrincipal(name, pass); + + assertThat(p.getName(), is(name)); + assertThat(p.toString(), is(name)); + assertThat(p.getCred(), is(pass.getBytes())); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + content_field.set(p, "pass"); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - // One more time for coverage purposes - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - } + // One more time for coverage purposes + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + } - @Test - public void testConfigPrincipalStringByteArray() throws IOException, IllegalArgumentException, IllegalAccessException { - ConfigPrincipal p = new ConfigPrincipal(name, pass.getBytes()); - - assertThat(p.getName(), is(name)); - assertThat(p.toString(), is(name)); - assertThat(p.getCred(), is(pass.getBytes())); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - content_field.set(p, "pass"); - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + @Test + public void testConfigPrincipalStringByteArray() throws IOException, IllegalArgumentException, IllegalAccessException { + ConfigPrincipal p = new ConfigPrincipal(name, pass.getBytes()); + + assertThat(p.getName(), is(name)); + assertThat(p.toString(), is(name)); + assertThat(p.getCred(), is(pass.getBytes())); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + content_field.set(p, "pass"); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - // One more time for coverage purposes - assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); - } - + // One more time for coverage purposes + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java index b99030eb..c1a43f0d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java @@ -45,84 +45,84 @@ import org.onap.aaf.cadi.lur.EpiLur; public class JU_EpiLur { - private ArrayList<Permission> perms; - private CredValStub lurMock3; + private ArrayList<Permission> perms; + private CredValStub lurMock3; - @Mock private Lur lurMock1; - @Mock private CachingLur<?> lurMock2; - @Mock private Principal princMock; - @Mock private Permission permMock; + @Mock private Lur lurMock1; + @Mock private CachingLur<?> lurMock2; + @Mock private Principal princMock; + @Mock private Permission permMock; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); - perms = new ArrayList<>(); - perms.add(permMock); + perms = new ArrayList<>(); + perms.add(permMock); - lurMock3 = new CredValStub(); - } + lurMock3 = new CredValStub(); + } - @Test - public void test() throws CadiException { - EpiLur lur; - try { - lur = new EpiLur(); - } catch (CadiException e) { - assertThat(e.getMessage(), is("Need at least one Lur implementation in constructor")); - } - lur = new EpiLur(lurMock1, lurMock2, lurMock3); - assertThat(lur.fish(null, null), is(false)); + @Test + public void test() throws CadiException { + EpiLur lur; + try { + lur = new EpiLur(); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Need at least one Lur implementation in constructor")); + } + lur = new EpiLur(lurMock1, lurMock2, lurMock3); + assertThat(lur.fish(null, null), is(false)); - assertThat(lur.fish(princMock, permMock), is(false)); + assertThat(lur.fish(princMock, permMock), is(false)); - when(lurMock2.handlesExclusively(permMock)).thenReturn(true); - assertThat(lur.fish(princMock, permMock), is(false)); + when(lurMock2.handlesExclusively(permMock)).thenReturn(true); + assertThat(lur.fish(princMock, permMock), is(false)); - when(lurMock2.fish(princMock, permMock)).thenReturn(true); - assertThat(lur.fish(princMock, permMock), is(true)); + when(lurMock2.fish(princMock, permMock)).thenReturn(true); + assertThat(lur.fish(princMock, permMock), is(true)); - lur.fishAll(princMock, perms); + lur.fishAll(princMock, perms); - assertThat(lur.handlesExclusively(permMock), is(false)); + assertThat(lur.handlesExclusively(permMock), is(false)); - assertThat(lur.get(-1), is(nullValue())); - assertThat(lur.get(0), is(lurMock1)); - assertThat(lur.get(1), is((Lur)lurMock2)); - assertThat(lur.get(2), is((Lur)lurMock3)); - assertThat(lur.get(3), is(nullValue())); + assertThat(lur.get(-1), is(nullValue())); + assertThat(lur.get(0), is(lurMock1)); + assertThat(lur.get(1), is((Lur)lurMock2)); + assertThat(lur.get(2), is((Lur)lurMock3)); + assertThat(lur.get(3), is(nullValue())); - assertThat(lur.handles(princMock), is(false)); - when(lurMock2.handles(princMock)).thenReturn(true); - assertThat(lur.handles(princMock), is(true)); + assertThat(lur.handles(princMock), is(false)); + when(lurMock2.handles(princMock)).thenReturn(true); + assertThat(lur.handles(princMock), is(true)); - lur.remove("id"); + lur.remove("id"); - lur.clear(princMock, null); + lur.clear(princMock, null); - assertThat(lur.createPerm("perm"), is(not(nullValue()))); + assertThat(lur.createPerm("perm"), is(not(nullValue()))); - lur.getUserPassImpl(); - assertThat(lur.getUserPassImpl(), is((CredVal)lurMock3)); + lur.getUserPassImpl(); + assertThat(lur.getUserPassImpl(), is((CredVal)lurMock3)); - lur.toString(); - lur.destroy(); + lur.toString(); + lur.destroy(); - lur = new EpiLur(lurMock1, lurMock2); - assertThat(lur.getUserPassImpl(), is(nullValue())); + lur = new EpiLur(lurMock1, lurMock2); + assertThat(lur.getUserPassImpl(), is(nullValue())); - assertThat(lur.subLur(Lur.class), is(nullValue())); - } + assertThat(lur.subLur(Lur.class), is(nullValue())); + } - private class CredValStub implements Lur, CredVal { - @Override public boolean validate(String user, Type type, byte[] cred, Object state) { return false; } - @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 void destroy() { } - @Override public boolean handlesExclusively(Permission ... pond) { return false; } - @Override public boolean handles(Principal principal) { return false; } - @Override public void clear(Principal p, StringBuilder report) { } - } + private class CredValStub implements Lur, CredVal { + @Override public boolean validate(String user, Type type, byte[] cred, Object state) { return false; } + @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 void destroy() { } + @Override public boolean handlesExclusively(Permission ... pond) { return false; } + @Override public boolean handles(Principal principal) { return false; } + @Override public void clear(Principal p, StringBuilder report) { } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java index f35f81c1..e291cd20 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java @@ -47,126 +47,126 @@ import org.onap.aaf.cadi.lur.LocalPermission; public class JU_LocalLur { - private PropAccess access; - private ByteArrayOutputStream outStream; - - @Mock Permission permMock; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - - outStream = new ByteArrayOutputStream(); - access = new PropAccess(new PrintStream(outStream), new String[0]) { - @Override public String decrypt(String encrypted, boolean anytext) throws IOException { - return rot13(encrypted); - } - @Override public String encrypt(String unencrypted) throws IOException { - return rot13(unencrypted); - } - }; - - } - - @Test - public void test() throws IOException { - final String password = "<pass>"; - final String encrypted = rot13(password); - - LocalLur lur; - List<AbsUserCache<LocalPermission>.DumpInfo> info; - - lur = new LocalLur(access, null, null); - assertThat(lur.dumpInfo().size(), is(0)); - - lur = new LocalLur(access, "user1", null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1")); - - lur.clearAll(); - assertThat(lur.dumpInfo().size(), is(0)); - - lur = new LocalLur(access, "user1%" + encrypted, null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1@none")); - - lur.clearAll(); - assertThat(lur.dumpInfo().size(), is(0)); - - lur = new LocalLur(access, "user1@domain%" + encrypted, null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1@domain")); - - lur = new LocalLur(access, "user1@domain%" + encrypted + ":groupA", null); - info = lur.dumpInfo(); - assertThat(info.size(), is(1)); - assertThat(info.get(0).user, is("user1@domain")); - - when(permMock.getKey()).thenReturn("groupA"); - assertThat(lur.handlesExclusively(permMock), is(true)); - when(permMock.getKey()).thenReturn("groupB"); - assertThat(lur.handlesExclusively(permMock), is(false)); - - assertThat(lur.fish(null, null), is(false)); - - Principal princ = new ConfigPrincipal("user1@localized", encrypted); - - lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); - assertThat(lur.fish(princ, lur.createPerm("groupA")), is(true)); - assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); - assertThat(lur.fish(princ, permMock), is(false)); - - princ = new ConfigPrincipal("user1@domain", encrypted); - assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); - - princ = new ConfigPrincipal("user1@localized", "badpass"); - assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); - - assertThat(lur.handles(null), is(false)); - - lur.fishAll(null, null); - - List<Permission> perms = new ArrayList<>(); - perms.add(lur.createPerm("groupB")); - perms.add(lur.createPerm("groupA")); - princ = new ConfigPrincipal("user1@localized", encrypted); - lur.fishAll(princ, perms); - princ = new ConfigPrincipal("user1@localized", "badpass"); - lur.fishAll(princ, perms); - - assertThat(lur.validate(null, null, null, null), is(false)); - assertThat(lur.validate("user", null, "badpass".getBytes(), null), is(false)); - assertThat(lur.validate("user1@localized", null, encrypted.getBytes(), null), is(false)); - - lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); - assertThat(lur.validate("user1@localized", Type.PASSWORD, encrypted.getBytes(), null), is(true)); - - lur = new LocalLur(access, null, "admin"); - lur = new LocalLur(access, null, "admin:user1"); - lur = new LocalLur(access, null, "admin:user1@localized"); - lur = new LocalLur(access, null, "admin:user1@localized,user2@localized%" + password + ";user:user1@localized"); - } - - public static String rot13(String input) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < input.length(); i++) { - char c = input.charAt(i); - if (c >= 'a' && c <= 'm') { - c += 13; - } else if (c >= 'A' && c <= 'M') { - c += 13; - } else if (c >= 'n' && c <= 'z') { - c -= 13; - } else if (c >= 'N' && c <= 'Z') { - c -= 13; - } - sb.append(c); - } - return sb.toString(); - } + private PropAccess access; + private ByteArrayOutputStream outStream; + + @Mock Permission permMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]) { + @Override public String decrypt(String encrypted, boolean anytext) throws IOException { + return rot13(encrypted); + } + @Override public String encrypt(String unencrypted) throws IOException { + return rot13(unencrypted); + } + }; + + } + + @Test + public void test() throws IOException { + final String password = "<pass>"; + final String encrypted = rot13(password); + + LocalLur lur; + List<AbsUserCache<LocalPermission>.DumpInfo> info; + + lur = new LocalLur(access, null, null); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1", null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1")); + + lur.clearAll(); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1%" + encrypted, null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@none")); + + lur.clearAll(); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1@domain%" + encrypted, null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@domain")); + + lur = new LocalLur(access, "user1@domain%" + encrypted + ":groupA", null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@domain")); + + when(permMock.getKey()).thenReturn("groupA"); + assertThat(lur.handlesExclusively(permMock), is(true)); + when(permMock.getKey()).thenReturn("groupB"); + assertThat(lur.handlesExclusively(permMock), is(false)); + + assertThat(lur.fish(null, null), is(false)); + + Principal princ = new ConfigPrincipal("user1@localized", encrypted); + + lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); + assertThat(lur.fish(princ, lur.createPerm("groupA")), is(true)); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + assertThat(lur.fish(princ, permMock), is(false)); + + princ = new ConfigPrincipal("user1@domain", encrypted); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + + princ = new ConfigPrincipal("user1@localized", "badpass"); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + + assertThat(lur.handles(null), is(false)); + + lur.fishAll(null, null); + + List<Permission> perms = new ArrayList<>(); + perms.add(lur.createPerm("groupB")); + perms.add(lur.createPerm("groupA")); + princ = new ConfigPrincipal("user1@localized", encrypted); + lur.fishAll(princ, perms); + princ = new ConfigPrincipal("user1@localized", "badpass"); + lur.fishAll(princ, perms); + + assertThat(lur.validate(null, null, null, null), is(false)); + assertThat(lur.validate("user", null, "badpass".getBytes(), null), is(false)); + assertThat(lur.validate("user1@localized", null, encrypted.getBytes(), null), is(false)); + + lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); + assertThat(lur.validate("user1@localized", Type.PASSWORD, encrypted.getBytes(), null), is(true)); + + lur = new LocalLur(access, null, "admin"); + lur = new LocalLur(access, null, "admin:user1"); + lur = new LocalLur(access, null, "admin:user1@localized"); + lur = new LocalLur(access, null, "admin:user1@localized,user2@localized%" + password + ";user:user1@localized"); + } + + public static String rot13(String input) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < input.length(); i++) { + char c = input.charAt(i); + if (c >= 'a' && c <= 'm') { + c += 13; + } else if (c >= 'A' && c <= 'M') { + c += 13; + } else if (c >= 'n' && c <= 'z') { + c -= 13; + } else if (c >= 'N' && c <= 'Z') { + c -= 13; + } + sb.append(c); + } + return sb.toString(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java index f4b051a8..4e378cb9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalPermission.java @@ -34,38 +34,38 @@ import org.onap.aaf.cadi.Permission; public class JU_LocalPermission { - @Mock - Permission perm; + @Mock + Permission perm; - private LocalPermission localPerm; - private String role = "Fake Role"; + private LocalPermission localPerm; + private String role = "Fake Role"; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(perm.getKey()).thenReturn(role); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(perm.getKey()).thenReturn(role); - localPerm = new LocalPermission(role); - } + localPerm = new LocalPermission(role); + } - @Test - public void getKeyTest() { - assertThat(localPerm.getKey(), is(role)); - } + @Test + public void getKeyTest() { + assertThat(localPerm.getKey(), is(role)); + } - @Test - public void toStringTest() { - assertThat(localPerm.toString(), is(role)); - } + @Test + public void toStringTest() { + assertThat(localPerm.toString(), is(role)); + } - @Test - public void matchTest() { - assertTrue(localPerm.match(perm)); - } + @Test + public void matchTest() { + assertTrue(localPerm.match(perm)); + } - @Test - public void permTypeTest() { - assertThat(localPerm.permType(), is("LOCAL")); - } + @Test + public void permTypeTest() { + assertThat(localPerm.permType(), is("LOCAL")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java index 1a7293d3..c88a608b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_NullLur.java @@ -36,45 +36,45 @@ import org.onap.aaf.cadi.lur.NullLur; public class JU_NullLur { - @Mock - Principal p; + @Mock + Principal p; - @Mock - Permission perm; + @Mock + Permission perm; - @Mock - List<Permission> perms; + @Mock + List<Permission> perms; - private NullLur nullLur; + private NullLur nullLur; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); - nullLur = new NullLur(); - } + nullLur = new NullLur(); + } - @Test - public void coverageTests() throws Exception { + @Test + public void coverageTests() throws Exception { - Field nullClass = NullLur.class.getDeclaredField("NULL"); - nullClass.setAccessible(true); - assertThat(((Permission) nullClass.get(NullLur.class)).permType(), is("")); - assertThat(((Permission) nullClass.get(NullLur.class)).getKey(), is("")); - assertFalse(((Permission) nullClass.get(NullLur.class)).match(perm)); + Field nullClass = NullLur.class.getDeclaredField("NULL"); + nullClass.setAccessible(true); + assertThat(((Permission) nullClass.get(NullLur.class)).permType(), is("")); + assertThat(((Permission) nullClass.get(NullLur.class)).getKey(), is("")); + assertFalse(((Permission) nullClass.get(NullLur.class)).match(perm)); - nullLur.fishAll(p, perms); - nullLur.destroy(); + nullLur.fishAll(p, perms); + nullLur.destroy(); - assertFalse(nullLur.fish(p, perm)); - assertFalse(nullLur.handlesExclusively(perm)); - assertFalse(nullLur.handles(p)); - assertThat(nullLur.createPerm(""), is(nullClass.get(NullLur.class))); + assertFalse(nullLur.fish(p, perm)); + assertFalse(nullLur.handlesExclusively(perm)); + assertFalse(nullLur.handles(p)); + assertThat(nullLur.createPerm(""), is(nullClass.get(NullLur.class))); - StringBuilder sb = new StringBuilder(); - nullLur.clear(p, sb); - assertThat(sb.toString(), is("NullLur\n")); - assertThat(nullLur.toString(), is("NullLur\n")); - } + StringBuilder sb = new StringBuilder(); + nullLur.clear(p, sb); + assertThat(sb.toString(), is("NullLur\n")); + assertThat(nullLur.toString(), is("NullLur\n")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java index 32d6cd0a..e67e096f 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java @@ -40,85 +40,85 @@ import org.onap.aaf.cadi.principal.BasicPrincipal; public class JU_BasicPrincipal { - @Test - public void Constructor1Test() throws Exception { - // Test that everything works when the content doesn't contain "Basic" - BasicPrincipal bp = new BasicPrincipal("content", "domain"); - assertThat(bp.getName(), is("content")); - assertThat(bp.getCred(), is(nullValue())); - - // Test sending a user without an implicit domain - String name = "User"; - String password = "password"; - String content = name + ":" + password; - String domain = "exampledomain.com"; - String encrypted = new String(Symm.base64.encode(content.getBytes())); - bp = new BasicPrincipal("Basic " + encrypted, domain); - assertThat(bp.getShortName(), is(name)); - assertThat(bp.getName(), is(name + "@" + domain)); - assertThat(bp.getCred(), is(password.getBytes())); - - // Test sending a user with an implicit domain - String longName = name + "@" + domain + ":" + password; - encrypted = new String(Symm.base64.encode(longName.getBytes())); - bp = new BasicPrincipal("Basic " + encrypted, domain); - assertThat(bp.getShortName(), is(name)); - assertThat(bp.getName(), is(name + "@" + domain)); - assertThat(bp.getCred(), is(password.getBytes())); - - // Check that an exception is throw if no name is given in the content - try { - bp = new BasicPrincipal("Basic " + new String(Symm.base64.encode("no name".getBytes())), ""); - fail("Should have thrown an exception"); - } catch (IOException e) { - assertThat(e.getMessage(), is("Invalid Coding")); - } - } - - @Test - public void Constructor2Test() { - String name = "User"; - String password = "password"; - BasicCred bc = mock(BasicCred.class); - when(bc.getUser()).thenReturn(name); - when(bc.getCred()).thenReturn(password.getBytes()); - - BasicPrincipal bp = new BasicPrincipal(bc, "domain"); - assertThat(bp.getName(), is(name)); - assertThat(bp.getCred(), is(password.getBytes())); - } - - @Test - public void accessorsTest() throws IOException { - String name = "User"; - String password = "password"; - String content = name + ":" + password; - String domain = "exampledomain.com"; - String encrypted = new String(Symm.base64.encode(content.getBytes())); - String bearer = "bearer"; - long created = System.currentTimeMillis(); - BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, domain); - bp.setBearer(bearer); - - String expected = "Basic Authorization for " + name + "@" + domain + " evaluated on " + new Date(bp.created()).toString(); - assertTrue(Math.abs(bp.created() - created) < 10); - assertThat(bp.toString(), is(expected)); - assertThat(bp.tag(), is("BAth")); - assertThat(bp.personalName(), is(bp.getName())); - - // This test hits the abstract class BearerPrincipal - assertThat(bp.getBearer(), is(bearer)); - } - - - @Test - public void coverageTest() throws IOException { - String name = "User"; - String password = "password:with:colons"; - String content = name + ":" + password; - String encrypted = new String(Symm.base64.encode(content.getBytes())); - @SuppressWarnings("unused") - BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, "domain"); - } + @Test + public void Constructor1Test() throws Exception { + // Test that everything works when the content doesn't contain "Basic" + BasicPrincipal bp = new BasicPrincipal("content", "domain"); + assertThat(bp.getName(), is("content")); + assertThat(bp.getCred(), is(nullValue())); + + // Test sending a user without an implicit domain + String name = "User"; + String password = "password"; + String content = name + ":" + password; + String domain = "exampledomain.com"; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + bp = new BasicPrincipal("Basic " + encrypted, domain); + assertThat(bp.getShortName(), is(name)); + assertThat(bp.getName(), is(name + "@" + domain)); + assertThat(bp.getCred(), is(password.getBytes())); + + // Test sending a user with an implicit domain + String longName = name + "@" + domain + ":" + password; + encrypted = new String(Symm.base64.encode(longName.getBytes())); + bp = new BasicPrincipal("Basic " + encrypted, domain); + assertThat(bp.getShortName(), is(name)); + assertThat(bp.getName(), is(name + "@" + domain)); + assertThat(bp.getCred(), is(password.getBytes())); + + // Check that an exception is throw if no name is given in the content + try { + bp = new BasicPrincipal("Basic " + new String(Symm.base64.encode("no name".getBytes())), ""); + fail("Should have thrown an exception"); + } catch (IOException e) { + assertThat(e.getMessage(), is("Invalid Coding")); + } + } + + @Test + public void Constructor2Test() { + String name = "User"; + String password = "password"; + BasicCred bc = mock(BasicCred.class); + when(bc.getUser()).thenReturn(name); + when(bc.getCred()).thenReturn(password.getBytes()); + + BasicPrincipal bp = new BasicPrincipal(bc, "domain"); + assertThat(bp.getName(), is(name)); + assertThat(bp.getCred(), is(password.getBytes())); + } + + @Test + public void accessorsTest() throws IOException { + String name = "User"; + String password = "password"; + String content = name + ":" + password; + String domain = "exampledomain.com"; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + String bearer = "bearer"; + long created = System.currentTimeMillis(); + BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, domain); + bp.setBearer(bearer); + + String expected = "Basic Authorization for " + name + "@" + domain + " evaluated on " + new Date(bp.created()).toString(); + assertTrue(Math.abs(bp.created() - created) < 10); + assertThat(bp.toString(), is(expected)); + assertThat(bp.tag(), is("BAth")); + assertThat(bp.personalName(), is(bp.getName())); + + // This test hits the abstract class BearerPrincipal + assertThat(bp.getBearer(), is(bearer)); + } + + + @Test + public void coverageTest() throws IOException { + String name = "User"; + String password = "password:with:colons"; + String content = name + ":" + password; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + @SuppressWarnings("unused") + BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, "domain"); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java index 20e1d4d9..5b780c9a 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java @@ -43,82 +43,82 @@ import org.onap.aaf.cadi.principal.CachedBasicPrincipal; import org.onap.aaf.cadi.taf.HttpTaf; public class JU_CachedBasicPrincipal { - private Field creatorField; - private Field timeToLiveField; - - @Mock - private HttpTaf creator; - - private CachedPrincipal.Resp resp; - - @Before - public void setup() throws NoSuchFieldException, SecurityException { - MockitoAnnotations.initMocks(this); - - creatorField = CachedBasicPrincipal.class.getDeclaredField("creator"); - timeToLiveField = CachedBasicPrincipal.class.getDeclaredField("timeToLive"); - - creatorField.setAccessible(true); - timeToLiveField.setAccessible(true); - } - - @Test - public void Constructor1Test() throws IllegalArgumentException, IllegalAccessException { - String name = "User"; - String password = "password"; - BasicCred bc = mock(BasicCred.class); - when(bc.getUser()).thenReturn(name); - when(bc.getCred()).thenReturn(password.getBytes()); - - long timeToLive = 10000L; - long expires = System.currentTimeMillis() + timeToLive; - CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, bc, "domain", timeToLive); - - assertThat((HttpTaf)creatorField.get(cbp), is(creator)); - assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - } - - @Test - public void Constructor2Test() throws Exception { - String name = "User"; - String password = "password"; - String content = name + ":" + password; - long timeToLive = 10000L; - long expires = System.currentTimeMillis() + timeToLive; - CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); - - assertThat((HttpTaf)creatorField.get(cbp), is(creator)); - assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - } - - @Test - public void revalidateTest() throws IOException, IllegalArgumentException, IllegalAccessException, InterruptedException { - resp = CachedPrincipal.Resp.REVALIDATED; - when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); - - String name = "User"; - String password = "password"; - String content = name + ":" + password; - long timeToLive = 10000L; - long expires = System.currentTimeMillis() + timeToLive; - CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); - - assertTrue(Math.abs(cbp.expires() - expires) < 10); - - Thread.sleep(1); - expires = System.currentTimeMillis() + timeToLive; - assertThat(cbp.revalidate(new Object()), is(resp)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - - resp = CachedPrincipal.Resp.UNVALIDATED; - when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); - expires = System.currentTimeMillis() + timeToLive; - cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); - - assertThat(cbp.revalidate(new Object()), is(resp)); - assertTrue(Math.abs(cbp.expires() - expires) < 10); - } + private Field creatorField; + private Field timeToLiveField; + + @Mock + private HttpTaf creator; + + private CachedPrincipal.Resp resp; + + @Before + public void setup() throws NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + creatorField = CachedBasicPrincipal.class.getDeclaredField("creator"); + timeToLiveField = CachedBasicPrincipal.class.getDeclaredField("timeToLive"); + + creatorField.setAccessible(true); + timeToLiveField.setAccessible(true); + } + + @Test + public void Constructor1Test() throws IllegalArgumentException, IllegalAccessException { + String name = "User"; + String password = "password"; + BasicCred bc = mock(BasicCred.class); + when(bc.getUser()).thenReturn(name); + when(bc.getCred()).thenReturn(password.getBytes()); + + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, bc, "domain", timeToLive); + + assertThat((HttpTaf)creatorField.get(cbp), is(creator)); + assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } + + @Test + public void Constructor2Test() throws Exception { + String name = "User"; + String password = "password"; + String content = name + ":" + password; + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertThat((HttpTaf)creatorField.get(cbp), is(creator)); + assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } + + @Test + public void revalidateTest() throws IOException, IllegalArgumentException, IllegalAccessException, InterruptedException { + resp = CachedPrincipal.Resp.REVALIDATED; + when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); + + String name = "User"; + String password = "password"; + String content = name + ":" + password; + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertTrue(Math.abs(cbp.expires() - expires) < 10); + + Thread.sleep(1); + expires = System.currentTimeMillis() + timeToLive; + assertThat(cbp.revalidate(new Object()), is(resp)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + + resp = CachedPrincipal.Resp.UNVALIDATED; + when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); + expires = System.currentTimeMillis() + timeToLive; + cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertThat(cbp.revalidate(new Object()), is(resp)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java index e9bd799c..04b9367b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_Kind.java @@ -36,35 +36,35 @@ import org.onap.aaf.cadi.principal.X509Principal; public class JU_Kind { - @Mock - private TrustPrincipal trust; + @Mock + private TrustPrincipal trust; - @Mock - private X509Principal x509; + @Mock + private X509Principal x509; - @Mock - private OAuth2FormPrincipal oauth; + @Mock + private OAuth2FormPrincipal oauth; - @Mock - private BasicPrincipal basic; + @Mock + private BasicPrincipal basic; - @Before - public void setup() throws SecurityException { - MockitoAnnotations.initMocks(this); - } + @Before + public void setup() throws SecurityException { + MockitoAnnotations.initMocks(this); + } - @Test - public void getKind() { - assertThat(Kind.getKind(trust), is('U')); - assertThat(Kind.getKind(x509), is('X')); - assertThat(Kind.getKind(oauth), is('O')); - assertThat(Kind.getKind(basic), is('B')); - } + @Test + public void getKind() { + assertThat(Kind.getKind(trust), is('U')); + assertThat(Kind.getKind(x509), is('X')); + assertThat(Kind.getKind(oauth), is('O')); + assertThat(Kind.getKind(basic), is('B')); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - Kind kind = new Kind(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + Kind kind = new Kind(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java index c0b1c2af..c9623fb9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_OAuth2FormPrincipal.java @@ -30,27 +30,27 @@ import org.onap.aaf.cadi.principal.OAuth2FormPrincipal; public class JU_OAuth2FormPrincipal { - private String username = "user"; - private String id = "id"; - - @Test - public void accessorsTest() { - OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); - assertThat(oauth.getName(), is(username)); - assertThat(oauth.client_id(), is(id)); - assertThat(oauth.tag(), is("OAuth")); - } - - @Test - public void personalNameTest() { - OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); - assertThat(oauth.personalName(), is(username + "|" + id)); - - oauth = new OAuth2FormPrincipal(id, null); - assertThat(oauth.personalName(), is(id)); - - oauth = new OAuth2FormPrincipal(id, id); - assertThat(oauth.personalName(), is(id)); - } + private String username = "user"; + private String id = "id"; + + @Test + public void accessorsTest() { + OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); + assertThat(oauth.getName(), is(username)); + assertThat(oauth.client_id(), is(id)); + assertThat(oauth.tag(), is("OAuth")); + } + + @Test + public void personalNameTest() { + OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); + assertThat(oauth.personalName(), is(username + "|" + id)); + + oauth = new OAuth2FormPrincipal(id, null); + assertThat(oauth.personalName(), is(id)); + + oauth = new OAuth2FormPrincipal(id, id); + assertThat(oauth.personalName(), is(id)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java index cce86255..a76e01f7 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_StringTagLookup.java @@ -30,11 +30,11 @@ import org.onap.aaf.cadi.principal.StringTagLookup; public class JU_StringTagLookup { - @Test - public void accessorsTest() throws Exception { - String tag = "tag"; - StringTagLookup stl = new StringTagLookup(tag); - assertThat(stl.lookup(), is(tag)); - } + @Test + public void accessorsTest() throws Exception { + String tag = "tag"; + StringTagLookup stl = new StringTagLookup(tag); + assertThat(stl.lookup(), is(tag)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java index 2bbfee23..3dfe8d86 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TaggedPrincipal.java @@ -33,36 +33,36 @@ import org.onap.aaf.cadi.principal.StringTagLookup; public class JU_TaggedPrincipal { - private final String name = "stubbedName"; - private final String tag = "tag"; + private final String name = "stubbedName"; + private final String tag = "tag"; - private class TaggedPrincipalStub extends TaggedPrincipal { - public TaggedPrincipalStub() { super(); } - public TaggedPrincipalStub(final TagLookup tl) { super(tl); } - @Override public String getName() { return name; } - @Override public String tag() { return null; } - } + private class TaggedPrincipalStub extends TaggedPrincipal { + public TaggedPrincipalStub() { super(); } + public TaggedPrincipalStub(final TagLookup tl) { super(tl); } + @Override public String getName() { return name; } + @Override public String tag() { return null; } + } - private class WhinyTagLookup implements TagLookup { - public WhinyTagLookup(final String tag) { } - @Override - public String lookup() throws CadiException { - throw new CadiException(); - } - } + private class WhinyTagLookup implements TagLookup { + public WhinyTagLookup(final String tag) { } + @Override + public String lookup() throws CadiException { + throw new CadiException(); + } + } - @Test - public void personalNameTest() { - TaggedPrincipal tp = new TaggedPrincipalStub(); - assertThat(tp.personalName(), is(name)); + @Test + public void personalNameTest() { + TaggedPrincipal tp = new TaggedPrincipalStub(); + assertThat(tp.personalName(), is(name)); - StringTagLookup stl = new StringTagLookup(tag); - tp = new TaggedPrincipalStub(stl); - assertThat(tp.personalName(), is(tag)); + StringTagLookup stl = new StringTagLookup(tag); + tp = new TaggedPrincipalStub(stl); + assertThat(tp.personalName(), is(tag)); - WhinyTagLookup wtl = new WhinyTagLookup(tag); - tp.setTagLookup(wtl); - assertThat(tp.personalName(), is(name)); - } + WhinyTagLookup wtl = new WhinyTagLookup(tag); + tp.setTagLookup(wtl); + assertThat(tp.personalName(), is(name)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java index 12b4bc9f..ed1ae4c9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_TrustPrincipal.java @@ -34,58 +34,58 @@ import org.onap.aaf.cadi.principal.TrustPrincipal; public class JU_TrustPrincipal { - private final String ucName = "UserChain"; - private final String uc = "This is a UserChain"; - private final String taggedName = "TaggedPrincipal"; - private final String tag = "tag"; - private final String pName = "Principal"; + private final String ucName = "UserChain"; + private final String uc = "This is a UserChain"; + private final String taggedName = "TaggedPrincipal"; + private final String tag = "tag"; + private final String pName = "Principal"; - private class UserChainPrincipalStub implements Principal, UserChain { - @Override public String userChain() { return uc; } - @Override public String getName() { return ucName; } - } + private class UserChainPrincipalStub implements Principal, UserChain { + @Override public String userChain() { return uc; } + @Override public String getName() { return ucName; } + } - private class TaggedPrincipalStub extends TaggedPrincipal { - public TaggedPrincipalStub() { super(); } - @Override public String getName() { return taggedName; } - @Override public String tag() { return tag; } - } + private class TaggedPrincipalStub extends TaggedPrincipal { + public TaggedPrincipalStub() { super(); } + @Override public String getName() { return taggedName; } + @Override public String tag() { return tag; } + } - private class PrincipalStub implements Principal { - @Override public String getName() { return pName; } - } + private class PrincipalStub implements Principal { + @Override public String getName() { return pName; } + } - @Test - public void userChainConstructorTest() { - UserChainPrincipalStub ucps = new UserChainPrincipalStub(); - TrustPrincipal tp = new TrustPrincipal(ucps, taggedName); - assertThat(tp.getName(), is(taggedName)); - assertThat(tp.userChain(), is(uc)); - assertSame(tp.original(), ucps); - assertThat(tp.tag(), is(uc)); - assertThat(tp.personalName(), is(ucName + '[' + uc + ']')); - } + @Test + public void userChainConstructorTest() { + UserChainPrincipalStub ucps = new UserChainPrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(ucps, taggedName); + assertThat(tp.getName(), is(taggedName)); + assertThat(tp.userChain(), is(uc)); + assertSame(tp.original(), ucps); + assertThat(tp.tag(), is(uc)); + assertThat(tp.personalName(), is(ucName + '[' + uc + ']')); + } - @Test - public void taggedPrincipalConstructorTest() { - TaggedPrincipal tagged = new TaggedPrincipalStub(); - TrustPrincipal tp = new TrustPrincipal(tagged, taggedName); - assertThat(tp.getName(), is(taggedName)); - assertThat(tp.userChain(), is(tag)); - assertSame(tp.original(), tagged); - assertThat(tp.tag(), is(tag)); - assertThat(tp.personalName(), is(taggedName + '[' + tag + ']')); - } + @Test + public void taggedPrincipalConstructorTest() { + TaggedPrincipal tagged = new TaggedPrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(tagged, taggedName); + assertThat(tp.getName(), is(taggedName)); + assertThat(tp.userChain(), is(tag)); + assertSame(tp.original(), tagged); + assertThat(tp.tag(), is(tag)); + assertThat(tp.personalName(), is(taggedName + '[' + tag + ']')); + } - @Test - public void principalConstructorTest() { - Principal principal = new PrincipalStub(); - TrustPrincipal tp = new TrustPrincipal(principal, pName); - assertThat(tp.getName(), is(pName)); - assertThat(tp.userChain(), is(principal.getClass().getSimpleName())); - assertSame(tp.original(), principal); - assertThat(tp.tag(), is(principal.getClass().getSimpleName())); - assertThat(tp.personalName(), is(pName + '[' + principal.getClass().getSimpleName() + ']')); - } + @Test + public void principalConstructorTest() { + Principal principal = new PrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(principal, pName); + assertThat(tp.getName(), is(pName)); + assertThat(tp.userChain(), is(principal.getClass().getSimpleName())); + assertSame(tp.original(), principal); + assertThat(tp.tag(), is(principal.getClass().getSimpleName())); + assertThat(tp.personalName(), is(pName + '[' + principal.getClass().getSimpleName() + ']')); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java index c0095131..60fc88e2 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_UnAuthPrincipal.java @@ -30,12 +30,12 @@ import org.onap.aaf.cadi.principal.UnAuthPrincipal; public class JU_UnAuthPrincipal { - private final String name = "name"; + private final String name = "name"; - @Test - public void accessorsTest() { - UnAuthPrincipal up = new UnAuthPrincipal(name); - assertThat(up.getName(), is(name)); - } + @Test + public void accessorsTest() { + UnAuthPrincipal up = new UnAuthPrincipal(name); + assertThat(up.getName(), is(name)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java index 0857a870..a8839f2c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java @@ -38,103 +38,103 @@ import org.onap.aaf.cadi.principal.X509Principal; public class JU_X509Principal { - private final String name = "x509 name"; - private final byte[] cred = "super duper secret password".getBytes(); - - @Mock - X509Certificate cert; - - @Mock - Principal subject; - - @Before - public void setup() throws CertificateEncodingException { - MockitoAnnotations.initMocks(this); - when(cert.getEncoded()).thenReturn(cred); - } - - @Test - public void constructor1Test() throws IOException { - X509Principal x509 = new X509Principal(name, cert); - // Call twice to hit both branches - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.toString(), is("X509 Authentication for " + name)); - assertTrue(x509.getCred().equals(cred)); - assertThat(x509.getName(), is(name)); - assertThat(x509.tag(), is("x509")); - } - - @Test - public void constructor2Test() throws IOException { - X509Principal x509 = new X509Principal(name, cert, cred,null); - // Call twice to hit both branches - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.toString(), is("X509 Authentication for " + name)); - assertTrue(x509.getCred().equals(cred)); - assertThat(x509.getName(), is(name)); - assertThat(x509.tag(), is("x509")); - } - - @Test - public void constructor3Test() throws IOException { - final String longName = "name@domain"; - when(subject.getName()).thenReturn("OU=" + longName + ",extra"); - when(cert.getSubjectDN()).thenReturn(subject); - X509Principal x509 = new X509Principal(cert, cred,null); - // Call twice to hit both branches - assertThat(x509.getAsHeader(), is("X509 " + cred)); - assertThat(x509.toString(), is("X509 Authentication for " + longName)); - assertTrue(x509.getCred().equals(cred)); - assertThat(x509.getName(), is(longName)); - - when(subject.getName()).thenReturn(longName + ",extra"); - when(cert.getSubjectDN()).thenReturn(subject); - try { - x509 = new X509Principal(cert, cred, null); - fail("Should have thrown an Exception"); - } catch(IOException e) { - assertThat(e.getMessage(), is("X509 does not have Identity as CN")); - } - - when(subject.getName()).thenReturn("OU=" + longName); - when(cert.getSubjectDN()).thenReturn(subject); - try { - x509 = new X509Principal(cert, cred, null); - fail("Should have thrown an Exception"); - } catch(IOException e) { - assertThat(e.getMessage(), is("X509 does not have Identity as CN")); - } - - when(subject.getName()).thenReturn("OU=" + name + ",exta"); - when(cert.getSubjectDN()).thenReturn(subject); - try { - x509 = new X509Principal(cert, cred, null); - fail("Should have thrown an Exception"); - } catch(IOException e) { - assertThat(e.getMessage(), is("X509 does not have Identity as CN")); - } - - } - - @Test - public void throwsTest() throws CertificateEncodingException { - when(cert.getEncoded()).thenThrow(new CertificateEncodingException()); - X509Principal x509 = new X509Principal(name, cert); - assertThat(x509.getCred(), is(nullValue())); - try { - x509.getAsHeader(); - fail("Should have thrown an Exception"); - } catch (IOException e) { - } - } - - @Test - public void getCredTest() { - X509Principal x509 = new X509Principal(name, cert); - // Call twice to hit both branches - assertTrue(x509.getCred().equals(cred)); - assertTrue(x509.getCred().equals(cred)); - } + private final String name = "x509 name"; + private final byte[] cred = "super duper secret password".getBytes(); + + @Mock + X509Certificate cert; + + @Mock + Principal subject; + + @Before + public void setup() throws CertificateEncodingException { + MockitoAnnotations.initMocks(this); + when(cert.getEncoded()).thenReturn(cred); + } + + @Test + public void constructor1Test() throws IOException { + X509Principal x509 = new X509Principal(name, cert); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + name)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(name)); + assertThat(x509.tag(), is("x509")); + } + + @Test + public void constructor2Test() throws IOException { + X509Principal x509 = new X509Principal(name, cert, cred,null); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + name)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(name)); + assertThat(x509.tag(), is("x509")); + } + + @Test + public void constructor3Test() throws IOException { + final String longName = "name@domain"; + when(subject.getName()).thenReturn("OU=" + longName + ",extra"); + when(cert.getSubjectDN()).thenReturn(subject); + X509Principal x509 = new X509Principal(cert, cred,null); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + longName)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(longName)); + + when(subject.getName()).thenReturn(longName + ",extra"); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch(IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + when(subject.getName()).thenReturn("OU=" + longName); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch(IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + when(subject.getName()).thenReturn("OU=" + name + ",exta"); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch(IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + } + + @Test + public void throwsTest() throws CertificateEncodingException { + when(cert.getEncoded()).thenThrow(new CertificateEncodingException()); + X509Principal x509 = new X509Principal(name, cert); + assertThat(x509.getCred(), is(nullValue())); + try { + x509.getAsHeader(); + fail("Should have thrown an Exception"); + } catch (IOException e) { + } + } + + @Test + public void getCredTest() { + X509Principal x509 = new X509Principal(name, cert); + // Call twice to hit both branches + assertTrue(x509.getCred().equals(cred)); + assertTrue(x509.getCred().equals(cred)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java index 137eab3b..b5f019d4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java @@ -67,121 +67,121 @@ import org.onap.aaf.cadi.taf.basic.BasicHttpTaf; public class JU_BasicHttpTaf { - private final static String realm = "realm"; - private final static String id = "id"; - private final static String addr = "addr"; - - private final static String name = "User"; - private final static String password = "password"; - private final static String content = name + ":" + password; - private static String encrypted; - - private final static long timeToLive = 10000L; - - private PropAccess access; - - @Mock private HttpServletResponse respMock; - @Mock private HttpServletRequest reqMock; - @Mock private CredVal rbacMock; - @Mock private CachedPrincipal princMock; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - encrypted = new String(Symm.base64.encode(content.getBytes())); - } - - @Test - public void test() { - BasicHttpTaf taf = new BasicHttpTaf(access, rbacMock, realm, timeToLive, true); - BasicCredStub bcstub = new BasicCredStub(); - assertThat(taf.validate(LifeForm.SBLF, bcstub, respMock), is(not(nullValue()))); - - assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); - - when(reqMock.getHeader("Authorization")).thenReturn("test"); - assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); - - when(reqMock.getHeader("Authorization")).thenReturn("Basic " + encrypted); - assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); - - assertThat(taf.revalidate(princMock, "state"), is(Resp.NOT_MINE)); - - assertThat(taf.toString(), is("Basic Auth enabled on realm: " + realm)); - } - - private class BasicCredStub implements HttpServletRequest, BasicCred { - @Override public String getUser() { return id; } - @Override public String getRemoteAddr() { return addr; } - - @Override public AsyncContext getAsyncContext() { return null; } - @Override public Object getAttribute(String arg0) { return null; } - @Override public Enumeration<String> getAttributeNames() { return null; } - @Override public String getCharacterEncoding() { return null; } - @Override public int getContentLength() { return 0; } - @Override public String getContentType() { return null; } - @Override public DispatcherType getDispatcherType() { return null; } - @Override public ServletInputStream getInputStream() throws IOException { return null; } - @Override public String getLocalAddr() { return null; } - @Override public String getLocalName() { return null; } - @Override public int getLocalPort() { return 0; } - @Override public Locale getLocale() { return null; } - @Override public Enumeration<Locale> getLocales() { return null; } - @Override public String getParameter(String arg0) { return null; } - @Override public Map<String, String[]> getParameterMap() { return null; } - @Override public Enumeration<String> getParameterNames() { return null; } - @Override public String[] getParameterValues(String arg0) { return null; } - @Override public String getProtocol() { return null; } - @Override public BufferedReader getReader() throws IOException { return null; } - @Override public String getRealPath(String arg0) { return null; } - @Override public String getRemoteHost() { return null; } - @Override public int getRemotePort() { return 0; } - @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; } - @Override public String getScheme() { return null; } - @Override public String getServerName() { return null; } - @Override public int getServerPort() { return 0; } - @Override public ServletContext getServletContext() { return null; } - @Override public boolean isAsyncStarted() { return false; } - @Override public boolean isAsyncSupported() { return false; } - @Override public boolean isSecure() { return false; } - @Override public void removeAttribute(String arg0) { } - @Override public void setAttribute(String arg0, Object arg1) { } - @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { } - @Override public AsyncContext startAsync() throws IllegalStateException { return null; } - @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) throws IllegalStateException { return null; } - @Override public byte[] getCred() { return null; } - @Override public void setUser(String user) { } - @Override public void setCred(byte[] passwd) { } - @Override public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException { return false; } - @Override public String getAuthType() { return null; } - @Override public String getContextPath() { return null; } - @Override public Cookie[] getCookies() { return null; } - @Override public long getDateHeader(String arg0) { return 0; } - @Override public String getHeader(String arg0) { return null; } - @Override public Enumeration<String> getHeaderNames() { return null; } - @Override public Enumeration<String> getHeaders(String arg0) { return null; } - @Override public int getIntHeader(String arg0) { return 0; } - @Override public String getMethod() { return null; } - @Override public Part getPart(String arg0) throws IOException, ServletException { return null; } - @Override public Collection<Part> getParts() throws IOException, ServletException { return null; } - @Override public String getPathInfo() { return null; } - @Override public String getPathTranslated() { return null; } - @Override public String getQueryString() { return null; } - @Override public String getRemoteUser() { return null; } - @Override public String getRequestURI() { return null; } - @Override public StringBuffer getRequestURL() { return null; } - @Override public String getRequestedSessionId() { return null; } - @Override public String getServletPath() { return null; } - @Override public HttpSession getSession() { return null; } - @Override public HttpSession getSession(boolean arg0) { return null; } - @Override public Principal getUserPrincipal() { return null; } - @Override public boolean isRequestedSessionIdFromCookie() { return false; } - @Override public boolean isRequestedSessionIdFromURL() { return false; } - @Override public boolean isRequestedSessionIdFromUrl() { return false; } - @Override public boolean isRequestedSessionIdValid() { return false; } - @Override public boolean isUserInRole(String arg0) { return false; } - @Override public void login(String arg0, String arg1) throws ServletException { } - @Override public void logout() throws ServletException { } - } + private final static String realm = "realm"; + private final static String id = "id"; + private final static String addr = "addr"; + + private final static String name = "User"; + private final static String password = "password"; + private final static String content = name + ":" + password; + private static String encrypted; + + private final static long timeToLive = 10000L; + + private PropAccess access; + + @Mock private HttpServletResponse respMock; + @Mock private HttpServletRequest reqMock; + @Mock private CredVal rbacMock; + @Mock private CachedPrincipal princMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + encrypted = new String(Symm.base64.encode(content.getBytes())); + } + + @Test + public void test() { + BasicHttpTaf taf = new BasicHttpTaf(access, rbacMock, realm, timeToLive, true); + BasicCredStub bcstub = new BasicCredStub(); + assertThat(taf.validate(LifeForm.SBLF, bcstub, respMock), is(not(nullValue()))); + + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + when(reqMock.getHeader("Authorization")).thenReturn("test"); + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + when(reqMock.getHeader("Authorization")).thenReturn("Basic " + encrypted); + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + assertThat(taf.revalidate(princMock, "state"), is(Resp.NOT_MINE)); + + assertThat(taf.toString(), is("Basic Auth enabled on realm: " + realm)); + } + + private class BasicCredStub implements HttpServletRequest, BasicCred { + @Override public String getUser() { return id; } + @Override public String getRemoteAddr() { return addr; } + + @Override public AsyncContext getAsyncContext() { return null; } + @Override public Object getAttribute(String arg0) { return null; } + @Override public Enumeration<String> getAttributeNames() { return null; } + @Override public String getCharacterEncoding() { return null; } + @Override public int getContentLength() { return 0; } + @Override public String getContentType() { return null; } + @Override public DispatcherType getDispatcherType() { return null; } + @Override public ServletInputStream getInputStream() throws IOException { return null; } + @Override public String getLocalAddr() { return null; } + @Override public String getLocalName() { return null; } + @Override public int getLocalPort() { return 0; } + @Override public Locale getLocale() { return null; } + @Override public Enumeration<Locale> getLocales() { return null; } + @Override public String getParameter(String arg0) { return null; } + @Override public Map<String, String[]> getParameterMap() { return null; } + @Override public Enumeration<String> getParameterNames() { return null; } + @Override public String[] getParameterValues(String arg0) { return null; } + @Override public String getProtocol() { return null; } + @Override public BufferedReader getReader() throws IOException { return null; } + @Override public String getRealPath(String arg0) { return null; } + @Override public String getRemoteHost() { return null; } + @Override public int getRemotePort() { return 0; } + @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; } + @Override public String getScheme() { return null; } + @Override public String getServerName() { return null; } + @Override public int getServerPort() { return 0; } + @Override public ServletContext getServletContext() { return null; } + @Override public boolean isAsyncStarted() { return false; } + @Override public boolean isAsyncSupported() { return false; } + @Override public boolean isSecure() { return false; } + @Override public void removeAttribute(String arg0) { } + @Override public void setAttribute(String arg0, Object arg1) { } + @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { } + @Override public AsyncContext startAsync() throws IllegalStateException { return null; } + @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) throws IllegalStateException { return null; } + @Override public byte[] getCred() { return null; } + @Override public void setUser(String user) { } + @Override public void setCred(byte[] passwd) { } + @Override public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException { return false; } + @Override public String getAuthType() { return null; } + @Override public String getContextPath() { return null; } + @Override public Cookie[] getCookies() { return null; } + @Override public long getDateHeader(String arg0) { return 0; } + @Override public String getHeader(String arg0) { return null; } + @Override public Enumeration<String> getHeaderNames() { return null; } + @Override public Enumeration<String> getHeaders(String arg0) { return null; } + @Override public int getIntHeader(String arg0) { return 0; } + @Override public String getMethod() { return null; } + @Override public Part getPart(String arg0) throws IOException, ServletException { return null; } + @Override public Collection<Part> getParts() throws IOException, ServletException { return null; } + @Override public String getPathInfo() { return null; } + @Override public String getPathTranslated() { return null; } + @Override public String getQueryString() { return null; } + @Override public String getRemoteUser() { return null; } + @Override public String getRequestURI() { return null; } + @Override public StringBuffer getRequestURL() { return null; } + @Override public String getRequestedSessionId() { return null; } + @Override public String getServletPath() { return null; } + @Override public HttpSession getSession() { return null; } + @Override public HttpSession getSession(boolean arg0) { return null; } + @Override public Principal getUserPrincipal() { return null; } + @Override public boolean isRequestedSessionIdFromCookie() { return false; } + @Override public boolean isRequestedSessionIdFromURL() { return false; } + @Override public boolean isRequestedSessionIdFromUrl() { return false; } + @Override public boolean isRequestedSessionIdValid() { return false; } + @Override public boolean isUserInRole(String arg0) { return false; } + @Override public void login(String arg0, String arg1) throws ServletException { } + @Override public void logout() throws ServletException { } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java index 8eba1faf..641545ca 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java @@ -41,27 +41,27 @@ import org.onap.aaf.cadi.taf.basic.BasicHttpTafResp; public class JU_BasicHttpTafResp { - private final static String realm = "realm"; - private final static String description = "description"; + private final static String realm = "realm"; + private final static String description = "description"; - private PropAccess access; + private PropAccess access; - @Mock private HttpServletResponse respMock; - @Mock private TaggedPrincipal princMock; + @Mock private HttpServletResponse respMock; + @Mock private TaggedPrincipal princMock; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } - @Test - public void test() throws IOException { - BasicHttpTafResp tafResp = new BasicHttpTafResp(access, princMock, description, RESP.IS_AUTHENTICATED, respMock, realm, false); + @Test + public void test() throws IOException { + BasicHttpTafResp tafResp = new BasicHttpTafResp(access, princMock, description, RESP.IS_AUTHENTICATED, respMock, realm, false); - assertThat(tafResp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); - assertThat(tafResp.isAuthenticated(), is (RESP.IS_AUTHENTICATED)); - assertThat(tafResp.isFailedAttempt(), is(false)); - } + assertThat(tafResp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + assertThat(tafResp.isAuthenticated(), is (RESP.IS_AUTHENTICATED)); + assertThat(tafResp.isFailedAttempt(), is(false)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java index 36f17ef1..83c93210 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java @@ -39,25 +39,25 @@ import org.onap.aaf.cadi.taf.cert.X509HttpTafResp; public class JU_X509HttpTafResp { - private final static String description = "description"; - private final static RESP status = RESP.IS_AUTHENTICATED; - - private PropAccess access; - - @Mock private TaggedPrincipal princMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws IOException { - X509HttpTafResp resp = new X509HttpTafResp(access, princMock, description, status); - assertThat(resp.authenticate(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(resp.isAuthenticated(), is(status)); - assertThat(resp.toString(), is(status.name())); - } + private final static String description = "description"; + private final static RESP status = RESP.IS_AUTHENTICATED; + + private PropAccess access; + + @Mock private TaggedPrincipal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws IOException { + X509HttpTafResp resp = new X509HttpTafResp(access, princMock, description, status); + assertThat(resp.authenticate(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.toString(), is(status.name())); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java index 997ebced..0f337d1b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java @@ -48,324 +48,324 @@ import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf.Counter; public class JU_DenialOfServiceTaf { - @Mock - HttpServletResponse respMock; - - @Mock - HttpServletRequest reqMock1; - - @Mock - HttpServletRequest reqMock2; - - @Mock - HttpServletRequest reqMock3; - - @Mock - Access accessMock; - - private File dosIPFile; - private File dosIDFile; - private File dosDir; - private final String dosDirName = "test"; - - private final String id1 = "id1"; - private final String id2 = "id2"; - - private final String ip1 = "111.111.111.111"; - private final String ip2 = "222.222.222.222"; - - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); - - dosDir = new File(dosDirName); - dosDir.mkdirs(); - dosIPFile = new File(dosDirName, "/dosIP"); - dosIDFile = new File(dosDirName, "/dosID"); - dosIPFile.delete(); - dosIDFile.delete(); - - when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); - when(reqMock1.getRemoteAddr()).thenReturn(ip1); - when(reqMock2.getRemoteAddr()).thenReturn(ip2); - - setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); - setPrivateField(DenialOfServiceTaf.class, "deniedID", null); - setPrivateField(DenialOfServiceTaf.class, "dosIP", null); - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - } - - @After - public void tearDown() { - dosIPFile = new File(dosDirName, "/dosIP"); - dosIDFile = new File(dosDirName, "/dosID"); - dosIPFile.delete(); - dosIDFile.delete(); - } - - @Test - public void constructorTest() throws CadiException { - @SuppressWarnings("unused") - DenialOfServiceTaf dost; - - // coverage... - when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(null); - dost = new DenialOfServiceTaf(accessMock); - - when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); - dost = new DenialOfServiceTaf(accessMock); - - // more coverage... - dost = new DenialOfServiceTaf(accessMock); - - // more coverage... - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - dost = new DenialOfServiceTaf(accessMock); - } - - @Test - public void validateTest() throws CadiException { - DenialOfServiceTaf dost; - TafResp tafResp; - - dost = new DenialOfServiceTaf(accessMock); - tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); - - assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); - assertThat(tafResp.taf(), is("DenialOfServiceTaf")); - - assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); - - tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); - assertThat(tafResp.desc(), is(ip1 + " is on the IP Denial list")); - - tafResp = dost.validate(LifeForm.SBLF, reqMock2, respMock); - assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); - assertThat(tafResp.taf(), is("DenialOfServiceTaf")); - } - - @Test - public void revalidateTest() throws CadiException { - DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); - Resp resp = dost.revalidate(null, null); - assertThat(resp, is(Resp.NOT_MINE)); - } - - @Test - public void denyIPTest() throws CadiException { - assertThat(DenialOfServiceTaf.isDeniedIP(ip1), is(nullValue())); - assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyIP(ip2), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyIP(ip1), is(false)); // false because it's already been added - assertThat(DenialOfServiceTaf.denyIP(ip2), is(false)); // false because it's already been added - - Counter counter; - counter = DenialOfServiceTaf.isDeniedIP(ip1); - assertThat(counter.getName(), is(ip1)); - assertThat(counter.getCount(), is(0)); - assertThat(counter.getLast(), is(0L)); - assertThat(counter.toString(), is(ip1 + " is on the denied list, but has not attempted Access" )); - - DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); - dost.validate(LifeForm.SBLF, reqMock1, respMock); - long approxTime = System.currentTimeMillis(); - - counter = DenialOfServiceTaf.isDeniedIP(ip1); - assertThat(counter.getName(), is(ip1)); - assertThat(counter.getCount(), is(1)); - assertThat((Math.abs(approxTime - counter.getLast()) < 10), is(true)); - assertThat(counter.toString().contains(ip1), is(true)); - assertThat(counter.toString().contains(" has been denied 1 times since "), is(true)); - assertThat(counter.toString().contains(". Last denial was "), is(true)); - - // coverage... - dost.validate(LifeForm.SBLF, reqMock1, respMock); - - assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(true)); - assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(false)); - assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(true)); - assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(false)); - } - - @Test - public void denyIDTest() throws CadiException { - assertThat(DenialOfServiceTaf.isDeniedID(id1), is(nullValue())); - assertThat(DenialOfServiceTaf.denyID(id1), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyID(id2), is(true)); // true because it's been added - assertThat(DenialOfServiceTaf.denyID(id1), is(false)); // false because it's already been added - assertThat(DenialOfServiceTaf.denyID(id2), is(false)); // false because it's already been added - - Counter counter; - counter = DenialOfServiceTaf.isDeniedID(id1); - assertThat(counter.getName(), is(id1)); - assertThat(counter.getCount(), is(0)); - assertThat(counter.getLast(), is(0L)); - - assertThat(DenialOfServiceTaf.removeDenyID(id1), is(true)); - assertThat(DenialOfServiceTaf.removeDenyID(id1), is(false)); - assertThat(DenialOfServiceTaf.removeDenyID(id2), is(true)); - assertThat(DenialOfServiceTaf.removeDenyID(id2), is(false)); - } - - @Test - public void reportTest() throws CadiException { - DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); - List<String> denials = dost.report(); - assertThat(denials.size(), is(0)); - - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.denyID(id2); - - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.denyIP(ip2); - - denials = dost.report(); - assertThat(denials.size(), is(4)); - for (String denied : denials) { - switch (denied.split(" ", 2)[0]) { - case ip1: - case ip2: - case id1: - case id2: - break; - default: - fail("The line: [" + denied + "] shouldn't be in the report"); - } - } - } - - @Test - public void respDenyIDTest() { - TafResp tafResp = DenialOfServiceTaf.respDenyID(accessMock, id1); - assertThat(tafResp.desc(), is(id1 + " is on the Identity Denial list")); - } - - @Test - public void ipFileIOTest() throws CadiException, IOException { - @SuppressWarnings("unused") - DenialOfServiceTaf dost; - - dosIPFile.createNewFile(); - - // coverage... - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.removeDenyIP(ip1); - - dost = new DenialOfServiceTaf(accessMock); - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.denyIP(ip2); - // coverage... - DenialOfServiceTaf.denyIP(ip2); - - String contents = readContentsFromFile(dosIPFile); - assertThat(contents.contains(ip1), is(true)); - assertThat(contents.contains(ip2), is(true)); - - // Removing all ips should delete the file - assertThat(dosIPFile.exists(), is(true)); - DenialOfServiceTaf.removeDenyIP(ip1); - DenialOfServiceTaf.removeDenyIP(ip2); - assertThat(dosIPFile.exists(), is(false)); - - dosIPFile.createNewFile(); - - DenialOfServiceTaf.denyIP(ip1); - DenialOfServiceTaf.denyIP(ip2); - - setPrivateField(DenialOfServiceTaf.class, "dosIP", null); - dost = new DenialOfServiceTaf(accessMock); - - contents = readContentsFromFile(dosIPFile); - assertThat(contents.contains(ip1), is(true)); - assertThat(contents.contains(ip2), is(true)); - - dosIPFile.delete(); - - // coverage... - setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); - DenialOfServiceTaf.denyIP(ip1); - dosIPFile.delete(); - DenialOfServiceTaf.removeDenyIP(ip1); - - // coverage... - dosIPFile.delete(); - setPrivateField(DenialOfServiceTaf.class, "dosIP", null); - dost = new DenialOfServiceTaf(accessMock); - } - - @Test - public void idFileIOTest() throws CadiException, IOException { - @SuppressWarnings("unused") - DenialOfServiceTaf dost; - - dosIDFile.createNewFile(); - - // coverage... - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.removeDenyID(id1); - - dost = new DenialOfServiceTaf(accessMock); - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.denyID(id2); - // coverage... - DenialOfServiceTaf.denyID(id2); - - String contents = readContentsFromFile(dosIDFile); - assertThat(contents.contains(id1), is(true)); - assertThat(contents.contains(id2), is(true)); - - // Removing all ids should delete the file - assertThat(dosIDFile.exists(), is(true)); - DenialOfServiceTaf.removeDenyID(id1); - DenialOfServiceTaf.removeDenyID(id2); - assertThat(dosIDFile.exists(), is(false)); - - dosIDFile.createNewFile(); - - DenialOfServiceTaf.denyID(id1); - DenialOfServiceTaf.denyID(id2); - - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - dost = new DenialOfServiceTaf(accessMock); - - contents = readContentsFromFile(dosIDFile); - assertThat(contents.contains(id1), is(true)); - assertThat(contents.contains(id2), is(true)); - - dosIDFile.delete(); - - // coverage... - setPrivateField(DenialOfServiceTaf.class, "deniedID", null); - DenialOfServiceTaf.denyID(id1); - dosIDFile.delete(); - DenialOfServiceTaf.removeDenyID(id1); - - // coverage... - dosIDFile.delete(); - setPrivateField(DenialOfServiceTaf.class, "dosID", null); - dost = new DenialOfServiceTaf(accessMock); - } - - private void setPrivateField(Class<?> clazz, String fieldName, Object value) { - try { - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(null, value); - field.setAccessible(false); - } catch(Exception e) { - System.err.println("Could not set field [" + fieldName + "] to " + value); - } - } - - private String readContentsFromFile(File file) throws IOException { - BufferedReader br = new BufferedReader(new FileReader(file)); - StringBuilder sb = new StringBuilder(); - String line; - while ((line = br.readLine()) != null) { - sb.append(line); - } - br.close(); - return sb.toString(); - } + @Mock + HttpServletResponse respMock; + + @Mock + HttpServletRequest reqMock1; + + @Mock + HttpServletRequest reqMock2; + + @Mock + HttpServletRequest reqMock3; + + @Mock + Access accessMock; + + private File dosIPFile; + private File dosIDFile; + private File dosDir; + private final String dosDirName = "test"; + + private final String id1 = "id1"; + private final String id2 = "id2"; + + private final String ip1 = "111.111.111.111"; + private final String ip2 = "222.222.222.222"; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + dosDir = new File(dosDirName); + dosDir.mkdirs(); + dosIPFile = new File(dosDirName, "/dosIP"); + dosIDFile = new File(dosDirName, "/dosID"); + dosIPFile.delete(); + dosIDFile.delete(); + + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); + when(reqMock1.getRemoteAddr()).thenReturn(ip1); + when(reqMock2.getRemoteAddr()).thenReturn(ip2); + + setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); + setPrivateField(DenialOfServiceTaf.class, "deniedID", null); + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + } + + @After + public void tearDown() { + dosIPFile = new File(dosDirName, "/dosIP"); + dosIDFile = new File(dosDirName, "/dosID"); + dosIPFile.delete(); + dosIDFile.delete(); + } + + @Test + public void constructorTest() throws CadiException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + // coverage... + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(null); + dost = new DenialOfServiceTaf(accessMock); + + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); + dost = new DenialOfServiceTaf(accessMock); + + // more coverage... + dost = new DenialOfServiceTaf(accessMock); + + // more coverage... + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + } + + @Test + public void validateTest() throws CadiException { + DenialOfServiceTaf dost; + TafResp tafResp; + + dost = new DenialOfServiceTaf(accessMock); + tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); + + assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); + assertThat(tafResp.taf(), is("DenialOfServiceTaf")); + + assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); + + tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); + assertThat(tafResp.desc(), is(ip1 + " is on the IP Denial list")); + + tafResp = dost.validate(LifeForm.SBLF, reqMock2, respMock); + assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); + assertThat(tafResp.taf(), is("DenialOfServiceTaf")); + } + + @Test + public void revalidateTest() throws CadiException { + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + Resp resp = dost.revalidate(null, null); + assertThat(resp, is(Resp.NOT_MINE)); + } + + @Test + public void denyIPTest() throws CadiException { + assertThat(DenialOfServiceTaf.isDeniedIP(ip1), is(nullValue())); + assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyIP(ip2), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyIP(ip1), is(false)); // false because it's already been added + assertThat(DenialOfServiceTaf.denyIP(ip2), is(false)); // false because it's already been added + + Counter counter; + counter = DenialOfServiceTaf.isDeniedIP(ip1); + assertThat(counter.getName(), is(ip1)); + assertThat(counter.getCount(), is(0)); + assertThat(counter.getLast(), is(0L)); + assertThat(counter.toString(), is(ip1 + " is on the denied list, but has not attempted Access" )); + + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + dost.validate(LifeForm.SBLF, reqMock1, respMock); + long approxTime = System.currentTimeMillis(); + + counter = DenialOfServiceTaf.isDeniedIP(ip1); + assertThat(counter.getName(), is(ip1)); + assertThat(counter.getCount(), is(1)); + assertThat((Math.abs(approxTime - counter.getLast()) < 10), is(true)); + assertThat(counter.toString().contains(ip1), is(true)); + assertThat(counter.toString().contains(" has been denied 1 times since "), is(true)); + assertThat(counter.toString().contains(". Last denial was "), is(true)); + + // coverage... + dost.validate(LifeForm.SBLF, reqMock1, respMock); + + assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(true)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(false)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(true)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(false)); + } + + @Test + public void denyIDTest() throws CadiException { + assertThat(DenialOfServiceTaf.isDeniedID(id1), is(nullValue())); + assertThat(DenialOfServiceTaf.denyID(id1), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyID(id2), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyID(id1), is(false)); // false because it's already been added + assertThat(DenialOfServiceTaf.denyID(id2), is(false)); // false because it's already been added + + Counter counter; + counter = DenialOfServiceTaf.isDeniedID(id1); + assertThat(counter.getName(), is(id1)); + assertThat(counter.getCount(), is(0)); + assertThat(counter.getLast(), is(0L)); + + assertThat(DenialOfServiceTaf.removeDenyID(id1), is(true)); + assertThat(DenialOfServiceTaf.removeDenyID(id1), is(false)); + assertThat(DenialOfServiceTaf.removeDenyID(id2), is(true)); + assertThat(DenialOfServiceTaf.removeDenyID(id2), is(false)); + } + + @Test + public void reportTest() throws CadiException { + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + List<String> denials = dost.report(); + assertThat(denials.size(), is(0)); + + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + + denials = dost.report(); + assertThat(denials.size(), is(4)); + for (String denied : denials) { + switch (denied.split(" ", 2)[0]) { + case ip1: + case ip2: + case id1: + case id2: + break; + default: + fail("The line: [" + denied + "] shouldn't be in the report"); + } + } + } + + @Test + public void respDenyIDTest() { + TafResp tafResp = DenialOfServiceTaf.respDenyID(accessMock, id1); + assertThat(tafResp.desc(), is(id1 + " is on the Identity Denial list")); + } + + @Test + public void ipFileIOTest() throws CadiException, IOException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + dosIPFile.createNewFile(); + + // coverage... + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.removeDenyIP(ip1); + + dost = new DenialOfServiceTaf(accessMock); + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + // coverage... + DenialOfServiceTaf.denyIP(ip2); + + String contents = readContentsFromFile(dosIPFile); + assertThat(contents.contains(ip1), is(true)); + assertThat(contents.contains(ip2), is(true)); + + // Removing all ips should delete the file + assertThat(dosIPFile.exists(), is(true)); + DenialOfServiceTaf.removeDenyIP(ip1); + DenialOfServiceTaf.removeDenyIP(ip2); + assertThat(dosIPFile.exists(), is(false)); + + dosIPFile.createNewFile(); + + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + dost = new DenialOfServiceTaf(accessMock); + + contents = readContentsFromFile(dosIPFile); + assertThat(contents.contains(ip1), is(true)); + assertThat(contents.contains(ip2), is(true)); + + dosIPFile.delete(); + + // coverage... + setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); + DenialOfServiceTaf.denyIP(ip1); + dosIPFile.delete(); + DenialOfServiceTaf.removeDenyIP(ip1); + + // coverage... + dosIPFile.delete(); + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + dost = new DenialOfServiceTaf(accessMock); + } + + @Test + public void idFileIOTest() throws CadiException, IOException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + dosIDFile.createNewFile(); + + // coverage... + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.removeDenyID(id1); + + dost = new DenialOfServiceTaf(accessMock); + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + // coverage... + DenialOfServiceTaf.denyID(id2); + + String contents = readContentsFromFile(dosIDFile); + assertThat(contents.contains(id1), is(true)); + assertThat(contents.contains(id2), is(true)); + + // Removing all ids should delete the file + assertThat(dosIDFile.exists(), is(true)); + DenialOfServiceTaf.removeDenyID(id1); + DenialOfServiceTaf.removeDenyID(id2); + assertThat(dosIDFile.exists(), is(false)); + + dosIDFile.createNewFile(); + + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + + contents = readContentsFromFile(dosIDFile); + assertThat(contents.contains(id1), is(true)); + assertThat(contents.contains(id2), is(true)); + + dosIDFile.delete(); + + // coverage... + setPrivateField(DenialOfServiceTaf.class, "deniedID", null); + DenialOfServiceTaf.denyID(id1); + dosIDFile.delete(); + DenialOfServiceTaf.removeDenyID(id1); + + // coverage... + dosIDFile.delete(); + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + } + + private void setPrivateField(Class<?> clazz, String fieldName, Object value) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(null, value); + field.setAccessible(false); + } catch(Exception e) { + System.err.println("Could not set field [" + fieldName + "] to " + value); + } + } + + private String readContentsFromFile(File file) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(file)); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line); + } + br.close(); + return sb.toString(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java index 34b2a513..b9b7b16d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java @@ -37,21 +37,21 @@ import org.onap.aaf.cadi.taf.dos.DenialOfServiceTafResp; public class JU_DenialOfServiceTafResp { - private final static String description = "description"; - private final static RESP status = RESP.IS_AUTHENTICATED; - - private PropAccess access; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws IOException { - DenialOfServiceTafResp resp = new DenialOfServiceTafResp(access, status, description); - assertThat(resp.isAuthenticated(), is(status)); - assertThat(resp.authenticate(), is(status)); - } + private final static String description = "description"; + private final static RESP status = RESP.IS_AUTHENTICATED; + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws IOException { + DenialOfServiceTafResp resp = new DenialOfServiceTafResp(access, status, description); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.authenticate(), is(status)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java index e4469d30..bf5a15fb 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java @@ -39,52 +39,52 @@ import org.onap.aaf.cadi.taf.AbsTafResp; import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_AbsTafResp { - - private static final String JUNIT = "Junit"; - private static final String name = "name"; - private static final String tag = "tag"; - private static final String description = "description"; - - private Access access; - private TaggedPrincipal taggedPrinc; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - taggedPrinc = new TaggedPrincipal() { - @Override public String getName() { return name; } - @Override public String tag() { return tag; } - }; - } + + private static final String JUNIT = "Junit"; + private static final String name = "name"; + private static final String tag = "tag"; + private static final String description = "description"; + + private Access access; + private TaggedPrincipal taggedPrinc; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + taggedPrinc = new TaggedPrincipal() { + @Override public String getName() { return name; } + @Override public String tag() { return tag; } + }; + } - @Test - public void test() { - AbsTafResp tafResp = new AbsTafResp(access, JUNIT, taggedPrinc, description) { - @Override public RESP authenticate() throws IOException { - return null; - } - }; + @Test + public void test() { + AbsTafResp tafResp = new AbsTafResp(access, JUNIT, taggedPrinc, description) { + @Override public RESP authenticate() throws IOException { + return null; + } + }; - assertThat(tafResp.isValid(), is(true)); - assertThat(tafResp.desc(), is(description)); - assertThat(tafResp.taf(), is(JUNIT)); - assertThat(tafResp.isAuthenticated(), is(RESP.IS_AUTHENTICATED)); - assertThat(tafResp.getPrincipal(), is(taggedPrinc)); - assertThat(tafResp.getAccess(), is(access)); - assertThat(tafResp.isFailedAttempt(), is(false)); + assertThat(tafResp.isValid(), is(true)); + assertThat(tafResp.desc(), is(description)); + assertThat(tafResp.taf(), is(JUNIT)); + assertThat(tafResp.isAuthenticated(), is(RESP.IS_AUTHENTICATED)); + assertThat(tafResp.getPrincipal(), is(taggedPrinc)); + assertThat(tafResp.getAccess(), is(access)); + assertThat(tafResp.isFailedAttempt(), is(false)); - tafResp = new AbsTafResp(null, JUNIT, null, null) { - @Override public RESP authenticate() throws IOException { - return null; - } - }; + tafResp = new AbsTafResp(null, JUNIT, null, null) { + @Override public RESP authenticate() throws IOException { + return null; + } + }; - assertThat(tafResp.isValid(), is(false)); - assertThat(tafResp.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(tafResp.getPrincipal(), is(nullValue())); - assertThat(tafResp.getAccess(), is(nullValue())); - assertThat(tafResp.taf(), is(JUNIT)); - assertThat(tafResp.isFailedAttempt(), is(false)); - } + assertThat(tafResp.isValid(), is(false)); + assertThat(tafResp.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(tafResp.getPrincipal(), is(nullValue())); + assertThat(tafResp.getAccess(), is(nullValue())); + assertThat(tafResp.taf(), is(JUNIT)); + assertThat(tafResp.isFailedAttempt(), is(false)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java index f8e20cbf..cb96f87b 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_EpiTaf.java @@ -40,71 +40,71 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_EpiTaf { - @Test(expected = CadiException.class) - @SuppressWarnings("unused") - public void constructorTest() throws CadiException { - EpiTaf et = new EpiTaf(); - } + @Test(expected = CadiException.class) + @SuppressWarnings("unused") + public void constructorTest() throws CadiException { + EpiTaf et = new EpiTaf(); + } - @Test - public void validateTryAnotherTest() throws CadiException { - EpiTaf et = new EpiTaf(new TryAnotherTaf()); - TafResp output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - } + @Test + public void validateTryAnotherTest() throws CadiException { + EpiTaf et = new EpiTaf(new TryAnotherTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + } - @Test - public void validateTryAuthenticatingTest() throws CadiException { - EpiTaf et = new EpiTaf(new TryAuthenticatingTaf(), new TryAuthenticatingTaf()); - TafResp output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); - output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); - } + @Test + public void validateTryAuthenticatingTest() throws CadiException { + EpiTaf et = new EpiTaf(new TryAuthenticatingTaf(), new TryAuthenticatingTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + } - @Test - public void validateDefaultCaseTest() throws CadiException { - EpiTaf et = new EpiTaf(new NullTaf()); - TafResp output = et.validate(LifeForm.CBLF); - assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - } + @Test + public void validateDefaultCaseTest() throws CadiException { + EpiTaf et = new EpiTaf(new NullTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + } - class TryAnotherTafResp implements TafResp { - @Override public boolean isValid() { return false; } - @Override public String desc() { return null; } - @Override public RESP isAuthenticated() { return RESP.TRY_ANOTHER_TAF; } - @Override public RESP authenticate() throws IOException { return null; } - @Override public TaggedPrincipal getPrincipal() { return null; } - @Override public Access getAccess() { return null; } - @Override public boolean isFailedAttempt() { return false; } - @Override public float timing() { return 0; } - @Override public void timing(long start) {} - @Override public String taf() {return "JUnit";} - } + class TryAnotherTafResp implements TafResp { + @Override public boolean isValid() { return false; } + @Override public String desc() { return null; } + @Override public RESP isAuthenticated() { return RESP.TRY_ANOTHER_TAF; } + @Override public RESP authenticate() throws IOException { return null; } + @Override public TaggedPrincipal getPrincipal() { return null; } + @Override public Access getAccess() { return null; } + @Override public boolean isFailedAttempt() { return false; } + @Override public float timing() { return 0; } + @Override public void timing(long start) {} + @Override public String taf() {return "JUnit";} + } - class TryAnotherTaf implements Taf { - @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAnotherTafResp(); } - } + class TryAnotherTaf implements Taf { + @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAnotherTafResp(); } + } - class TryAuthenticatingResp implements TafResp { - @Override public boolean isValid() { return false; } - @Override public String desc() { return null; } - @Override public RESP isAuthenticated() { return RESP.TRY_AUTHENTICATING; } - @Override public RESP authenticate() throws IOException { return null; } - @Override public TaggedPrincipal getPrincipal() { return null; } - @Override public Access getAccess() { return null; } - @Override public boolean isFailedAttempt() { return false; } - @Override public float timing() { return 0; } - @Override public void timing(long start) {} - @Override public String taf() {return "JUnit";} - } + class TryAuthenticatingResp implements TafResp { + @Override public boolean isValid() { return false; } + @Override public String desc() { return null; } + @Override public RESP isAuthenticated() { return RESP.TRY_AUTHENTICATING; } + @Override public RESP authenticate() throws IOException { return null; } + @Override public TaggedPrincipal getPrincipal() { return null; } + @Override public Access getAccess() { return null; } + @Override public boolean isFailedAttempt() { return false; } + @Override public float timing() { return 0; } + @Override public void timing(long start) {} + @Override public String taf() {return "JUnit";} + } - class TryAuthenticatingTaf implements Taf { - @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAuthenticatingResp(); } - } + class TryAuthenticatingTaf implements Taf { + @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAuthenticatingResp(); } + } - class EpiTafStub extends EpiTaf { - public EpiTafStub() throws CadiException { } - } + class EpiTafStub extends EpiTaf { + public EpiTafStub() throws CadiException { } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java index 93a20474..6952a042 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java @@ -54,92 +54,92 @@ import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_HttpEpiTaf { - private PropAccess access; - - @Mock private Locator<URI> locMock; - @Mock private TrustChecker trustCheckerMock; - @Mock private HttpServletRequest reqMock; - @Mock private HttpServletResponse respMock; - @Mock private HttpTaf tafMock; - @Mock private TafResp trespMock; - @Mock private Redirectable redirMock; - - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws Exception { - HttpEpiTaf taf; - try { - taf = new HttpEpiTaf(access, locMock, trustCheckerMock); - fail("Should've thrown an exception"); - } catch (CadiException e) { - assertThat(e.getMessage(), is("Need at least one HttpTaf implementation in constructor")); - } - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, new NullTaf()); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - // Coverage of tricorderScan - taf.validate(LifeForm.LFN, reqMock, respMock); - when(reqMock.getHeader("User-Agent")).thenReturn("Non-mozilla-header"); - taf.validate(LifeForm.LFN, reqMock, respMock); - when(reqMock.getHeader("User-Agent")).thenReturn("Mozilla-header"); - taf.validate(LifeForm.LFN, reqMock, respMock); - - access.setLogLevel(Level.DEBUG); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(trespMock); - when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_ANOTHER_TAF); - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(trespMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(redirMock); - when(redirMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); - taf.validate(LifeForm.CBLF, reqMock, respMock); - - taf = new HttpEpiTaf(access, locMock, null, tafMock); - when(redirMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); - try { - taf.validate(LifeForm.CBLF, reqMock, respMock); - fail("Should've thrown an exception"); - } catch (Exception e) { - } - - assertThat(taf.revalidate(null), is(false)); - assertThat(taf.revalidate(null), is(false)); - - when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE); - assertThat(taf.revalidate(null, null), is(Resp.NOT_MINE)); - when(tafMock.revalidate(null, null)).thenReturn(Resp.REVALIDATED); - assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); - - when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE).thenReturn(Resp.NOT_MINE).thenReturn(Resp.REVALIDATED); - taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock, tafMock); - assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); - - taf.toString(); - - } + private PropAccess access; + + @Mock private Locator<URI> locMock; + @Mock private TrustChecker trustCheckerMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private HttpTaf tafMock; + @Mock private TafResp trespMock; + @Mock private Redirectable redirMock; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws Exception { + HttpEpiTaf taf; + try { + taf = new HttpEpiTaf(access, locMock, trustCheckerMock); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Need at least one HttpTaf implementation in constructor")); + } + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, new NullTaf()); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + // Coverage of tricorderScan + taf.validate(LifeForm.LFN, reqMock, respMock); + when(reqMock.getHeader("User-Agent")).thenReturn("Non-mozilla-header"); + taf.validate(LifeForm.LFN, reqMock, respMock); + when(reqMock.getHeader("User-Agent")).thenReturn("Mozilla-header"); + taf.validate(LifeForm.LFN, reqMock, respMock); + + access.setLogLevel(Level.DEBUG); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(trespMock); + when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_ANOTHER_TAF); + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(trespMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(redirMock); + when(redirMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, null, tafMock); + when(redirMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); + try { + taf.validate(LifeForm.CBLF, reqMock, respMock); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + assertThat(taf.revalidate(null), is(false)); + assertThat(taf.revalidate(null), is(false)); + + when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE); + assertThat(taf.revalidate(null, null), is(Resp.NOT_MINE)); + when(tafMock.revalidate(null, null)).thenReturn(Resp.REVALIDATED); + assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); + + when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE).thenReturn(Resp.NOT_MINE).thenReturn(Resp.REVALIDATED); + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock, tafMock); + assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); + + taf.toString(); + + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java index 3124bbd4..05944e5c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java @@ -52,50 +52,50 @@ import org.onap.aaf.cadi.taf.TafResp.RESP; public class JU_LoginPageTafResp { - private static final String uriString = "example.com"; + private static final String uriString = "example.com"; - private URI uri; - private Access access; - private List<Redirectable> redirectables; + private URI uri; + private Access access; + private List<Redirectable> redirectables; - @Mock private HttpServletResponse respMock; - @Mock private Locator<URI> locatorMock; - @Mock private Redirectable redirMock; + @Mock private HttpServletResponse respMock; + @Mock private Locator<URI> locatorMock; + @Mock private Redirectable redirMock; - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - redirectables = new ArrayList<>(); - uri = new URI(uriString); - } + redirectables = new ArrayList<>(); + uri = new URI(uriString); + } - @Test - public void test() throws LocatorException, IOException { - TafResp resp; - resp = LoginPageTafResp.create(access, null, respMock, redirectables); - assertThat(resp.desc(), is("All Authentication denied")); + @Test + public void test() throws LocatorException, IOException { + TafResp resp; + resp = LoginPageTafResp.create(access, null, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); - redirectables.add(redirMock); - redirectables.add(redirMock); - resp = LoginPageTafResp.create(access, null, respMock, redirectables); - assertThat((Redirectable)resp, is(redirMock)); + redirectables.add(redirMock); + redirectables.add(redirMock); + resp = LoginPageTafResp.create(access, null, respMock, redirectables); + assertThat((Redirectable)resp, is(redirMock)); - resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); - assertThat(resp.desc(), is("All Authentication denied")); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); - when(locatorMock.get((Item)any())).thenReturn(uri); - resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); - assertThat(resp.desc(), is("Multiple Possible HTTP Logins available. Redirecting to Login Choice Page")); - assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); - assertThat(resp.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + when(locatorMock.get((Item)any())).thenReturn(uri); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("Multiple Possible HTTP Logins available. Redirecting to Login Choice Page")); + assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + assertThat(resp.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); - redirectables = new ArrayList<>(); - resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); - assertThat(resp.desc(), is("All Authentication denied")); + redirectables = new ArrayList<>(); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); - } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java index f42184df..83bc8167 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_NullTaf.java @@ -36,30 +36,30 @@ import org.onap.aaf.cadi.taf.NullTaf; public class JU_NullTaf { - @Test - public void test() throws IOException { - NullTaf nt = new NullTaf(); - TafResp singleton1 = nt.validate(null); - TafResp singleton2 = nt.validate(null, null, null); - Resp singleton3 = nt.revalidate(null, null); - - assertThat(singleton1, is(singleton2)); - - assertFalse(singleton1.isValid()); - - assertThat(singleton1.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - - assertThat(singleton1.desc(), is("All Authentication denied")); - - assertThat(singleton1.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); - - assertThat(singleton1.getPrincipal(), is(nullValue())); - - assertThat(singleton1.getAccess(), is(Access.NULL)); - - assertTrue(singleton1.isFailedAttempt()); + @Test + public void test() throws IOException { + NullTaf nt = new NullTaf(); + TafResp singleton1 = nt.validate(null); + TafResp singleton2 = nt.validate(null, null, null); + Resp singleton3 = nt.revalidate(null, null); + + assertThat(singleton1, is(singleton2)); + + assertFalse(singleton1.isValid()); + + assertThat(singleton1.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + + assertThat(singleton1.desc(), is("All Authentication denied")); + + assertThat(singleton1.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); + + assertThat(singleton1.getPrincipal(), is(nullValue())); + + assertThat(singleton1.getAccess(), is(Access.NULL)); + + assertTrue(singleton1.isFailedAttempt()); - assertThat(singleton3, is(Resp.NOT_MINE)); - } + assertThat(singleton3, is(Resp.NOT_MINE)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java index aacce522..a6b3bd2a 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_PuntTafResp.java @@ -35,21 +35,21 @@ import org.onap.aaf.cadi.taf.PuntTafResp; public class JU_PuntTafResp { - @Test - public void test() throws IOException { - String name = "name"; - String explanation = "example explanation"; - - PuntTafResp punt = new PuntTafResp(name, explanation); - - assertFalse(punt.isValid()); - assertThat(punt.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(punt.desc(), is("Not processing this transaction: " + explanation)); - assertThat(punt.taf(), is(name)); - assertThat(punt.authenticate(), is(RESP.TRY_ANOTHER_TAF)); - assertThat(punt.getPrincipal(), is(nullValue())); - assertThat(punt.getAccess(), is(Access.NULL)); - assertFalse(punt.isFailedAttempt()); - } + @Test + public void test() throws IOException { + String name = "name"; + String explanation = "example explanation"; + + PuntTafResp punt = new PuntTafResp(name, explanation); + + assertFalse(punt.isValid()); + assertThat(punt.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(punt.desc(), is("Not processing this transaction: " + explanation)); + assertThat(punt.taf(), is(name)); + assertThat(punt.authenticate(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(punt.getPrincipal(), is(nullValue())); + assertThat(punt.getAccess(), is(Access.NULL)); + assertFalse(punt.isFailedAttempt()); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java index b032c020..9945bfbe 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustNotTafResp.java @@ -37,36 +37,36 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_TrustNotTafResp { - @Mock - TafResp delegateMock; + @Mock + TafResp delegateMock; - @Mock - TaggedPrincipal principalMock; + @Mock + TaggedPrincipal principalMock; - @Mock - Access accessMock; + @Mock + Access accessMock; - private final String description = "Example Description"; + private final String description = "Example Description"; - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); - when(delegateMock.getPrincipal()).thenReturn(principalMock); - when(delegateMock.getAccess()).thenReturn(accessMock); - } + when(delegateMock.getPrincipal()).thenReturn(principalMock); + when(delegateMock.getAccess()).thenReturn(accessMock); + } - @Test - public void test() throws IOException { - TrustNotTafResp ttr = new TrustNotTafResp(delegateMock, description); - assertThat(ttr.isValid(), is(false)); - assertThat(ttr.desc(), is(description)); - assertThat(ttr.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); - assertThat(ttr.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); - assertThat(ttr.getPrincipal(), is(principalMock)); - assertThat(ttr.getAccess(), is(accessMock)); - assertThat(ttr.isFailedAttempt(), is(true)); - assertThat(ttr.toString(), is(description)); - } + @Test + public void test() throws IOException { + TrustNotTafResp ttr = new TrustNotTafResp(delegateMock, description); + assertThat(ttr.isValid(), is(false)); + assertThat(ttr.desc(), is(description)); + assertThat(ttr.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); + assertThat(ttr.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + assertThat(ttr.getPrincipal(), is(principalMock)); + assertThat(ttr.getAccess(), is(accessMock)); + assertThat(ttr.isFailedAttempt(), is(true)); + assertThat(ttr.toString(), is(description)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java index 10b5f146..5fa1a4d9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_TrustTafResp.java @@ -37,46 +37,46 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_TrustTafResp { - @Mock - TafResp delegateMock; + @Mock + TafResp delegateMock; - @Mock - TaggedPrincipal principalMock; + @Mock + TaggedPrincipal principalMock; - @Mock - Access accessMock; + @Mock + Access accessMock; - private final String description = "Example Description"; - private final String anotherDescription = "Another Description"; - private final String name = "name"; + private final String description = "Example Description"; + private final String anotherDescription = "Another Description"; + private final String name = "name"; - private final RESP resp = RESP.IS_AUTHENTICATED; + private final RESP resp = RESP.IS_AUTHENTICATED; - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); - when(delegateMock.desc()).thenReturn(anotherDescription); - when(delegateMock.isValid()).thenReturn(true); - when(delegateMock.isAuthenticated()).thenReturn(resp); - when(delegateMock.authenticate()).thenReturn(resp); - when(delegateMock.getAccess()).thenReturn(accessMock); - when(delegateMock.isFailedAttempt()).thenReturn(true); + when(delegateMock.desc()).thenReturn(anotherDescription); + when(delegateMock.isValid()).thenReturn(true); + when(delegateMock.isAuthenticated()).thenReturn(resp); + when(delegateMock.authenticate()).thenReturn(resp); + when(delegateMock.getAccess()).thenReturn(accessMock); + when(delegateMock.isFailedAttempt()).thenReturn(true); - when(principalMock.getName()).thenReturn(name); - } + when(principalMock.getName()).thenReturn(name); + } - @Test - public void test() throws IOException { - TrustTafResp ttr = new TrustTafResp(delegateMock, principalMock, description); - assertThat(ttr.isValid(), is(true)); - assertThat(ttr.desc(), is(description + ' ' + anotherDescription)); - assertThat(ttr.authenticate(), is(resp)); - assertThat(ttr.isAuthenticated(), is(resp)); - assertThat(ttr.getPrincipal(), is(principalMock)); - assertThat(ttr.getAccess(), is(accessMock)); - assertThat(ttr.isFailedAttempt(), is(true)); - assertThat(ttr.toString(), is(name + " by trust of " + description + ' ' + anotherDescription)); - } + @Test + public void test() throws IOException { + TrustTafResp ttr = new TrustTafResp(delegateMock, principalMock, description); + assertThat(ttr.isValid(), is(true)); + assertThat(ttr.desc(), is(description + ' ' + anotherDescription)); + assertThat(ttr.authenticate(), is(resp)); + assertThat(ttr.isAuthenticated(), is(resp)); + assertThat(ttr.getPrincipal(), is(principalMock)); + assertThat(ttr.getAccess(), is(accessMock)); + assertThat(ttr.isFailedAttempt(), is(true)); + assertThat(ttr.toString(), is(name + " by trust of " + description + ' ' + anotherDescription)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java index d78706dc..67dcb397 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java @@ -46,149 +46,149 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.Symm; public class JU_AES { - private AES aes; - private ByteArrayInputStream baisEncrypt; - private ByteArrayInputStream baisDecrypt; - private ByteArrayOutputStream baosEncrypt; - private ByteArrayOutputStream baosDecrypt; - - private ByteArrayOutputStream errStream; - - @Before - public void setup() throws Exception { - byte[] keyBytes = new byte[AES.AES_KEY_SIZE/8]; - char[] codeset = Symm.base64.codeset; - int offset = (Math.abs(codeset[0]) + 47) % (codeset.length - keyBytes.length); - for(int i = 0; i < keyBytes.length; ++i) { - keyBytes[i] = (byte)codeset[i+offset]; - } - aes = new AES(keyBytes, 0, keyBytes.length); - - errStream = new ByteArrayOutputStream(); - System.setErr(new PrintStream(errStream)); - } - - @After - public void tearDown() { - System.setErr(System.err); - } - - @Test - public void newKeyTest() throws Exception { - SecretKey secretKey = AES.newKey(); - assertThat(secretKey.getAlgorithm(), is(AES.class.getSimpleName())); - } - - @Test - public void encryptDecrpytFromBytes() throws Exception { - String orig = "I'm a password, really"; - byte[] encrypted = aes.encrypt(orig.getBytes()); - byte[] decrypted = aes.decrypt(encrypted); - assertThat(new String(decrypted), is(orig)); + private AES aes; + private ByteArrayInputStream baisEncrypt; + private ByteArrayInputStream baisDecrypt; + private ByteArrayOutputStream baosEncrypt; + private ByteArrayOutputStream baosDecrypt; + + private ByteArrayOutputStream errStream; + + @Before + public void setup() throws Exception { + byte[] keyBytes = new byte[AES.AES_KEY_SIZE/8]; + char[] codeset = Symm.base64.codeset; + int offset = (Math.abs(codeset[0]) + 47) % (codeset.length - keyBytes.length); + for(int i = 0; i < keyBytes.length; ++i) { + keyBytes[i] = (byte)codeset[i+offset]; + } + aes = new AES(keyBytes, 0, keyBytes.length); + + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } + + @Test + public void newKeyTest() throws Exception { + SecretKey secretKey = AES.newKey(); + assertThat(secretKey.getAlgorithm(), is(AES.class.getSimpleName())); + } + + @Test + public void encryptDecrpytFromBytes() throws Exception { + String orig = "I'm a password, really"; + byte[] encrypted = aes.encrypt(orig.getBytes()); + byte[] decrypted = aes.decrypt(encrypted); + assertThat(new String(decrypted), is(orig)); - Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); - aeskeySpec_field.setAccessible(true); - aeskeySpec_field.set(aes, null); - - try { - aes.encrypt(orig.getBytes()); - fail("Should have thrown an exception"); - } catch (CadiException e) { - } - try { - aes.decrypt(encrypted); - fail("Should have thrown an exception"); - } catch (CadiException e) { - } - } - - @Test - public void saveToFileTest() throws Exception { - String filePath = "src/test/resources/output_key"; - File keyfile = new File(filePath); - aes.save(keyfile); - assertTrue(Files.isReadable(Paths.get(filePath))); - assertFalse(Files.isWritable(Paths.get(filePath))); - assertFalse(Files.isExecutable(Paths.get(filePath))); - keyfile.delete(); - } - - @Test - public void encryptDecryptFromInputStream() throws Exception { - String orig = "I'm a password, really"; - byte[] b64encrypted; - String output; - - CipherInputStream cisEncrypt; - CipherInputStream cisDecrypt; - - // Test CipherInputStream - baisEncrypt = new ByteArrayInputStream(orig.getBytes()); - cisEncrypt = aes.inputStream(baisEncrypt, true); - baosEncrypt = new ByteArrayOutputStream(); - transferFromInputStreamToOutputStream(cisEncrypt, baosEncrypt); - cisEncrypt.close(); - - b64encrypted = baosEncrypt.toByteArray(); - - baisDecrypt = new ByteArrayInputStream(b64encrypted); - cisDecrypt = aes.inputStream(baisDecrypt, false); - baosDecrypt = new ByteArrayOutputStream(); - transferFromInputStreamToOutputStream(cisDecrypt, baosDecrypt); - cisDecrypt.close(); - - output = new String(baosDecrypt.toByteArray()); - assertThat(output, is(orig)); - - Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); - aeskeySpec_field.setAccessible(true); - aeskeySpec_field.set(aes, null); - - assertNull(aes.inputStream(baisEncrypt, true)); - assertThat(errStream.toString(), is("Error creating Aes CipherInputStream\n")); - } - - @Test - public void encryptDecryptFromOutputStream() throws Exception { - String orig = "I'm a password, really"; - byte[] b64encrypted; - String output; - - CipherOutputStream cosEncrypt; - CipherOutputStream cosDecrypt; - - // Test CipherOutputStream - baisEncrypt = new ByteArrayInputStream(orig.getBytes()); - baosEncrypt = new ByteArrayOutputStream(); - cosEncrypt = aes.outputStream(baosEncrypt, true); - transferFromInputStreamToOutputStream(baisEncrypt, cosEncrypt); - cosEncrypt.close(); - - b64encrypted = baosEncrypt.toByteArray(); - - baosDecrypt = new ByteArrayOutputStream(); - cosDecrypt = aes.outputStream(baosDecrypt, false); - baisDecrypt = new ByteArrayInputStream(b64encrypted); - transferFromInputStreamToOutputStream(baisDecrypt, cosDecrypt); - cosDecrypt.close(); - - output = new String(baosDecrypt.toByteArray()); - assertThat(output, is(orig)); - - Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); - aeskeySpec_field.setAccessible(true); - aeskeySpec_field.set(aes, null); - - assertNull(aes.outputStream(baosEncrypt, true)); - assertThat(errStream.toString(), is("Error creating Aes CipherOutputStream\n")); - } - - public void transferFromInputStreamToOutputStream(InputStream is, OutputStream os) throws IOException { - byte[] buffer = new byte[200]; - int len; - while ((len = is.read(buffer)) != -1) { - os.write(buffer, 0, len); - } - } - + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + try { + aes.encrypt(orig.getBytes()); + fail("Should have thrown an exception"); + } catch (CadiException e) { + } + try { + aes.decrypt(encrypted); + fail("Should have thrown an exception"); + } catch (CadiException e) { + } + } + + @Test + public void saveToFileTest() throws Exception { + String filePath = "src/test/resources/output_key"; + File keyfile = new File(filePath); + aes.save(keyfile); + assertTrue(Files.isReadable(Paths.get(filePath))); + assertFalse(Files.isWritable(Paths.get(filePath))); + assertFalse(Files.isExecutable(Paths.get(filePath))); + keyfile.delete(); + } + + @Test + public void encryptDecryptFromInputStream() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + CipherInputStream cisEncrypt; + CipherInputStream cisDecrypt; + + // Test CipherInputStream + baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + cisEncrypt = aes.inputStream(baisEncrypt, true); + baosEncrypt = new ByteArrayOutputStream(); + transferFromInputStreamToOutputStream(cisEncrypt, baosEncrypt); + cisEncrypt.close(); + + b64encrypted = baosEncrypt.toByteArray(); + + baisDecrypt = new ByteArrayInputStream(b64encrypted); + cisDecrypt = aes.inputStream(baisDecrypt, false); + baosDecrypt = new ByteArrayOutputStream(); + transferFromInputStreamToOutputStream(cisDecrypt, baosDecrypt); + cisDecrypt.close(); + + output = new String(baosDecrypt.toByteArray()); + assertThat(output, is(orig)); + + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + assertNull(aes.inputStream(baisEncrypt, true)); + assertThat(errStream.toString(), is("Error creating Aes CipherInputStream\n")); + } + + @Test + public void encryptDecryptFromOutputStream() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + CipherOutputStream cosEncrypt; + CipherOutputStream cosDecrypt; + + // Test CipherOutputStream + baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + baosEncrypt = new ByteArrayOutputStream(); + cosEncrypt = aes.outputStream(baosEncrypt, true); + transferFromInputStreamToOutputStream(baisEncrypt, cosEncrypt); + cosEncrypt.close(); + + b64encrypted = baosEncrypt.toByteArray(); + + baosDecrypt = new ByteArrayOutputStream(); + cosDecrypt = aes.outputStream(baosDecrypt, false); + baisDecrypt = new ByteArrayInputStream(b64encrypted); + transferFromInputStreamToOutputStream(baisDecrypt, cosDecrypt); + cosDecrypt.close(); + + output = new String(baosDecrypt.toByteArray()); + assertThat(output, is(orig)); + + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + assertNull(aes.outputStream(baosEncrypt, true)); + assertThat(errStream.toString(), is("Error creating Aes CipherOutputStream\n")); + } + + public void transferFromInputStreamToOutputStream(InputStream is, OutputStream os) throws IOException { + byte[] buffer = new byte[200]; + int len; + while ((len = is.read(buffer)) != -1) { + os.write(buffer, 0, len); + } + } + } 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 index b34e90ab..8305be83 100644 --- 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 @@ -56,310 +56,310 @@ 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(System.lineSeparator()); - 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(System.lineSeparator()); - 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<>(); - names.add(name1); - names.add(name2); - List<String> permissions = new ArrayList<>(); - 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; } - } + @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(System.lineSeparator()); + 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(System.lineSeparator()); + 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<>(); + names.add(name1); + names.add(name2); + List<String> permissions = new ArrayList<>(); + 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_Access.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Access.java index 98903567..f97fb5fe 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Access.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Access.java @@ -32,35 +32,35 @@ import org.onap.aaf.cadi.Access.Level; public class JU_Access { - @Test - public void levelTests() { - assertTrue(Level.DEBUG.inMask(0x1)); - for (int i = 2; i > 0; i <<= 1) { - assertFalse(Level.DEBUG.inMask(i)); - } - assertFalse(Level.DEBUG.inMask(0x80000000)); + @Test + public void levelTests() { + assertTrue(Level.DEBUG.inMask(0x1)); + for (int i = 2; i > 0; i <<= 1) { + assertFalse(Level.DEBUG.inMask(i)); + } + assertFalse(Level.DEBUG.inMask(0x80000000)); - assertThat(Level.DEBUG.addToMask(0x2), is(0x3)); - assertThat(Level.DEBUG.delFromMask(0x1), is(0x0)); - assertThat(Level.DEBUG.toggle(0x2), is(0x3)); - assertThat(Level.DEBUG.toggle(0x1), is(0x0)); - assertThat(Level.DEBUG.maskOf(), is(123153)); - assertThat(Level.NONE.maskOf(), is(0)); - } + assertThat(Level.DEBUG.addToMask(0x2), is(0x3)); + assertThat(Level.DEBUG.delFromMask(0x1), is(0x0)); + assertThat(Level.DEBUG.toggle(0x2), is(0x3)); + assertThat(Level.DEBUG.toggle(0x1), is(0x0)); + assertThat(Level.DEBUG.maskOf(), is(123153)); + assertThat(Level.NONE.maskOf(), is(0)); + } - @Test - public void nullTests() throws IOException { - // These are entirely for coverage - Access.NULL.log(Level.DEBUG); - Access.NULL.printf(Level.DEBUG, ""); - Access.NULL.log(new Exception()); - Access.NULL.classLoader(); - assertThat(Access.NULL.getProperty("", ""), is(nullValue())); - Access.NULL.load(System.in); - Access.NULL.setLogLevel(Level.DEBUG); - assertThat(Access.NULL.decrypt("test", true), is("test")); - assertFalse(Access.NULL.willLog(Level.DEBUG)); - assertThat(Access.NULL.getProperties(), is(not(nullValue()))); - } + @Test + public void nullTests() throws IOException { + // These are entirely for coverage + Access.NULL.log(Level.DEBUG); + Access.NULL.printf(Level.DEBUG, ""); + Access.NULL.log(new Exception()); + Access.NULL.classLoader(); + assertThat(Access.NULL.getProperty("", ""), is(nullValue())); + Access.NULL.load(System.in); + Access.NULL.setLogLevel(Level.DEBUG); + assertThat(Access.NULL.decrypt("test", true), is("test")); + assertFalse(Access.NULL.willLog(Level.DEBUG)); + assertThat(Access.NULL.getProperties(), is(not(nullValue()))); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java index 801259d4..e819d574 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Base64.java @@ -34,59 +34,59 @@ import org.onap.aaf.cadi.Symm; import org.onap.aaf.cadi.config.Config; public class JU_Base64 { - private static final String encoding = "Man is distinguished, not only by his reason, but by this singular " + - "passion from other animals, which is a lust of the mind, that by a " + - "perseverance of delight in the continued and indefatigable generation of " + - "knowledge, exceeds the short vehemence of any carnal pleasure."; + private static final String encoding = "Man is distinguished, not only by his reason, but by this singular " + + "passion from other animals, which is a lust of the mind, that by a " + + "perseverance of delight in the continued and indefatigable generation of " + + "knowledge, exceeds the short vehemence of any carnal pleasure."; - private static final String expected = - "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz\n" + - "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg\n" + - "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu\n" + - "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo\n" + - "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; + private static final String expected = + "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz\n" + + "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg\n" + + "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu\n" + + "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo\n" + + "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; - @Test - public void test() throws Exception { - // Test with different Padding - assertEncoded("leas", "bGVhcw=="); - assertEncoded("leasu", "bGVhc3U="); - assertEncoded("leasur", "bGVhc3Vy"); - assertEncoded("leasure", "bGVhc3VyZQ=="); - assertEncoded("leasure.", "bGVhc3VyZS4="); + @Test + public void test() throws Exception { + // Test with different Padding + assertEncoded("leas", "bGVhcw=="); + assertEncoded("leasu", "bGVhc3U="); + assertEncoded("leasur", "bGVhc3Vy"); + assertEncoded("leasure", "bGVhc3VyZQ=="); + assertEncoded("leasure.", "bGVhc3VyZS4="); - // Test with line ends - assertEncoded(encoding, expected); - } + // Test with line ends + assertEncoded(encoding, expected); + } - @Test - public void symmetric() throws IOException { - String symmetric = new String(Symm.keygen()); - Symm bsym = Symm.obtain(symmetric); - String result = bsym.encode(encoding); - assertThat(bsym.decode(result), is(encoding)); + @Test + public void symmetric() throws IOException { + String symmetric = new String(Symm.keygen()); + Symm bsym = Symm.obtain(symmetric); + String result = bsym.encode(encoding); + assertThat(bsym.decode(result), is(encoding)); - char[] manipulate = symmetric.toCharArray(); - int spot = new SecureRandom().nextInt(manipulate.length); - manipulate[spot]|=0xFF; - String newsymmetric = new String(manipulate); - assertThat(symmetric, is(not(newsymmetric))); - try { - bsym = Symm.obtain(newsymmetric); - result = bsym.decode(result); - assertThat(result, is(encoding)); - } catch (IOException e) { - // this is what we want to see if key wrong - } - } + char[] manipulate = symmetric.toCharArray(); + int spot = new SecureRandom().nextInt(manipulate.length); + manipulate[spot]|=0xFF; + String newsymmetric = new String(manipulate); + assertThat(symmetric, is(not(newsymmetric))); + try { + bsym = Symm.obtain(newsymmetric); + result = bsym.decode(result); + assertThat(result, is(encoding)); + } catch (IOException e) { + // this is what we want to see if key wrong + } + } - private void assertEncoded(String toEncode, String expected) throws IOException { - String result = Symm.base64.encode(toEncode); - assertThat(result, is(expected)); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Symm.base64.decode(new ByteArrayInputStream(result.getBytes()), baos); - result = baos.toString(Config.UTF_8); - assertThat(result, is(toEncode)); - } + private void assertEncoded(String toEncode, String expected) throws IOException { + String result = Symm.base64.encode(toEncode); + assertThat(result, is(expected)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Symm.base64.decode(new ByteArrayInputStream(result.getBytes()), baos); + result = baos.toString(Config.UTF_8); + assertThat(result, is(toEncode)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java index 172270da..d01e0f07 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedCadiWrap.java @@ -28,18 +28,18 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class JU_BufferedCadiWrap { - @Mock - private HttpServletRequest request; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } + @Mock + private HttpServletRequest request; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } - @Test - public void constructorTest() { - // TODO: Ian - This will always fail beacuse the constructor is invalid - // BufferedCadiWrap bcw = new BufferedCadiWrap(request); - } + @Test + public void constructorTest() { + // TODO: Ian - This will always fail beacuse the constructor is invalid + // BufferedCadiWrap bcw = new BufferedCadiWrap(request); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java index 66ac3610..a16487f8 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java @@ -34,98 +34,98 @@ import org.onap.aaf.cadi.BufferedServletInputStream; import static junit.framework.Assert.assertEquals; public class JU_BufferedServletInputStream { - private BufferedServletInputStream bsis; - private String expected; - - @Before - public void setup() throws FileNotFoundException { - expected = new String("This is the expected output"); - bsis = new BufferedServletInputStream(new ByteArrayInputStream(expected.getBytes())); - } - - @After - public void tearDown() throws IOException { - bsis.close(); - } - - @Test - public void ByteReadNoMarkTest() throws Exception { - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - } - Assert.assertEquals(new String(output, 0, i), expected); - } - - @Test - public void ByteReadMarkTest() throws Exception { - bsis.mark(0); - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - } - Assert.assertEquals(new String(output, 0, i), expected); - } - - @Test - public void ByteReadStateIsStoreTest() throws Exception { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); - bsis.mark(0); - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - } - bsis.reset(); - Assert.assertEquals(state_field.get(bsis), 2); // state == READ - } - - @Test - public void ByteReadStateIsReadTest() throws Exception { - bsis.mark(0); // Initialize the capacitor - boolean isReset = false; - int c; - int i = 0; - byte output[] = new byte[100]; - while ((c = bsis.read()) != -1) { - output[i++] = (byte)c; - if ((i > 5) && !isReset) { - // Close the capacitor and start over. This is done for coverage purposes - i = 0; - isReset = true; - bsis.reset(); // Sets state to READ - } - } - Assert.assertEquals(new String(output, 0, i), expected); - } - - @Test - public void ByteReadStateIsNoneTest() throws Exception { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); - bsis.mark(0); // Initialize the capacitor - int c; - c = bsis.read(); - // Close the capacitor. This is done for coverage purposes - bsis.reset(); // Sets state to READ - state_field.setInt(bsis, 0); // state == NONE - c = bsis.read(); - Assert.assertEquals(c, -1); - } - - @Test - public void ByteArrayReadNoMarkTest() throws Exception { - byte output[] = new byte[100]; - int count = bsis.read(output, 0, expected.length()); - Assert.assertEquals(new String(output, 0, count), expected); - Assert.assertEquals(count, expected.length()); - } + private BufferedServletInputStream bsis; + private String expected; + + @Before + public void setup() throws FileNotFoundException { + expected = new String("This is the expected output"); + bsis = new BufferedServletInputStream(new ByteArrayInputStream(expected.getBytes())); + } + + @After + public void tearDown() throws IOException { + bsis.close(); + } + + @Test + public void ByteReadNoMarkTest() throws Exception { + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadMarkTest() throws Exception { + bsis.mark(0); + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadStateIsStoreTest() throws Exception { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + bsis.mark(0); + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + bsis.reset(); + Assert.assertEquals(state_field.get(bsis), 2); // state == READ + } + + @Test + public void ByteReadStateIsReadTest() throws Exception { + bsis.mark(0); // Initialize the capacitor + boolean isReset = false; + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + if ((i > 5) && !isReset) { + // Close the capacitor and start over. This is done for coverage purposes + i = 0; + isReset = true; + bsis.reset(); // Sets state to READ + } + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadStateIsNoneTest() throws Exception { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + bsis.mark(0); // Initialize the capacitor + int c; + c = bsis.read(); + // Close the capacitor. This is done for coverage purposes + bsis.reset(); // Sets state to READ + state_field.setInt(bsis, 0); // state == NONE + c = bsis.read(); + Assert.assertEquals(c, -1); + } + + @Test + public void ByteArrayReadNoMarkTest() throws Exception { + byte output[] = new byte[100]; + int count = bsis.read(output, 0, expected.length()); + Assert.assertEquals(new String(output, 0, count), expected); + Assert.assertEquals(count, expected.length()); + } @Test public void ByteArrayReadTest() throws Exception { @@ -135,50 +135,50 @@ public class JU_BufferedServletInputStream { Assert.assertEquals(new String(output, 0, expected.length()), expected); } - @Test - public void ByteArrayReadStateIsStoreTest() throws Exception { - byte output[] = new byte[100]; - bsis.mark(0); - int count = bsis.read(output, 0, expected.length()); - Assert.assertEquals(new String(output, 0, count), expected); - Assert.assertEquals(count, expected.length()); - - count = bsis.read(output, 0, 0); - Assert.assertEquals(count, -1); - } - - @Test - public void ByteArrayReadStateIsReadTest() throws Exception { - byte output[] = new byte[200]; - for(int i = 0; i < 2; ++i) { - bsis.mark(0); - bsis.read(output, 0, 100); + @Test + public void ByteArrayReadStateIsStoreTest() throws Exception { + byte output[] = new byte[100]; + bsis.mark(0); + int count = bsis.read(output, 0, expected.length()); + Assert.assertEquals(new String(output, 0, count), expected); + Assert.assertEquals(count, expected.length()); + + count = bsis.read(output, 0, 0); + Assert.assertEquals(count, -1); + } + + @Test + public void ByteArrayReadStateIsReadTest() throws Exception { + byte output[] = new byte[200]; + for(int i = 0; i < 2; ++i) { + bsis.mark(0); + bsis.read(output, 0, 100); Assert.assertEquals(new String(output, 0, expected.length()), expected); - bsis.reset(); - bsis.read(output, 0, output.length); + bsis.reset(); + bsis.read(output, 0, output.length); Assert.assertEquals(new String(output, 0, expected.length()), expected); - bsis = new BufferedServletInputStream(new ByteArrayInputStream(output)); - if(i == 0) { - output = new byte[200]; - } - } + bsis = new BufferedServletInputStream(new ByteArrayInputStream(output)); + if(i == 0) { + output = new byte[200]; + } + } Assert.assertEquals(new String(output, 0, expected.length()), expected); - } + } - @Test - public void ByteArrayReadStateIsNoneTest() throws Exception { + @Test + public void ByteArrayReadStateIsNoneTest() throws Exception { byte output[] = new byte[100]; bsis.mark(0); Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); + state_field.setAccessible(true); state_field.setInt(bsis, 0); // state == NONE int count = bsis.read(output, 0, 100); Assert.assertEquals(count, -1); - } + } @Test public void skipTest() throws Exception { @@ -210,42 +210,42 @@ public class JU_BufferedServletInputStream { @Test public void closeTest() throws Exception { - Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); - capacitor_field.setAccessible(true); + Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); + capacitor_field.setAccessible(true); bsis.mark(0); Assert.assertNotNull(capacitor_field.get(bsis)); bsis.close(); - Assert.assertNull(capacitor_field.get(bsis)); + Assert.assertNull(capacitor_field.get(bsis)); } - @Test - public void markTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); - capacitor_field.setAccessible(true); - state_field.setAccessible(true); + @Test + public void markTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); + capacitor_field.setAccessible(true); + state_field.setAccessible(true); - // capacitor is null initially - Assert.assertNull(capacitor_field.get(bsis)); + // capacitor is null initially + Assert.assertNull(capacitor_field.get(bsis)); - state_field.setInt(bsis, 0); // state == NONE - bsis.mark(0); // the value passed into mark is ignored - Assert.assertNotNull(capacitor_field.get(bsis)); - Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + state_field.setInt(bsis, 0); // state == NONE + bsis.mark(0); // the value passed into mark is ignored + Assert.assertNotNull(capacitor_field.get(bsis)); + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE - state_field.setInt(bsis, 1); // state == STORE - bsis.mark(0); // the value passed into mark is ignored - Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + state_field.setInt(bsis, 1); // state == STORE + bsis.mark(0); // the value passed into mark is ignored + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE - state_field.setInt(bsis, 2); // state == READ - bsis.mark(0); // the value passed into mark is ignored - Assert.assertEquals(state_field.get(bsis), 1); // state == STORE - } + state_field.setInt(bsis, 2); // state == READ + bsis.mark(0); // the value passed into mark is ignored + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + } @Test public void resetTest() throws Exception { - Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); - state_field.setAccessible(true); + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); bsis.mark(0); Assert.assertEquals(state_field.get(bsis), 1); // state == STORE @@ -254,7 +254,7 @@ public class JU_BufferedServletInputStream { bsis.reset(); Assert.assertEquals(state_field.get(bsis), 2); // state == READ - state_field.setInt(bsis, -1); // state is invalid + state_field.setInt(bsis, -1); // state is invalid bsis.reset(); // This call does nothing. It is for coverage alone Assert.assertEquals(state_field.get(bsis), -1); // state doesn't change @@ -271,50 +271,50 @@ public class JU_BufferedServletInputStream { Assert.assertTrue(bsis.markSupported()); } - // "Bug" 4/22/2013 - // Some XML code expects Buffered InputStream can never return 0... This isn't actually true, but we'll accommodate as far - // as we can. - // Here, we make sure we set and read the Buffered data, making sure the buffer is empty on the last test... - @Test - public void issue04_22_2013() throws IOException { - String testString = "We want to read in and get out with a Buffered Stream seamlessly."; - ByteArrayInputStream bais = new ByteArrayInputStream(testString.getBytes()); - BufferedServletInputStream bsis = new BufferedServletInputStream(bais); - try { - bsis.mark(0); - byte aa[] = new byte[testString.length()]; // 65 count... important for our test (divisible by 5); - - int read; - for(int i=0;i<aa.length;i+=5) { - read = bsis.read(aa, i, 5); - assertEquals(5,read); - } - // System.out.println(new String(aa)); - - bsis.reset(); - - byte bb[] = new byte[aa.length]; - read = 0; - for(int i=0;read>=0;i+=read) { - read = bsis.read(bb,i,5); - switch(i) { - case 65: - assertEquals(read,-1); - break; - default: - assertEquals(read,5); - } - } - // System.out.println(new String(bb)); - assertEquals(testString,new String(aa)); - assertEquals(testString,new String(bb)); - - } finally { - bsis.close(); - bais.close(); - } - - } + // "Bug" 4/22/2013 + // Some XML code expects Buffered InputStream can never return 0... This isn't actually true, but we'll accommodate as far + // as we can. + // Here, we make sure we set and read the Buffered data, making sure the buffer is empty on the last test... + @Test + public void issue04_22_2013() throws IOException { + String testString = "We want to read in and get out with a Buffered Stream seamlessly."; + ByteArrayInputStream bais = new ByteArrayInputStream(testString.getBytes()); + BufferedServletInputStream bsis = new BufferedServletInputStream(bais); + try { + bsis.mark(0); + byte aa[] = new byte[testString.length()]; // 65 count... important for our test (divisible by 5); + + int read; + for(int i=0;i<aa.length;i+=5) { + read = bsis.read(aa, i, 5); + assertEquals(5,read); + } + // System.out.println(new String(aa)); + + bsis.reset(); + + byte bb[] = new byte[aa.length]; + read = 0; + for(int i=0;read>=0;i+=read) { + read = bsis.read(bb,i,5); + switch(i) { + case 65: + assertEquals(read,-1); + break; + default: + assertEquals(read,5); + } + } + // System.out.println(new String(bb)); + assertEquals(testString,new String(aa)); + assertEquals(testString,new String(bb)); + + } finally { + bsis.close(); + bais.close(); + } + + } } 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 index bfcaeeab..f1b5f144 100644 --- 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 @@ -29,92 +29,92 @@ 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")); - - } + @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 index 850dd22c..ef07fa66 100644 --- 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 @@ -51,111 +51,111 @@ 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 HttpServletRequest request; + + @Mock + private TafResp tafResp; + + @Mock + private TaggedPrincipal principle; - @Mock - private Lur lur; + @Mock + private Lur lur; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); - System.setOut(new PrintStream(new ByteArrayOutputStream())); - } + System.setOut(new PrintStream(new ByteArrayOutputStream())); + } - @After - public void tearDown() { - System.setOut(System.out); - } + @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"); + @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")); - } + 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")); - } + @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/JU_Capacitor.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java index e9bceccd..ad08d159 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java @@ -32,22 +32,22 @@ import org.onap.aaf.cadi.Capacitor; import java.lang.reflect.*; public class JU_Capacitor { - private Capacitor cap; - public final static String TEST_DATA = - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + - "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + - "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + - "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - - @Before - public void setup() { - cap = new Capacitor(); - } - - @Test - public void singleByteTest() throws Exception { + private Capacitor cap; + public final static String TEST_DATA = + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + + @Before + public void setup() { + cap = new Capacitor(); + } + + @Test + public void singleByteTest() throws Exception { assertEquals(cap.read(), -1); cap.setForRead(); Field curr_field = Capacitor.class.getDeclaredField("curr"); @@ -57,35 +57,35 @@ public class JU_Capacitor { assertNull(curr_field.get(cap)); assertEquals(idx_field.get(cap), 0); - for(int iter = 0; iter < 20; ++iter) { - for(int i = 0; i < 20; ++i) { - cap.put((byte)('a' + i)); - } - cap.setForRead(); - byte[] array = new byte[20]; - for(int i = 0; i < 20; ++i) { - array[i]=(byte)cap.read(); - } - assertEquals("abcdefghijklmnopqrst", new String(array)); - assertEquals(-1, cap.read()); - - cap.done(); - } - - for(int i = 0; i < 500; i++) { - cap.put((byte)'a'); - } - cap.setForRead(); - byte[] array = new byte[500]; - for(int i = 0; i < 500; ++i) { - array[i]=(byte)cap.read(); - } + for(int iter = 0; iter < 20; ++iter) { + for(int i = 0; i < 20; ++i) { + cap.put((byte)('a' + i)); + } + cap.setForRead(); + byte[] array = new byte[20]; + for(int i = 0; i < 20; ++i) { + array[i]=(byte)cap.read(); + } + assertEquals("abcdefghijklmnopqrst", new String(array)); + assertEquals(-1, cap.read()); + + cap.done(); + } + + for(int i = 0; i < 500; i++) { + cap.put((byte)'a'); + } + cap.setForRead(); + byte[] array = new byte[500]; + for(int i = 0; i < 500; ++i) { + array[i]=(byte)cap.read(); + } assertEquals((new String(array)).length(), 500); - assertEquals(-1, cap.read()); - } + assertEquals(-1, cap.read()); + } - @Test - public void availableTest() { + @Test + public void availableTest() { assertEquals(cap.available(), 0); for(int i = 0; i < 100; ++i) { cap.put((byte)'a'); @@ -95,9 +95,9 @@ public class JU_Capacitor { assertEquals(cap.available(), 156); } - @Test - public void byteArrayTest() { - byte[] arrayA = TEST_DATA.getBytes(); + @Test + public void byteArrayTest() { + byte[] arrayA = TEST_DATA.getBytes(); assertEquals(cap.read(arrayA, 0, arrayA.length), -1); cap.put(arrayA, 0, arrayA.length); @@ -109,24 +109,24 @@ public class JU_Capacitor { assertEquals(-1, cap.read()); cap.done(); - String b = "This is some content that we want to read"; - byte[] a = b.getBytes(); - byte[] c = new byte[b.length()]; // we want to use this to test reading offsets, etc - - for(int i = 0; i < a.length; i += 11) { - cap.put(a, i, Math.min(11, a.length-i)); - } - cap.reset(); - int read; - for(int i = 0; i < c.length; i += read) { - read = cap.read(c, i, Math.min(3, c.length-i)); - } - assertEquals(b, new String(c)); - } - - @Test - public void resetTest() throws Exception { - cap.reset(); + String b = "This is some content that we want to read"; + byte[] a = b.getBytes(); + byte[] c = new byte[b.length()]; // we want to use this to test reading offsets, etc + + for(int i = 0; i < a.length; i += 11) { + cap.put(a, i, Math.min(11, a.length-i)); + } + cap.reset(); + int read; + for(int i = 0; i < c.length; i += read) { + read = cap.read(c, i, Math.min(3, c.length-i)); + } + assertEquals(b, new String(c)); + } + + @Test + public void resetTest() throws Exception { + cap.reset(); Field curr_field = Capacitor.class.getDeclaredField("curr"); curr_field.setAccessible(true); Field idx_field = Capacitor.class.getDeclaredField("idx"); @@ -134,22 +134,22 @@ public class JU_Capacitor { assertNull(curr_field.get(cap)); assertEquals(idx_field.get(cap), 0); - cap.put((byte)'a'); - cap.reset(); + cap.put((byte)'a'); + cap.reset(); assertNotNull(curr_field.get(cap)); assertEquals(idx_field.get(cap), 1); - } - - @Test - public void skipTest() throws Exception { - // capacitor can't skip if nothing has been put into it - assertEquals(cap.skip(10), 0); - cap.put((byte)'a'); - // The Capacitor can hold 256 bytes. If we try to skip 100 bytes, - // it should only skip 1 byte, leaving 255 remaining - assertEquals(cap.skip(100), 255); - - // Skipping 200 bytes leaves 0 remaining - assertEquals(cap.skip(200), 0); - } + } + + @Test + public void skipTest() throws Exception { + // capacitor can't skip if nothing has been put into it + assertEquals(cap.skip(10), 0); + cap.put((byte)'a'); + // The Capacitor can hold 256 bytes. If we try to skip 100 bytes, + // it should only skip 1 byte, leaving 255 remaining + assertEquals(cap.skip(100), 255); + + // Skipping 200 bytes leaves 0 remaining + assertEquals(cap.skip(200), 0); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java index bf4304d9..3a996df4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java @@ -48,226 +48,226 @@ import org.onap.aaf.cadi.Symm; public class JU_CmdLine { - @Mock - private OutputStream thrower; - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - - private String password; - private String keyfile; - private String quickBrownFoxPlain = "The quick brown fox jumps over the lazy dog"; - private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; - private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; - private Symm symm; - - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); - - System.setOut(new PrintStream(outContent)); - - Properties p = new Properties(); - p.setProperty("force_exit", "false"); - - CmdLine.setSystemExit(false); - keyfile = "src/test/resources/keyfile"; - password = "password"; - - File keyF = new File("src/test/resources", "keyfile"); - FileInputStream fis = new FileInputStream(keyF); - try { - symm = Symm.obtain(fis); - } finally { - fis.close(); - } - } - - @After - public void restoreStreams() throws IOException { - System.setOut(System.out); - System.setIn(System.in); - } - - @Test - public void digestTest() throws Exception { - CmdLine.main(new String[]{"digest", password, keyfile}); - String decrypted = symm.depass(outContent.toString()); - assertThat(decrypted, is(password)); - - System.setIn(new ByteArrayInputStream(password.getBytes())); - CmdLine.main(new String[]{"digest", "-i", keyfile}); - decrypted = symm.depass(outContent.toString()); - assertThat(decrypted, is(password)); - } - - @Test - public void encode64Test() throws Exception { - CmdLine.main(new String[]{"encode64", password}); - String decrypted = Symm.base64.decode(outContent.toString()); - assertThat(decrypted, is(password)); - } - - @Test - public void decode64Test() throws Exception { - String encrypted = Symm.base64.encode(password); - CmdLine.main(new String[]{"decode64", encrypted}); - assertThat(outContent.toString(), is(password + System.lineSeparator())); - } - - @Test - public void encode64urlTest() throws Exception { - CmdLine.main(new String[]{"encode64url", password}); - String decrypted = Symm.base64url.decode(outContent.toString()); - assertThat(decrypted, is(password)); - } - - @Test - public void decode64urlTest() throws Exception { - String encrypted = Symm.base64url.encode(password); - CmdLine.main(new String[]{"decode64url", encrypted}); - assertThat(outContent.toString(), is(password + System.lineSeparator())); - } - - @Test - public void md5Test() throws Exception { - CmdLine.main(new String[]{"md5", quickBrownFoxPlain}); - assertThat(outContent.toString(), is(quickBrownFoxMD5 + System.lineSeparator())); - } - - @Test - public void sha256Test() throws Exception { - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain}); - assertThat(outContent.toString(), is(quickBrownFoxSHA256 + System.lineSeparator())); - - outContent.reset(); - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); - String hash1 = outContent.toString(); - - outContent.reset(); - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); - String hash2 = outContent.toString(); - - outContent.reset(); - CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "11"}); - String hash3 = outContent.toString(); - - assertThat(hash1, is(hash2)); - assertThat(hash1, is(not(hash3))); - } - - @Test - public void keygenTest() throws Exception { - CmdLine.main(new String[]{"keygen"}); - assertThat(outContent.toString().length(), is(2074)); - - String filePath = "test/output_key"; - File testDir = new File("test"); - if(!testDir.exists()) { - testDir.mkdirs(); - } - CmdLine.main(new String[]{"keygen", filePath}); - File keyfile = new File(filePath); - assertTrue(Files.isReadable(Paths.get(filePath))); - assertFalse(Files.isWritable(Paths.get(filePath))); - //assertFalse(Files.isExecutable(Paths.get(filePath))); - keyfile.delete(); - } - - @Test - public void passgenTest() throws Exception { - CmdLine.main(new String[]{"passgen"}); - String output = outContent.toString().trim(); - assertThat(output.length(), is(24)); - assertTrue(containsAny(output, "+!@#$%^&*(){}[]?:;,.")); - assertTrue(containsAny(output, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")); - assertTrue(containsAny(output, "abcdefghijklmnopqrstuvwxyz")); - assertTrue(containsAny(output, "0123456789")); - - int length = 10; - outContent.reset(); - CmdLine.main(new String[]{"passgen", String.valueOf(length)}); - output = outContent.toString().trim(); - assertThat(output.length(), is(length)); - - length = 5; - outContent.reset(); - CmdLine.main(new String[]{"passgen", String.valueOf(length)}); - output = outContent.toString().trim(); - assertThat(output.length(), is(8)); - - // Check that the custom hasRepeats method works - assertTrue(hasRepeats("aa")); - assertTrue(hasRepeats("baa")); - assertTrue(hasRepeats("aab")); - assertTrue(hasRepeats("baab")); - assertFalse(hasRepeats("abc")); - assertFalse(hasRepeats("aba")); - - // Run this a bunch of times for coverage - for (int i = 0; i < 1000; i++) { - outContent.reset(); - CmdLine.main(new String[]{"passgen"}); - output = outContent.toString().trim(); - assertFalse(hasRepeats(output)); - } - } - - @Test - public void urlgenTest() throws Exception { - CmdLine.main(new String[]{"urlgen"}); - String output = outContent.toString().trim(); - assertThat(output.length(), is(24)); - - int length = 5; - outContent.reset(); - CmdLine.main(new String[]{"urlgen", String.valueOf(length)}); - output = outContent.toString().trim(); - assertThat(output.length(), is(5)); - } - - @Test - public void showHelpTest() { - String lineSeparator = System.lineSeparator(); - String expected = - "Usage: java -jar <this jar> ..." + lineSeparator + - " keygen [<keyfile>] (Generates Key on file, or Std Out)" + lineSeparator + - " digest [<passwd>|-i|] <keyfile> (Encrypts Password with \"keyfile\"" + lineSeparator + - " if passwd = -i, will read StdIn" + lineSeparator + - " if passwd is blank, will ask securely)" + lineSeparator + - " passgen <digits> (Generate Password of given size)" + lineSeparator + - " urlgen <digits> (Generate URL field of given size)" + lineSeparator + - " encode64 <your text> (Encodes to Base64)" + lineSeparator + - " decode64 <base64 encoded text> (Decodes from Base64)" + lineSeparator + - " encode64url <your text> (Encodes to Base64 URL charset)" + lineSeparator + - " decode64url <base64url encoded text> (Decodes from Base64 URL charset)" + lineSeparator + - " sha256 <text> <salts(s)> (Digest String into SHA256 Hash)" + lineSeparator + - " md5 <text> (Digest String into MD5 Hash)" + lineSeparator; - - CmdLine.main(new String[]{}); - - assertThat(outContent.toString(), is(expected)); - } - - private boolean containsAny(String str, String searchChars) { - for (char c : searchChars.toCharArray()) { - if (str.indexOf(c) >= 0) { - return true; - } - } - return false; - } - - private boolean hasRepeats(String str) { - int c = -1; - int last; - for (int i = 0; i < str.length(); i++) { - last = c; - c = str.charAt(i); - if (c == last) { - return true; - } - } - return false; - } + @Mock + private OutputStream thrower; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + + private String password; + private String keyfile; + private String quickBrownFoxPlain = "The quick brown fox jumps over the lazy dog"; + private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; + private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; + private Symm symm; + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + + System.setOut(new PrintStream(outContent)); + + Properties p = new Properties(); + p.setProperty("force_exit", "false"); + + CmdLine.setSystemExit(false); + keyfile = "src/test/resources/keyfile"; + password = "password"; + + File keyF = new File("src/test/resources", "keyfile"); + FileInputStream fis = new FileInputStream(keyF); + try { + symm = Symm.obtain(fis); + } finally { + fis.close(); + } + } + + @After + public void restoreStreams() throws IOException { + System.setOut(System.out); + System.setIn(System.in); + } + + @Test + public void digestTest() throws Exception { + CmdLine.main(new String[]{"digest", password, keyfile}); + String decrypted = symm.depass(outContent.toString()); + assertThat(decrypted, is(password)); + + System.setIn(new ByteArrayInputStream(password.getBytes())); + CmdLine.main(new String[]{"digest", "-i", keyfile}); + decrypted = symm.depass(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void encode64Test() throws Exception { + CmdLine.main(new String[]{"encode64", password}); + String decrypted = Symm.base64.decode(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void decode64Test() throws Exception { + String encrypted = Symm.base64.encode(password); + CmdLine.main(new String[]{"decode64", encrypted}); + assertThat(outContent.toString(), is(password + System.lineSeparator())); + } + + @Test + public void encode64urlTest() throws Exception { + CmdLine.main(new String[]{"encode64url", password}); + String decrypted = Symm.base64url.decode(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void decode64urlTest() throws Exception { + String encrypted = Symm.base64url.encode(password); + CmdLine.main(new String[]{"decode64url", encrypted}); + assertThat(outContent.toString(), is(password + System.lineSeparator())); + } + + @Test + public void md5Test() throws Exception { + CmdLine.main(new String[]{"md5", quickBrownFoxPlain}); + assertThat(outContent.toString(), is(quickBrownFoxMD5 + System.lineSeparator())); + } + + @Test + public void sha256Test() throws Exception { + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain}); + assertThat(outContent.toString(), is(quickBrownFoxSHA256 + System.lineSeparator())); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); + String hash1 = outContent.toString(); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); + String hash2 = outContent.toString(); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "11"}); + String hash3 = outContent.toString(); + + assertThat(hash1, is(hash2)); + assertThat(hash1, is(not(hash3))); + } + + @Test + public void keygenTest() throws Exception { + CmdLine.main(new String[]{"keygen"}); + assertThat(outContent.toString().length(), is(2074)); + + String filePath = "test/output_key"; + File testDir = new File("test"); + if(!testDir.exists()) { + testDir.mkdirs(); + } + CmdLine.main(new String[]{"keygen", filePath}); + File keyfile = new File(filePath); + assertTrue(Files.isReadable(Paths.get(filePath))); + assertFalse(Files.isWritable(Paths.get(filePath))); + //assertFalse(Files.isExecutable(Paths.get(filePath))); + keyfile.delete(); + } + + @Test + public void passgenTest() throws Exception { + CmdLine.main(new String[]{"passgen"}); + String output = outContent.toString().trim(); + assertThat(output.length(), is(24)); + assertTrue(containsAny(output, "+!@#$%^&*(){}[]?:;,.")); + assertTrue(containsAny(output, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + assertTrue(containsAny(output, "abcdefghijklmnopqrstuvwxyz")); + assertTrue(containsAny(output, "0123456789")); + + int length = 10; + outContent.reset(); + CmdLine.main(new String[]{"passgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(length)); + + length = 5; + outContent.reset(); + CmdLine.main(new String[]{"passgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(8)); + + // Check that the custom hasRepeats method works + assertTrue(hasRepeats("aa")); + assertTrue(hasRepeats("baa")); + assertTrue(hasRepeats("aab")); + assertTrue(hasRepeats("baab")); + assertFalse(hasRepeats("abc")); + assertFalse(hasRepeats("aba")); + + // Run this a bunch of times for coverage + for (int i = 0; i < 1000; i++) { + outContent.reset(); + CmdLine.main(new String[]{"passgen"}); + output = outContent.toString().trim(); + assertFalse(hasRepeats(output)); + } + } + + @Test + public void urlgenTest() throws Exception { + CmdLine.main(new String[]{"urlgen"}); + String output = outContent.toString().trim(); + assertThat(output.length(), is(24)); + + int length = 5; + outContent.reset(); + CmdLine.main(new String[]{"urlgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(5)); + } + + @Test + public void showHelpTest() { + String lineSeparator = System.lineSeparator(); + String expected = + "Usage: java -jar <this jar> ..." + lineSeparator + + " keygen [<keyfile>] (Generates Key on file, or Std Out)" + lineSeparator + + " digest [<passwd>|-i|] <keyfile> (Encrypts Password with \"keyfile\"" + lineSeparator + + " if passwd = -i, will read StdIn" + lineSeparator + + " if passwd is blank, will ask securely)" + lineSeparator + + " passgen <digits> (Generate Password of given size)" + lineSeparator + + " urlgen <digits> (Generate URL field of given size)" + lineSeparator + + " encode64 <your text> (Encodes to Base64)" + lineSeparator + + " decode64 <base64 encoded text> (Decodes from Base64)" + lineSeparator + + " encode64url <your text> (Encodes to Base64 URL charset)" + lineSeparator + + " decode64url <base64url encoded text> (Decodes from Base64 URL charset)" + lineSeparator + + " sha256 <text> <salts(s)> (Digest String into SHA256 Hash)" + lineSeparator + + " md5 <text> (Digest String into MD5 Hash)" + lineSeparator; + + CmdLine.main(new String[]{}); + + assertThat(outContent.toString(), is(expected)); + } + + private boolean containsAny(String str, String searchChars) { + for (char c : searchChars.toCharArray()) { + if (str.indexOf(c) >= 0) { + return true; + } + } + return false; + } + + private boolean hasRepeats(String str) { + int c = -1; + int last; + for (int i = 0; i < str.length(); i++) { + last = c; + c = str.charAt(i); + if (c == last) { + return true; + } + } + return false; + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java index f5c4d872..343dd22a 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Hash.java @@ -32,156 +32,156 @@ import org.junit.BeforeClass; import static org.hamcrest.CoreMatchers.*; public class JU_Hash { - // Some common test vectors - private String quickBrownFoxVector = "The quick brown fox jumps over the lazy dog"; - private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; - private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; - - private String emptyVector = ""; - private String emptyMD5 = "0xd41d8cd98f00b204e9800998ecf8427e"; - private String emptySHA256 = "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - - - private byte[] same1 = "this is a twin".getBytes(); - private byte[] same2 = "this is a twin".getBytes(); - private byte[] different1 = "guvf vf n gjva".getBytes(); - private byte[] different2 = "this is an only child".getBytes(); - - - private String uppersDec = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - private String uppersHex1 = "0x4142434445464748494A4B4C4D4E4F505152535455565758595A"; - private String uppersHex2 = "0x4142434445464748494a4b4c4d4e4f505152535455565758595a"; - private String uppersHexNo0x1 = "4142434445464748494a4b4c4d4e4f505152535455565758595a"; - private String uppersHexNo0x2 = "4142434445464748494A4B4C4D4E4F505152535455565758595A"; - - private String lowersDec = "abcdefghijklmnopqrstuvwxyz"; - private String lowersHex = "0x6162636465666768696a6b6c6d6e6f707172737475767778797a"; - private String lowersHexNo0x1 = "6162636465666768696a6b6c6d6e6f707172737475767778797a"; - private String lowersHexNo0x2 = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; - - private String numbersDec = "1234567890"; - private String numbersHex = "0x31323334353637383930"; - private String numbersHexNo0x = "31323334353637383930"; - - @SuppressWarnings("unused") - @BeforeClass - public static void getCoverage() { - // All of this class's methods are static, so we never need to instantiate an object. - // That said, we can't get 100% coverage unless we instantiate one - Hash hash = new Hash(); - } + // Some common test vectors + private String quickBrownFoxVector = "The quick brown fox jumps over the lazy dog"; + private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; + private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; + + private String emptyVector = ""; + private String emptyMD5 = "0xd41d8cd98f00b204e9800998ecf8427e"; + private String emptySHA256 = "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + + private byte[] same1 = "this is a twin".getBytes(); + private byte[] same2 = "this is a twin".getBytes(); + private byte[] different1 = "guvf vf n gjva".getBytes(); + private byte[] different2 = "this is an only child".getBytes(); + + + private String uppersDec = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private String uppersHex1 = "0x4142434445464748494A4B4C4D4E4F505152535455565758595A"; + private String uppersHex2 = "0x4142434445464748494a4b4c4d4e4f505152535455565758595a"; + private String uppersHexNo0x1 = "4142434445464748494a4b4c4d4e4f505152535455565758595a"; + private String uppersHexNo0x2 = "4142434445464748494A4B4C4D4E4F505152535455565758595A"; + + private String lowersDec = "abcdefghijklmnopqrstuvwxyz"; + private String lowersHex = "0x6162636465666768696a6b6c6d6e6f707172737475767778797a"; + private String lowersHexNo0x1 = "6162636465666768696a6b6c6d6e6f707172737475767778797a"; + private String lowersHexNo0x2 = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; + + private String numbersDec = "1234567890"; + private String numbersHex = "0x31323334353637383930"; + private String numbersHexNo0x = "31323334353637383930"; + + @SuppressWarnings("unused") + @BeforeClass + public static void getCoverage() { + // All of this class's methods are static, so we never need to instantiate an object. + // That said, we can't get 100% coverage unless we instantiate one + Hash hash = new Hash(); + } @Test public void hashMD5Test() throws Exception { byte[] output = Hash.hashMD5(quickBrownFoxVector.getBytes()); - assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); output = Hash.hashMD5(emptyVector.getBytes()); - assertEquals(emptyMD5, new String(Hash.toHex(output))); + assertEquals(emptyMD5, new String(Hash.toHex(output))); } @Test public void hashMD5WithOffsetTest() throws Exception { byte[] output = Hash.hashMD5(quickBrownFoxVector.getBytes(), 0, quickBrownFoxVector.length()); - assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); output = Hash.hashMD5(emptyVector.getBytes(), 0, emptyVector.length()); - assertEquals(emptyMD5, new String(Hash.toHex(output))); + assertEquals(emptyMD5, new String(Hash.toHex(output))); } @Test public void hashMD5AsStringHexTest() throws Exception { String output = Hash.hashMD5asStringHex(quickBrownFoxVector); - assertEquals(quickBrownFoxMD5, output); + assertEquals(quickBrownFoxMD5, output); output = Hash.hashMD5asStringHex(emptyVector); - assertEquals(emptyMD5, output); + assertEquals(emptyMD5, output); } @Test public void hashSHA256Test() throws Exception { byte[] output = Hash.hashSHA256(quickBrownFoxVector.getBytes()); - assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); output = Hash.hashSHA256(emptyVector.getBytes()); - assertEquals(emptySHA256, new String(Hash.toHex(output))); + assertEquals(emptySHA256, new String(Hash.toHex(output))); } @Test public void hashSHA256WithOffsetTest() throws Exception { byte[] output = Hash.hashSHA256(quickBrownFoxVector.getBytes(), 0, quickBrownFoxVector.length()); - assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); + assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); output = Hash.hashSHA256(emptyVector.getBytes(), 0, emptyVector.length()); - assertEquals(emptySHA256, new String(Hash.toHex(output))); + assertEquals(emptySHA256, new String(Hash.toHex(output))); } @Test public void hashSHA256AsStringHexTest() throws Exception { String output = Hash.hashSHA256asStringHex(quickBrownFoxVector); - assertEquals(quickBrownFoxSHA256, output); + assertEquals(quickBrownFoxSHA256, output); output = Hash.hashSHA256asStringHex(emptyVector); - assertEquals(emptySHA256, output); + assertEquals(emptySHA256, output); } @Test public void hashSaltySHA256AsStringHexTest() throws Exception { - String input = "password"; - String hash1 = Hash.hashSHA256asStringHex(input, 10); - String hash2 = Hash.hashSHA256asStringHex(input, 10); - String hash3 = Hash.hashSHA256asStringHex(input, 11); + String input = "password"; + String hash1 = Hash.hashSHA256asStringHex(input, 10); + String hash2 = Hash.hashSHA256asStringHex(input, 10); + String hash3 = Hash.hashSHA256asStringHex(input, 11); - assertEquals(hash1, hash2); - assertThat(hash1, not(equalTo(hash3))); + assertEquals(hash1, hash2); + assertThat(hash1, not(equalTo(hash3))); } - @Test - public void isEqualTest() throws Exception { - assertTrue(Hash.isEqual(same1, same2)); - assertFalse(Hash.isEqual(same1, different1)); - assertFalse(Hash.isEqual(same1, different2)); - } - - @Test - public void compareToTest() throws Exception { - assertEquals(0, Hash.compareTo(same1, same2)); - // different1 is rot13(same1), so the difference should be 13 - assertEquals(13, Hash.compareTo(same1, different1)); - assertEquals(-78, Hash.compareTo(same1, different2)); - } - - @Test - public void toHexNo0xTest() throws Exception { - assertEquals(uppersHexNo0x1, Hash.toHexNo0x(uppersDec.getBytes())); - assertEquals(lowersHexNo0x1, Hash.toHexNo0x(lowersDec.getBytes())); - assertEquals(numbersHexNo0x, Hash.toHexNo0x(numbersDec.getBytes())); - } - - @Test - public void toHexTest() throws Exception { - assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes())); - assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes())); - assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes())); - } + @Test + public void isEqualTest() throws Exception { + assertTrue(Hash.isEqual(same1, same2)); + assertFalse(Hash.isEqual(same1, different1)); + assertFalse(Hash.isEqual(same1, different2)); + } + + @Test + public void compareToTest() throws Exception { + assertEquals(0, Hash.compareTo(same1, same2)); + // different1 is rot13(same1), so the difference should be 13 + assertEquals(13, Hash.compareTo(same1, different1)); + assertEquals(-78, Hash.compareTo(same1, different2)); + } + + @Test + public void toHexNo0xTest() throws Exception { + assertEquals(uppersHexNo0x1, Hash.toHexNo0x(uppersDec.getBytes())); + assertEquals(lowersHexNo0x1, Hash.toHexNo0x(lowersDec.getBytes())); + assertEquals(numbersHexNo0x, Hash.toHexNo0x(numbersDec.getBytes())); + } + + @Test + public void toHexTest() throws Exception { + assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes())); + assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes())); + assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes())); + } @Test public void toHexWithOffset() throws Exception { - assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes(), 0, uppersDec.length())); - assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes(), 0, lowersDec.length())); - assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes(), 0, numbersDec.length())); + assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes(), 0, uppersDec.length())); + assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes(), 0, lowersDec.length())); + assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes(), 0, numbersDec.length())); } - @Test - public void fromHexTest() throws Exception { - assertEquals(uppersDec, new String(Hash.fromHex(uppersHex1))); - assertEquals(lowersDec, new String(Hash.fromHex(lowersHex))); - assertEquals(numbersDec, new String(Hash.fromHex(numbersHex))); + @Test + public void fromHexTest() throws Exception { + assertEquals(uppersDec, new String(Hash.fromHex(uppersHex1))); + assertEquals(lowersDec, new String(Hash.fromHex(lowersHex))); + assertEquals(numbersDec, new String(Hash.fromHex(numbersHex))); try { // This string doesn't begin with "0x" Hash.fromHex("0X65"); - fail("Should have thrown CadiException"); + fail("Should have thrown CadiException"); } catch (CadiException e) { assertEquals("HexString must start with \"0x\"", e.getMessage()); } @@ -189,22 +189,22 @@ public class JU_Hash { try { // This string has invalid hex characters Hash.fromHex("0xQ"); - fail("Should have thrown CadiException"); + fail("Should have thrown CadiException"); } catch (CadiException e) { // 81 is dec(Q) assertEquals("Invalid char '81' in HexString", e.getMessage()); } - } - - @Test - public void fromHexNo0xTest() throws Exception { - assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x1))); - assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x1))); - assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x2))); - assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x2))); - assertEquals(numbersDec, new String(Hash.fromHexNo0x(numbersHexNo0x))); - byte[] output = Hash.fromHexNo0x("ABC"); - assertEquals(new String(new byte[] {(byte)0x0A, (byte)0xB0}), new String(output)); - assertNull(Hash.fromHexNo0x("~~")); - } + } + + @Test + public void fromHexNo0xTest() throws Exception { + assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x1))); + assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x1))); + assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x2))); + assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x2))); + assertEquals(numbersDec, new String(Hash.fromHexNo0x(numbersHexNo0x))); + byte[] output = Hash.fromHexNo0x("ABC"); + assertEquals(new String(new byte[] {(byte)0x0A, (byte)0xB0}), new String(output)); + assertNull(Hash.fromHexNo0x("~~")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java index 96cf8e51..ef354438 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_LocatorException.java @@ -29,32 +29,32 @@ import org.onap.aaf.cadi.LocatorException; import static org.hamcrest.CoreMatchers.is; public class JU_LocatorException { - @Test - public void stringTest() { - LocatorException exception = new LocatorException("New Exception"); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } + @Test + public void stringTest() { + LocatorException exception = new LocatorException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } - @Test - public void throwableTest() { - LocatorException exception = new LocatorException(new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); - } + @Test + public void throwableTest() { + LocatorException exception = new LocatorException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } - @Test - public void stringThrowableTest() { - LocatorException exception = new LocatorException("New Exception",new Throwable("New Exception")); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } + @Test + public void stringThrowableTest() { + LocatorException exception = new LocatorException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } - @Test - public void characterSequenceTest() { - CharSequence testCS = new String("New Exception"); - LocatorException exception = new LocatorException(testCS); - assertNotNull(exception); - assertThat(exception.getMessage(), is("New Exception")); - } + @Test + public void characterSequenceTest() { + CharSequence testCS = new String("New Exception"); + LocatorException exception = new LocatorException(testCS); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java index 7b5da6c1..eb5d32c6 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java @@ -38,114 +38,114 @@ import java.util.Properties; @SuppressWarnings("unused") public class JU_PropAccess { - // Note: We can't actually get coverage of the protected constructor - - // that will be done later, when testing the child class "ServletContextAccess" - - - @Test - public void ConstructorTest() throws Exception { - PropAccess prop = new PropAccess(); - assertThat(prop.getProperties(), is(not(nullValue()))); - } - - @Test - public void noPrintStreamConstructionTest() throws Exception { - // Test for coverage - PropAccess prop = new PropAccess((PrintStream)null, new String[]{"Invalid argument"}); - } - - @Test - public void noLogItConstructionTest() throws Exception { - // Test for coverage - PropAccess prop = new PropAccess((LogIt)null, new String[]{"Invalid argument"}); - } - - @Test - public void propertiesConstructionTest() throws Exception { - // Coverage tests - PropAccess prop = new PropAccess(System.getProperties()); - prop = new PropAccess((PrintStream)null, System.getProperties()); - } - - @Test - public void stringConstructionTest() throws Exception { - Properties testSystemProps = new Properties(System.getProperties()); - testSystemProps.setProperty("cadi_name", "user"); - System.setProperties(testSystemProps); - PropAccess prop = new PropAccess("cadi_keyfile=src/test/resources/keyfile", "cadi_loglevel=DEBUG", "cadi_prop_files=test/cadi.properties:not_a_file"); - } - - @Test - public void loadTest() throws Exception { - // Coverage tests - Properties props = mock(Properties.class); - when(props.getProperty("cadi_prop_files")).thenReturn("test/cadi.properties").thenReturn(null); - PropAccess pa = new PropAccess(); - Field props_field = PropAccess.class.getDeclaredField("props"); - props_field.setAccessible(true); - props_field.set(pa, props); - ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); - pa.load(bais); - } - - @Test - public void specialConversionsTest() throws Exception { - // Coverage tests - Properties testSystemProps = new Properties(System.getProperties()); - testSystemProps.setProperty("java.specification.version", "1.7"); - System.setProperties(testSystemProps); - PropAccess pa = new PropAccess("AFT_LATITUDE=1", "AFT_LONGITUDE=1", "cadi_protocols=TLSv1.2"); - } - - @Test - public void logTest() throws Exception { - // Coverage tests - PropAccess pa = new PropAccess(); - - pa.log(Level.DEBUG); - pa.printf(Level.DEBUG, "not a real format string"); - - pa.setLogLevel(Level.DEBUG); - pa.log(Level.DEBUG); - pa.log(Level.DEBUG, 1, " ", null, ""); - pa.log(Level.DEBUG, "This is a string", "This is another"); - pa.set(new LogIt() { - @Override public void push(Level level, Object ... elements) {} - }); - try { - pa.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { - fail("Should have thrown an exception"); - } - } - - @Test - public void classLoaderTest() { - PropAccess pa = new PropAccess(); - assertThat(pa.classLoader(), instanceOf(ClassLoader.class)); - } - - @Test - public void encryptionTest() throws Exception { - PropAccess pa = new PropAccess(); - String plainText = "This is a secret message"; - String secret_message = pa.encrypt(plainText); - String modified = secret_message.substring(4); - // Plenty of assertions to hit all branches - assertThat(pa.decrypt(secret_message, false), is(plainText)); - assertThat(pa.decrypt(null, false), is(nullValue())); - assertThat(pa.decrypt(modified, true), is(plainText)); - assertThat(pa.decrypt(modified, false), is(modified)); - } - - @Test - public void setPropertyTest() { - PropAccess pa = new PropAccess(); - pa.setProperty("test", null); - String prop = "New Property"; - String val ="And it's faithful value"; - pa.setProperty(prop, val); - - assertThat(pa.getProperty(prop), is(val)); - } + // Note: We can't actually get coverage of the protected constructor - + // that will be done later, when testing the child class "ServletContextAccess" + + + @Test + public void ConstructorTest() throws Exception { + PropAccess prop = new PropAccess(); + assertThat(prop.getProperties(), is(not(nullValue()))); + } + + @Test + public void noPrintStreamConstructionTest() throws Exception { + // Test for coverage + PropAccess prop = new PropAccess((PrintStream)null, new String[]{"Invalid argument"}); + } + + @Test + public void noLogItConstructionTest() throws Exception { + // Test for coverage + PropAccess prop = new PropAccess((LogIt)null, new String[]{"Invalid argument"}); + } + + @Test + public void propertiesConstructionTest() throws Exception { + // Coverage tests + PropAccess prop = new PropAccess(System.getProperties()); + prop = new PropAccess((PrintStream)null, System.getProperties()); + } + + @Test + public void stringConstructionTest() throws Exception { + Properties testSystemProps = new Properties(System.getProperties()); + testSystemProps.setProperty("cadi_name", "user"); + System.setProperties(testSystemProps); + PropAccess prop = new PropAccess("cadi_keyfile=src/test/resources/keyfile", "cadi_loglevel=DEBUG", "cadi_prop_files=test/cadi.properties:not_a_file"); + } + + @Test + public void loadTest() throws Exception { + // Coverage tests + Properties props = mock(Properties.class); + when(props.getProperty("cadi_prop_files")).thenReturn("test/cadi.properties").thenReturn(null); + PropAccess pa = new PropAccess(); + Field props_field = PropAccess.class.getDeclaredField("props"); + props_field.setAccessible(true); + props_field.set(pa, props); + ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); + pa.load(bais); + } + + @Test + public void specialConversionsTest() throws Exception { + // Coverage tests + Properties testSystemProps = new Properties(System.getProperties()); + testSystemProps.setProperty("java.specification.version", "1.7"); + System.setProperties(testSystemProps); + PropAccess pa = new PropAccess("AFT_LATITUDE=1", "AFT_LONGITUDE=1", "cadi_protocols=TLSv1.2"); + } + + @Test + public void logTest() throws Exception { + // Coverage tests + PropAccess pa = new PropAccess(); + + pa.log(Level.DEBUG); + pa.printf(Level.DEBUG, "not a real format string"); + + pa.setLogLevel(Level.DEBUG); + pa.log(Level.DEBUG); + pa.log(Level.DEBUG, 1, " ", null, ""); + pa.log(Level.DEBUG, "This is a string", "This is another"); + pa.set(new LogIt() { + @Override public void push(Level level, Object ... elements) {} + }); + try { + pa.log(new Exception("This exception was thrown intentionally, please ignore it")); + } catch(Exception e) { + fail("Should have thrown an exception"); + } + } + + @Test + public void classLoaderTest() { + PropAccess pa = new PropAccess(); + assertThat(pa.classLoader(), instanceOf(ClassLoader.class)); + } + + @Test + public void encryptionTest() throws Exception { + PropAccess pa = new PropAccess(); + String plainText = "This is a secret message"; + String secret_message = pa.encrypt(plainText); + String modified = secret_message.substring(4); + // Plenty of assertions to hit all branches + assertThat(pa.decrypt(secret_message, false), is(plainText)); + assertThat(pa.decrypt(null, false), is(nullValue())); + assertThat(pa.decrypt(modified, true), is(plainText)); + assertThat(pa.decrypt(modified, false), is(modified)); + } + + @Test + public void setPropertyTest() { + PropAccess pa = new PropAccess(); + pa.setProperty("test", null); + String prop = "New Property"; + String val ="And it's faithful value"; + pa.setProperty(prop, val); + + assertThat(pa.getProperty(prop), is(val)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java index 8531e1d1..e7689eae 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java @@ -47,58 +47,58 @@ import javax.servlet.ServletContext; @SuppressWarnings("unused") public class JU_ServletContextAccess { - private FilterConfig filter_mock; - Enumeration<String> enumeration; - - private class CustomEnumeration implements Enumeration<String> { - private int idx = 0; - private final String[] elements = {"This", "is", "a", "test"}; - @Override - public String nextElement() { - return idx >= elements.length ? null : elements[idx++]; - } - @Override - public boolean hasMoreElements() { - return idx < elements.length; - } - } + private FilterConfig filter_mock; + Enumeration<String> enumeration; + + private class CustomEnumeration implements Enumeration<String> { + private int idx = 0; + private final String[] elements = {"This", "is", "a", "test"}; + @Override + public String nextElement() { + return idx >= elements.length ? null : elements[idx++]; + } + @Override + public boolean hasMoreElements() { + return idx < elements.length; + } + } - @Before - public void setup() { - enumeration = new CustomEnumeration(); - filter_mock = mock(FilterConfig.class); - when(filter_mock.getInitParameterNames()).thenReturn(enumeration); - } - - @Test - public void ConstructorTest() throws Exception { - ServletContextAccess sca = new ServletContextAccess(filter_mock); - } + @Before + public void setup() { + enumeration = new CustomEnumeration(); + filter_mock = mock(FilterConfig.class); + when(filter_mock.getInitParameterNames()).thenReturn(enumeration); + } + + @Test + public void ConstructorTest() throws Exception { + ServletContextAccess sca = new ServletContextAccess(filter_mock); + } - @Test - public void logTest() throws Exception { - ServletContext sc_mock = mock(ServletContext.class); - when(filter_mock.getServletContext()).thenReturn(sc_mock); - ServletContextAccess sca = new ServletContextAccess(filter_mock); + @Test + public void logTest() throws Exception { + ServletContext sc_mock = mock(ServletContext.class); + when(filter_mock.getServletContext()).thenReturn(sc_mock); + ServletContextAccess sca = new ServletContextAccess(filter_mock); - sca.log(Level.DEBUG); + sca.log(Level.DEBUG); - sca.setLogLevel(Level.DEBUG); - sca.log(Level.DEBUG); + sca.setLogLevel(Level.DEBUG); + sca.log(Level.DEBUG); - try { - sca.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { - fail("Should have thrown an exception"); - } - } + try { + sca.log(new Exception("This exception was thrown intentionally, please ignore it")); + } catch(Exception e) { + fail("Should have thrown an exception"); + } + } - @Test - public void contextTest() { - ServletContext sc_mock = mock(ServletContext.class); - when(filter_mock.getServletContext()).thenReturn(sc_mock); - ServletContextAccess sca = new ServletContextAccess(filter_mock); - assertThat(sca.context(), instanceOf(ServletContext.class)); - } + @Test + public void contextTest() { + ServletContext sc_mock = mock(ServletContext.class); + when(filter_mock.getServletContext()).thenReturn(sc_mock); + ServletContextAccess sca = new ServletContextAccess(filter_mock); + assertThat(sca.context(), instanceOf(ServletContext.class)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java index 753451ed..abbc9e90 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Symm.java @@ -37,176 +37,176 @@ import org.onap.aaf.cadi.PropAccess; import org.onap.aaf.cadi.Symm; public class JU_Symm { - private Symm defaultSymm; - - private ByteArrayOutputStream outStream; - - @Before - public void setup() throws Exception { - defaultSymm = new Symm( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() - ,76, "Use default!" ,true); - outStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - } - - @After - public void tearDown() { - System.setOut(System.out); - } - - @Test - public void constructorTest() throws Exception { - Symm myCustomSymm = new Symm( - "ACEGIKMOQSUWYacegikmoqsuwy02468+/".toCharArray(), 76, "Default", true); - Field convert_field = Symm.class.getDeclaredField("convert"); - convert_field.setAccessible(true); - - Class<?> Unordered_class = Class.forName("org.onap.aaf.cadi.Symm$Unordered"); - assertThat(convert_field.get(myCustomSymm), instanceOf(Unordered_class)); - } - - @SuppressWarnings("unused") - @Test - public void copyTest() throws Exception { - Symm copy = Symm.base64.copy(76); - } - - @SuppressWarnings("deprecation") - @Test - public void deprecatedTest() { - assertEquals(Symm.base64(), Symm.base64); - assertEquals(Symm.base64noSplit(), Symm.base64noSplit); - assertEquals(Symm.base64url(), Symm.base64url); - assertEquals(Symm.baseCrypt(), Symm.encrypt); - } - - @Test - public void encodeDecodeStringTest() throws Exception { - String orig = "hello"; - String b64encrypted = Symm.base64.encode(orig); - assertEquals(Symm.base64.decode(b64encrypted), orig); - - String defaultEnrypted = defaultSymm.encode(orig); - assertEquals(defaultSymm.decode(defaultEnrypted), orig); - } - - @Test - public void encodeDecodeByteArrayTest() throws Exception { - String orig = "hello"; - byte[] b64encrypted = Symm.base64.encode(orig.getBytes()); - assertEquals(new String(Symm.base64.decode(b64encrypted)), orig); - - byte[] empty = null; - assertTrue(Arrays.equals(Symm.base64.encode(empty), new byte[0])); - } - - @Test - public void encodeDecodeStringToStreamTest() throws Exception { - String orig = "I'm a password, really"; - String b64encrypted; - String output; - - ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); - Symm.base64.encode(orig, baosEncrypt); - b64encrypted = new String(baosEncrypt.toByteArray()); - - ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); - Symm.base64.decode(b64encrypted, baosDecrypt); - output = new String(baosDecrypt.toByteArray()); - - assertEquals(orig, output); - } - - @Test - public void encryptDecryptStreamWithPrefixTest() throws Exception { - String orig = "I'm a password, really"; - byte[] b64encrypted; - String output; - - byte[] prefix = "enc:".getBytes(); - - ByteArrayInputStream baisEncrypt = new ByteArrayInputStream(orig.getBytes()); - ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); - Symm.base64.encode(baisEncrypt, baosEncrypt, prefix); - - b64encrypted = baosEncrypt.toByteArray(); - - ByteArrayInputStream baisDecrypt = new ByteArrayInputStream(b64encrypted); - ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); - Symm.base64.decode(baisDecrypt, baosDecrypt, prefix.length); - - output = new String(baosDecrypt.toByteArray()); - assertEquals(orig, output); - } - - @Test - public void randomGenTest() { - // Ian - There really isn't a great way to test for randomness... - String prev = null; - for (int i = 0; i < 10; i++) { - String current = Symm.randomGen(100); - if (current.equals(prev)) { - fail("I don't know how, but you generated the exact same random string twice in a row"); - } - prev = current; - } - assertTrue(true); - } - - @Test - public void obtainTest() throws Exception { - Symm symm = Symm.base64.obtain(); - - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - } - - @Test - public void InputStreamObtainTest() throws Exception { - byte[] keygen = Symm.keygen(); - - Symm symm = Symm.obtain(new ByteArrayInputStream(keygen)); - - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - } - - @Test - public void StringObtainTest() throws Exception { - byte[] keygen = Symm.keygen(); - - Symm symm = Symm.obtain(new String(keygen)); - - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - } - - @Test - public void AccessObtainTest() throws Exception { - PropAccess pa = new PropAccess("cadi_keyfile=src/test/resources/keyfile"); - Symm symm = Symm.obtain(pa); - String orig ="Another Password, please"; - String encrypted = symm.enpass(orig); - String decrypted = symm.depass(encrypted); - assertEquals(orig, decrypted); - - try { - PropAccess badPa = mock(PropAccess.class); - when(badPa.getProperty("cadi_keyfile", null)).thenReturn("not_a_real_file.txt"); - symm = Symm.obtain(badPa); - fail("Should have thrown an exception"); - } catch (CadiException e) { - assertTrue(e.getMessage().contains("ERROR: ")); - assertTrue(e.getMessage().contains("not_a_real_file.txt")); - assertTrue(e.getMessage().contains(" does not exist!")); - } - } - + private Symm defaultSymm; + + private ByteArrayOutputStream outStream; + + @Before + public void setup() throws Exception { + defaultSymm = new Symm( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() + ,76, "Use default!" ,true); + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void constructorTest() throws Exception { + Symm myCustomSymm = new Symm( + "ACEGIKMOQSUWYacegikmoqsuwy02468+/".toCharArray(), 76, "Default", true); + Field convert_field = Symm.class.getDeclaredField("convert"); + convert_field.setAccessible(true); + + Class<?> Unordered_class = Class.forName("org.onap.aaf.cadi.Symm$Unordered"); + assertThat(convert_field.get(myCustomSymm), instanceOf(Unordered_class)); + } + + @SuppressWarnings("unused") + @Test + public void copyTest() throws Exception { + Symm copy = Symm.base64.copy(76); + } + + @SuppressWarnings("deprecation") + @Test + public void deprecatedTest() { + assertEquals(Symm.base64(), Symm.base64); + assertEquals(Symm.base64noSplit(), Symm.base64noSplit); + assertEquals(Symm.base64url(), Symm.base64url); + assertEquals(Symm.baseCrypt(), Symm.encrypt); + } + + @Test + public void encodeDecodeStringTest() throws Exception { + String orig = "hello"; + String b64encrypted = Symm.base64.encode(orig); + assertEquals(Symm.base64.decode(b64encrypted), orig); + + String defaultEnrypted = defaultSymm.encode(orig); + assertEquals(defaultSymm.decode(defaultEnrypted), orig); + } + + @Test + public void encodeDecodeByteArrayTest() throws Exception { + String orig = "hello"; + byte[] b64encrypted = Symm.base64.encode(orig.getBytes()); + assertEquals(new String(Symm.base64.decode(b64encrypted)), orig); + + byte[] empty = null; + assertTrue(Arrays.equals(Symm.base64.encode(empty), new byte[0])); + } + + @Test + public void encodeDecodeStringToStreamTest() throws Exception { + String orig = "I'm a password, really"; + String b64encrypted; + String output; + + ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); + Symm.base64.encode(orig, baosEncrypt); + b64encrypted = new String(baosEncrypt.toByteArray()); + + ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); + Symm.base64.decode(b64encrypted, baosDecrypt); + output = new String(baosDecrypt.toByteArray()); + + assertEquals(orig, output); + } + + @Test + public void encryptDecryptStreamWithPrefixTest() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + byte[] prefix = "enc:".getBytes(); + + ByteArrayInputStream baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); + Symm.base64.encode(baisEncrypt, baosEncrypt, prefix); + + b64encrypted = baosEncrypt.toByteArray(); + + ByteArrayInputStream baisDecrypt = new ByteArrayInputStream(b64encrypted); + ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); + Symm.base64.decode(baisDecrypt, baosDecrypt, prefix.length); + + output = new String(baosDecrypt.toByteArray()); + assertEquals(orig, output); + } + + @Test + public void randomGenTest() { + // Ian - There really isn't a great way to test for randomness... + String prev = null; + for (int i = 0; i < 10; i++) { + String current = Symm.randomGen(100); + if (current.equals(prev)) { + fail("I don't know how, but you generated the exact same random string twice in a row"); + } + prev = current; + } + assertTrue(true); + } + + @Test + public void obtainTest() throws Exception { + Symm symm = Symm.base64.obtain(); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void InputStreamObtainTest() throws Exception { + byte[] keygen = Symm.keygen(); + + Symm symm = Symm.obtain(new ByteArrayInputStream(keygen)); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void StringObtainTest() throws Exception { + byte[] keygen = Symm.keygen(); + + Symm symm = Symm.obtain(new String(keygen)); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void AccessObtainTest() throws Exception { + PropAccess pa = new PropAccess("cadi_keyfile=src/test/resources/keyfile"); + Symm symm = Symm.obtain(pa); + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + + try { + PropAccess badPa = mock(PropAccess.class); + when(badPa.getProperty("cadi_keyfile", null)).thenReturn("not_a_real_file.txt"); + symm = Symm.obtain(badPa); + fail("Should have thrown an exception"); + } catch (CadiException e) { + assertTrue(e.getMessage().contains("ERROR: ")); + assertTrue(e.getMessage().contains("not_a_real_file.txt")); + assertTrue(e.getMessage().contains(" does not exist!")); + } + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java index 511c6ee3..c6070d7d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_TrustChecker.java @@ -29,9 +29,9 @@ import org.onap.aaf.cadi.TrustChecker; public class JU_TrustChecker { - @Test - public void noTrustTests() { - assertThat(TrustChecker.NOTRUST.mayTrust(null, null), is(nullValue())); - TrustChecker.NOTRUST.setLur(null); - } + @Test + public void noTrustTests() { + assertThat(TrustChecker.NOTRUST.mayTrust(null, null), is(nullValue())); + TrustChecker.NOTRUST.setLur(null); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java index 2d5ba8d2..857170a7 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_User.java @@ -45,141 +45,141 @@ import org.onap.aaf.cadi.lur.LocalPermission; public class JU_User { - private final Long SECOND = 1000L; - private final String name = "Fakey McFake"; - private final String cred = "Fake credentials"; - - private Field perms_field; - private Field count_field; - - @Mock - private Principal principal; - - @Mock - private LocalPermission permission; - @Mock - private LocalPermission permission2; - - @Before - public void setup() throws NoSuchFieldException, SecurityException { - MockitoAnnotations.initMocks(this); - - when(principal.getName()).thenReturn("Principal"); - - when(permission.getKey()).thenReturn("NewKey"); - when(permission.match(permission)).thenReturn(true); - - when(permission2.getKey()).thenReturn("NewKey2"); - when(permission2.match(permission)).thenReturn(false); - - perms_field = User.class.getDeclaredField("perms"); - perms_field.setAccessible(true); - - count_field = User.class.getDeclaredField("count"); - count_field.setAccessible(true); - } - - @Test - public void constructorPrincipalTest() throws IllegalArgumentException, IllegalAccessException { - User<Permission> user = new User<Permission>(principal); - assertThat(user.name, is(principal.getName())); - assertThat(user.principal, is(principal)); - assertThat(user.permExpires(), is(Long.MAX_VALUE)); - assertThat((int)count_field.get(user), is(0)); - } - - @Test - public void constructorNameCredTest() throws IllegalArgumentException, IllegalAccessException { - User<Permission> user = new User<Permission>(name, cred.getBytes()); - assertThat(user.name, is(name)); - assertThat(user.principal, is(nullValue())); - assertThat(user.permExpires(), is(Long.MAX_VALUE)); - assertThat((int)count_field.get(user), is(0)); - assertThat(user.getCred(), is(cred.getBytes())); - } - - @Test - public void constructorPrincipalIntervalTest() throws IllegalArgumentException, IllegalAccessException { - User<Permission> user = new User<Permission>(principal, 61 * SECOND); - Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; - assertThat(user.name, is(principal.getName())); - assertThat(user.principal, is(principal)); - assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); - assertThat((int)count_field.get(user), is(0)); - } - - @Test - public void constructorNameCredIntervalTest() throws IllegalArgumentException, IllegalAccessException { - String name = "Fakey McFake"; - User<Permission> user = new User<Permission>(name, cred.getBytes(), 61 * SECOND); - Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; - assertThat(user.name, is(name)); - assertThat(user.principal, is(nullValue())); - assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); - assertThat((int)count_field.get(user), is(0)); - assertThat(user.getCred(), is(cred.getBytes())); - } - - @Test - public void countCheckTest() throws IllegalArgumentException, IllegalAccessException { - User<Permission> user = new User<Permission>(principal); - user.resetCount(); - assertThat((int)count_field.get(user), is(0)); - user.incCount(); - assertThat((int)count_field.get(user), is(1)); - user.incCount(); - assertThat((int)count_field.get(user), is(2)); - user.resetCount(); - assertThat((int)count_field.get(user), is(0)); - } - - @Test - public void permTest() throws InterruptedException, IllegalArgumentException, IllegalAccessException { - User<Permission> user = new User<Permission>(principal); - assertThat(user.permExpires(), is(Long.MAX_VALUE)); - user.renewPerm(); - Thread.sleep(1); // Let it expire - assertThat(user.permExpired(), is(true)); - - user = new User<Permission>(principal,100); - assertTrue(user.noPerms()); - user.add(permission); - assertFalse(user.permsUnloaded()); - assertFalse(user.noPerms()); - user.setNoPerms(); - assertThat(user.permExpired(), is(false)); - assertTrue(user.permsUnloaded()); - assertTrue(user.noPerms()); - perms_field.set(user, null); - assertTrue(user.permsUnloaded()); - assertTrue(user.noPerms()); - } - - @Test - public void addValuesToNewMapTest() { - User<Permission> user = new User<Permission>(principal); - Map<String, Permission> newMap = new HashMap<>(); - - assertFalse(user.contains(permission)); - - user.add(newMap, permission); - user.setMap(newMap); - - assertTrue(user.contains(permission)); - - List<Permission> sink = new ArrayList<>(); - user.copyPermsTo(sink); - - assertThat(sink.size(), is(1)); - assertTrue(sink.contains(permission)); - - assertThat(user.toString(), is("Principal|:NewKey")); - - user.add(newMap, permission2); - user.setMap(newMap); - assertFalse(user.contains(permission2)); - - assertThat(user.toString(), is("Principal|:NewKey2,NewKey")); - } - + private final Long SECOND = 1000L; + private final String name = "Fakey McFake"; + private final String cred = "Fake credentials"; + + private Field perms_field; + private Field count_field; + + @Mock + private Principal principal; + + @Mock + private LocalPermission permission; + @Mock + private LocalPermission permission2; + + @Before + public void setup() throws NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + when(principal.getName()).thenReturn("Principal"); + + when(permission.getKey()).thenReturn("NewKey"); + when(permission.match(permission)).thenReturn(true); + + when(permission2.getKey()).thenReturn("NewKey2"); + when(permission2.match(permission)).thenReturn(false); + + perms_field = User.class.getDeclaredField("perms"); + perms_field.setAccessible(true); + + count_field = User.class.getDeclaredField("count"); + count_field.setAccessible(true); + } + + @Test + public void constructorPrincipalTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal); + assertThat(user.name, is(principal.getName())); + assertThat(user.principal, is(principal)); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void constructorNameCredTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(name, cred.getBytes()); + assertThat(user.name, is(name)); + assertThat(user.principal, is(nullValue())); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + assertThat((int)count_field.get(user), is(0)); + assertThat(user.getCred(), is(cred.getBytes())); + } + + @Test + public void constructorPrincipalIntervalTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal, 61 * SECOND); + Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; + assertThat(user.name, is(principal.getName())); + assertThat(user.principal, is(principal)); + assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void constructorNameCredIntervalTest() throws IllegalArgumentException, IllegalAccessException { + String name = "Fakey McFake"; + User<Permission> user = new User<Permission>(name, cred.getBytes(), 61 * SECOND); + Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; + assertThat(user.name, is(name)); + assertThat(user.principal, is(nullValue())); + assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); + assertThat((int)count_field.get(user), is(0)); + assertThat(user.getCred(), is(cred.getBytes())); + } + + @Test + public void countCheckTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal); + user.resetCount(); + assertThat((int)count_field.get(user), is(0)); + user.incCount(); + assertThat((int)count_field.get(user), is(1)); + user.incCount(); + assertThat((int)count_field.get(user), is(2)); + user.resetCount(); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void permTest() throws InterruptedException, IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + user.renewPerm(); + Thread.sleep(1); // Let it expire + assertThat(user.permExpired(), is(true)); + + user = new User<Permission>(principal,100); + assertTrue(user.noPerms()); + user.add(permission); + assertFalse(user.permsUnloaded()); + assertFalse(user.noPerms()); + user.setNoPerms(); + assertThat(user.permExpired(), is(false)); + assertTrue(user.permsUnloaded()); + assertTrue(user.noPerms()); + perms_field.set(user, null); + assertTrue(user.permsUnloaded()); + assertTrue(user.noPerms()); + } + + @Test + public void addValuesToNewMapTest() { + User<Permission> user = new User<Permission>(principal); + Map<String, Permission> newMap = new HashMap<>(); + + assertFalse(user.contains(permission)); + + user.add(newMap, permission); + user.setMap(newMap); + + assertTrue(user.contains(permission)); + + List<Permission> sink = new ArrayList<>(); + user.copyPermsTo(sink); + + assertThat(sink.size(), is(1)); + assertTrue(sink.contains(permission)); + + assertThat(user.toString(), is("Principal|:NewKey")); + + user.add(newMap, permission2); + user.setMap(newMap); + assertFalse(user.contains(permission2)); + + assertThat(user.toString(), is("Principal|:NewKey2,NewKey")); + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java index 62114189..f8905bb5 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Chmod.java @@ -37,39 +37,39 @@ import org.onap.aaf.cadi.util.Chmod; public class JU_Chmod { - private File file; - private String filePath; + private File file; + private String filePath; - @Before - public void setup() throws IOException { - file = File.createTempFile("chmod_test", ""); - filePath = file.getAbsolutePath(); - } + @Before + public void setup() throws IOException { + file = File.createTempFile("chmod_test", ""); + filePath = file.getAbsolutePath(); + } - @After - public void tearDown() { - file.delete(); - } + @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 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 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--------")); - } + @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/util/test/JU_FQI.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_FQI.java index bcd2f776..3daa6cb7 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_FQI.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_FQI.java @@ -30,15 +30,15 @@ import org.onap.aaf.cadi.util.FQI; public class JU_FQI { - @Test - public void reverseDomainTest() { - assertThat(FQI.reverseDomain("user@att.com"), is("com.att")); - } + @Test + public void reverseDomainTest() { + assertThat(FQI.reverseDomain("user@att.com"), is("com.att")); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - FQI fqi = new FQI(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + FQI fqi = new FQI(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java index da3557cb..b3d7797c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_JsonOutputStream.java @@ -36,58 +36,58 @@ import org.onap.aaf.cadi.util.JsonOutputStream; public class JU_JsonOutputStream { - private JsonOutputStream jos; - - @Before - public void setup() { - jos = new JsonOutputStream(new ByteArrayOutputStream()); - } - - @Test - public void constructorTest() { - jos = new JsonOutputStream(System.out); - jos = new JsonOutputStream(System.err); - } - - @Test - public void writeTest() throws IOException { - byte[] json = ("{" + - "name: user," + - "password: pass," + - "contact: {" + - "email: user@att.com," + - "phone: 555-5555" + - "}," + - "list: [" + - "item1," + - "item2" + - "],[],{}," + - "list:" + - "[" + - "item1," + - "item2" + - "]" + - "}").getBytes(); - jos.write(json); - } - - @Test - public void resetIndentTest() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - Field indentField = JsonOutputStream.class.getDeclaredField("indent"); - indentField.setAccessible(true); - - assertThat((int)indentField.get(jos), is(0)); - jos.resetIndent(); - assertThat((int)indentField.get(jos), is(1)); - } - - @Test - public void coverageTest() throws IOException { - jos.flush(); - jos.close(); - - jos = new JsonOutputStream(System.out); - jos.close(); - } + private JsonOutputStream jos; + + @Before + public void setup() { + jos = new JsonOutputStream(new ByteArrayOutputStream()); + } + + @Test + public void constructorTest() { + jos = new JsonOutputStream(System.out); + jos = new JsonOutputStream(System.err); + } + + @Test + public void writeTest() throws IOException { + byte[] json = ("{" + + "name: user," + + "password: pass," + + "contact: {" + + "email: user@att.com," + + "phone: 555-5555" + + "}," + + "list: [" + + "item1," + + "item2" + + "],[],{}," + + "list:" + + "[" + + "item1," + + "item2" + + "]" + + "}").getBytes(); + jos.write(json); + } + + @Test + public void resetIndentTest() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + Field indentField = JsonOutputStream.class.getDeclaredField("indent"); + indentField.setAccessible(true); + + assertThat((int)indentField.get(jos), is(0)); + jos.resetIndent(); + assertThat((int)indentField.get(jos), is(1)); + } + + @Test + public void coverageTest() throws IOException { + jos.flush(); + jos.close(); + + jos = new JsonOutputStream(System.out); + jos.close(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java index ea743430..ba03b6b1 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_MaskFormatException.java @@ -30,15 +30,15 @@ import org.onap.aaf.cadi.util.MaskFormatException; public class JU_MaskFormatException { - @Test - public void throwsTest() { - String errorMessage = "This is a MaskFormatException"; - try { - throw new MaskFormatException(errorMessage); - } catch (Exception e) { - assertThat(e.getMessage(), is(errorMessage)); - assertTrue(e instanceof MaskFormatException); - } - } + @Test + public void throwsTest() { + String errorMessage = "This is a MaskFormatException"; + try { + throw new MaskFormatException(errorMessage); + } catch (Exception e) { + assertThat(e.getMessage(), is(errorMessage)); + assertTrue(e instanceof MaskFormatException); + } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java index 403f1f1e..f2e393d9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_NetMask.java @@ -27,39 +27,39 @@ import org.onap.aaf.cadi.util.NetMask; public class JU_NetMask { - @Test - public void deriveTest() { - String test = "test"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } + @Test + public void deriveTest() { + String test = "test"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } - @Test - public void deriveTest2() { - String test = "1.2.3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest3() { - String test = "1.2.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest4() { - String test = "1.3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest5() { - String test = "2.3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } - - @Test - public void deriveTest6() { - String test = "3.4"; - assertEquals(NetMask.derive(test.getBytes()), 0); - } + @Test + public void deriveTest2() { + String test = "1.2.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest3() { + String test = "1.2.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest4() { + String test = "1.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest5() { + String test = "2.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest6() { + String test = "3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java index b9f0e997..5862d792 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Pool.java @@ -33,127 +33,127 @@ 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<>(); - 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")); - } + 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<>(); + 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/util/test/JU_Split.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Split.java index 12be4e15..8977a4f4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Split.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Split.java @@ -28,86 +28,86 @@ import org.onap.aaf.cadi.util.Split; public class JU_Split { - @Test - public void splitTest() { - String[] output = Split.split('c', "ctestctc", 0, "ctestctc".length()); - assertThat(output.length, is(4)); - assertThat(output[0], is("")); - assertThat(output[1], is("test")); - assertThat(output[2], is("t")); - assertThat(output[3], is("")); - - output = Split.split('c', "ctestctc", 0, 4); - assertThat(output.length, is(2)); - assertThat(output[0], is("")); - assertThat(output[1], is("tes")); + @Test + public void splitTest() { + String[] output = Split.split('c', "ctestctc", 0, "ctestctc".length()); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("test")); + assertThat(output[2], is("t")); + assertThat(output[3], is("")); + + output = Split.split('c', "ctestctc", 0, 4); + assertThat(output.length, is(2)); + assertThat(output[0], is("")); + assertThat(output[1], is("tes")); output = Split.split('c', "test", 0, "test".length()); - assertThat(output.length, is(1)); - assertThat(output[0], is("test")); + assertThat(output.length, is(1)); + assertThat(output[0], is("test")); - assertThat(Split.split('c', null, 0, 0).length, is(0)); + assertThat(Split.split('c', null, 0, 0).length, is(0)); // Test with fewer arguments - output = Split.split('c', "ctestctc"); - assertThat(output.length, is(4)); - assertThat(output[0], is("")); - assertThat(output[1], is("test")); - assertThat(output[2], is("t")); - assertThat(output[3], is("")); - } - - @Test - public void splitTrimTest() { - String[] output = Split.splitTrim('c', " cte stc ctc ", 0, " cte stc ctc ".length()); - assertThat(output.length, is(5)); - assertThat(output[0], is("")); - assertThat(output[1], is("te st")); - assertThat(output[2], is("")); - assertThat(output[3], is("t")); - assertThat(output[4], is("")); - - output = Split.splitTrim('c', " cte stc ctc ", 0, 5); - assertThat(output.length, is(2)); - assertThat(output[0], is("")); - assertThat(output[1], is("te")); - - assertThat(Split.splitTrim('c', " te st ", 0, " te st ".length())[0], is("te st")); + output = Split.split('c', "ctestctc"); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("test")); + assertThat(output[2], is("t")); + assertThat(output[3], is("")); + } + + @Test + public void splitTrimTest() { + String[] output = Split.splitTrim('c', " cte stc ctc ", 0, " cte stc ctc ".length()); + assertThat(output.length, is(5)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + assertThat(output[3], is("t")); + assertThat(output[4], is("")); + + output = Split.splitTrim('c', " cte stc ctc ", 0, 5); + assertThat(output.length, is(2)); + assertThat(output[0], is("")); + assertThat(output[1], is("te")); + + assertThat(Split.splitTrim('c', " te st ", 0, " te st ".length())[0], is("te st")); assertThat(Split.splitTrim('c', null, 0, 0).length, is(0)); - // Test with 2 arguments - output = Split.splitTrim('c', " cte stc ctc "); - assertThat(output.length, is(5)); - assertThat(output[0], is("")); - assertThat(output[1], is("te st")); - assertThat(output[2], is("")); - assertThat(output[3], is("t")); - assertThat(output[4], is("")); - - // Tests with 1 argument - output = Split.splitTrim('c', " cte stc ctc ", 1); - assertThat(output.length, is(1)); - assertThat(output[0], is("cte stc ctc")); - - output = Split.splitTrim('c', "testctest2", 2); - assertThat(output.length, is(2)); - assertThat(output[0], is("test")); - assertThat(output[1], is("test2")); - - output = Split.splitTrim('c', " cte stc ctc ", 4); - assertThat(output.length, is(4)); - assertThat(output[0], is("")); - assertThat(output[1], is("te st")); - assertThat(output[2], is("")); - - assertThat(Split.splitTrim('c', null, 0).length, is(0)); - } - - @Test - public void coverageTest() { - @SuppressWarnings("unused") - Split split = new Split(); - } + // Test with 2 arguments + output = Split.splitTrim('c', " cte stc ctc "); + assertThat(output.length, is(5)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + assertThat(output[3], is("t")); + assertThat(output[4], is("")); + + // Tests with 1 argument + output = Split.splitTrim('c', " cte stc ctc ", 1); + assertThat(output.length, is(1)); + assertThat(output[0], is("cte stc ctc")); + + output = Split.splitTrim('c', "testctest2", 2); + assertThat(output.length, is(2)); + assertThat(output[0], is("test")); + assertThat(output[1], is("test2")); + + output = Split.splitTrim('c', " cte stc ctc ", 4); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + + assertThat(Split.splitTrim('c', null, 0).length, is(0)); + } + + @Test + public void coverageTest() { + @SuppressWarnings("unused") + Split split = new Split(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java index 712b9891..5bc1be21 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_SubStandardConsole.java @@ -36,90 +36,90 @@ import org.onap.aaf.cadi.util.SubStandardConsole; public class JU_SubStandardConsole { - private String inputString = "An input string"; - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream errStream; - private String lineSeparator = System.lineSeparator(); - - @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" + lineSeparator, ">>> "); - assertThat(output, is(inputString)); - assertThat(outStream.toString(), is(">>> " + lineSeparator)); - } - - @Test - public void readLineTest2() { - byte[] input = inputString.getBytes(); - System.setIn(new ByteArrayInputStream(input)); - SubStandardConsole ssc = new SubStandardConsole(); - String output = ssc.readLine("%s %s" + lineSeparator, ">>> ", "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" + lineSeparator, ">>> "); - assertThat(output, is(">>> ")); - assertThat(outStream.toString(), is(">>> " + lineSeparator)); - } - - @Test - public void readPasswordTest() { - byte[] input = inputString.getBytes(); - System.setIn(new ByteArrayInputStream(input)); - SubStandardConsole ssc = new SubStandardConsole(); - char[] output = ssc.readPassword("%s" + lineSeparator, ">>> "); - System.out.println(output); - assertThat(output, is(inputString.toCharArray())); - assertThat(outStream.toString(), is(">>> " + lineSeparator + "An input string" + lineSeparator)); - } - - @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..." + lineSeparator)); + private String inputString = "An input string"; + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + private String lineSeparator = System.lineSeparator(); + + @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" + lineSeparator, ">>> "); + assertThat(output, is(inputString)); + assertThat(outStream.toString(), is(">>> " + lineSeparator)); + } + + @Test + public void readLineTest2() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s %s" + lineSeparator, ">>> ", "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" + lineSeparator, ">>> "); + assertThat(output, is(">>> ")); + assertThat(outStream.toString(), is(">>> " + lineSeparator)); + } + + @Test + public void readPasswordTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + char[] output = ssc.readPassword("%s" + lineSeparator, ">>> "); + System.out.println(output); + assertThat(output, is(inputString.toCharArray())); + assertThat(outStream.toString(), is(">>> " + lineSeparator + "An input string" + lineSeparator)); + } + + @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..." + lineSeparator)); errStream.reset(); - assertThat(ssc.readPassword("").length, is(0)); - assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); - } + assertThat(ssc.readPassword("").length, is(0)); + assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java index 40f88a3a..025e3e67 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_TheConsole.java @@ -27,8 +27,8 @@ import org.onap.aaf.cadi.util.TheConsole; public class JU_TheConsole { - @Test - public void implemented(){ - assertEquals(TheConsole.implemented(),false); - } + @Test + public void implemented(){ + assertEquals(TheConsole.implemented(),false); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java index 21f8c21b..9e4cd88d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_UserChainManip.java @@ -29,39 +29,39 @@ import org.onap.aaf.cadi.util.UserChainManip; public class JU_UserChainManip { - @Test - public void build(){ - UserChain.Protocol baseAuth=UserChain.Protocol.BasicAuth; - StringBuilder sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, true); - assertThat(sb.toString(), is("app:id:BasicAuth:AS")); + @Test + public void build(){ + UserChain.Protocol baseAuth=UserChain.Protocol.BasicAuth; + StringBuilder sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, true); + assertThat(sb.toString(), is("app:id:BasicAuth:AS")); - // for coverage - sb = UserChainManip.build(sb, "app", "id", baseAuth, true); - assertThat(sb.toString(), is("app:id:BasicAuth:AS,app:id:BasicAuth")); + // for coverage + sb = UserChainManip.build(sb, "app", "id", baseAuth, true); + assertThat(sb.toString(), is("app:id:BasicAuth:AS,app:id:BasicAuth")); - sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, false); - assertThat(sb.toString(), is("app:id:BasicAuth")); - } + sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, false); + assertThat(sb.toString(), is("app:id:BasicAuth")); + } - @Test - public void idToNSTEST() { - assertThat(UserChainManip.idToNS(null), is("")); - assertThat(UserChainManip.idToNS(""), is("")); - assertThat(UserChainManip.idToNS("something"), is("")); - assertThat(UserChainManip.idToNS("something@@"), is("")); - assertThat(UserChainManip.idToNS("something@@."), is("")); - assertThat(UserChainManip.idToNS("something@com"), is("com")); - assertThat(UserChainManip.idToNS("something@random.com"), is("com.random")); - assertThat(UserChainManip.idToNS("@random.com"), is("com.random")); - assertThat(UserChainManip.idToNS("something@random.com."), is("com.random")); - assertThat(UserChainManip.idToNS("something@..random...com..."), is("com.random")); - assertThat(UserChainManip.idToNS("something@this.random.com"), is("com.random.this")); - } + @Test + public void idToNSTEST() { + assertThat(UserChainManip.idToNS(null), is("")); + assertThat(UserChainManip.idToNS(""), is("")); + assertThat(UserChainManip.idToNS("something"), is("")); + assertThat(UserChainManip.idToNS("something@@"), is("")); + assertThat(UserChainManip.idToNS("something@@."), is("")); + assertThat(UserChainManip.idToNS("something@com"), is("com")); + assertThat(UserChainManip.idToNS("something@random.com"), is("com.random")); + assertThat(UserChainManip.idToNS("@random.com"), is("com.random")); + assertThat(UserChainManip.idToNS("something@random.com."), is("com.random")); + assertThat(UserChainManip.idToNS("something@..random...com..."), is("com.random")); + assertThat(UserChainManip.idToNS("something@this.random.com"), is("com.random.this")); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - UserChainManip ucm = new UserChainManip(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + UserChainManip ucm = new UserChainManip(); + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java index 551f725d..3eb43df4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java @@ -29,120 +29,120 @@ import org.junit.Test; import org.onap.aaf.cadi.util.Vars; public class JU_Vars { - - @Test - public void coverage() { - @SuppressWarnings("unused") - Vars my_nonstatic_object_for_coverage = new Vars(); - } + + @Test + public void coverage() { + @SuppressWarnings("unused") + Vars my_nonstatic_object_for_coverage = new Vars(); + } - @Test - public void convert() { - String test = "test"; - List<String> list = new ArrayList<>(); - list.add("method"); - assertEquals(Vars.convert(test, list), test); - } + @Test + public void convert() { + String test = "test"; + List<String> list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert(test, list), test); + } - @Test - public void convertTest1() { - List<String> list = new ArrayList<>(); - list.add("method"); - assertEquals(Vars.convert("test", list), "test"); - } + @Test + public void convertTest1() { + List<String> list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert("test", list), "test"); + } - @Test - public void convertTest2() { - List<String> list = new ArrayList<>(); - list.add("method"); - assertEquals(Vars.convert("test", list), "test"); - } + @Test + public void convertTest2() { + List<String> list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert("test", list), "test"); + } - @Test - public void test() { - StringBuilder holder = new StringBuilder(); - String str,bstr; - assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "a","b")); - assertEquals("set a to b",holder.toString()); - assertEquals(str,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "a","b")); - assertEquals("set a to b",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "a","b")); - - holder.setLength(0); - assertEquals(str = "%1=%2",Vars.convert(holder,str, "a","b")); - assertEquals("a=b",holder.toString()); - assertEquals(str,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="%s=%s", "a","b")); - assertEquals("a=b",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "a","b")); - - holder.setLength(0); - assertEquals(str = "%1%2",Vars.convert(holder,str, "a","b")); - assertEquals("ab",holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="%s%s", "a","b")); - assertEquals("ab",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "a","b")); + @Test + public void test() { + StringBuilder holder = new StringBuilder(); + String str,bstr; + assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "a","b")); + assertEquals("set a to b",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "a","b")); + assertEquals("set a to b",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = "%1=%2",Vars.convert(holder,str, "a","b")); + assertEquals("a=b",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="%s=%s", "a","b")); + assertEquals("a=b",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = "%1%2",Vars.convert(holder,str, "a","b")); + assertEquals("ab",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="%s%s", "a","b")); + assertEquals("ab",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); - holder.setLength(0); - assertEquals(str = " %1=%2 ",Vars.convert(holder,str, "a","b")); - assertEquals(" a=b ",holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr = " %s=%s ", "a","b")); - assertEquals(" a=b ",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "a","b")); + holder.setLength(0); + assertEquals(str = " %1=%2 ",Vars.convert(holder,str, "a","b")); + assertEquals(" a=b ",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr = " %s=%s ", "a","b")); + assertEquals(" a=b ",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); - holder.setLength(0); - assertEquals(str = " %1%2%10 ",Vars.convert(holder,str, "a","b","c","d","e","f","g","h","i","j")); - assertEquals(" abj ",holder.toString()); - assertEquals(str,Vars.convert(null,str, "a","b","c","d","e","f","g","h","i","j")); - holder.setLength(0); - assertEquals(str=" %1%2%3 ",Vars.convert(holder,bstr = " %s%s%s ", "a","b","c","d","e","f","g","h","i","j")); - assertEquals(" abc ",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "a","b","c","d","e","f","g","h","i","j")); - + holder.setLength(0); + assertEquals(str = " %1%2%10 ",Vars.convert(holder,str, "a","b","c","d","e","f","g","h","i","j")); + assertEquals(" abj ",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b","c","d","e","f","g","h","i","j")); + holder.setLength(0); + assertEquals(str=" %1%2%3 ",Vars.convert(holder,bstr = " %s%s%s ", "a","b","c","d","e","f","g","h","i","j")); + assertEquals(" abc ",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b","c","d","e","f","g","h","i","j")); + - holder.setLength(0); - assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "Something much","larger")); - assertEquals("set Something much to larger",holder.toString()); - assertEquals(str,Vars.convert(null,str,"Something much","larger")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "Something much","larger")); - assertEquals("set Something much to larger",holder.toString()); - assertEquals(str,Vars.convert(null,bstr, "Something much","larger")); + holder.setLength(0); + assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "Something much","larger")); + assertEquals("set Something much to larger",holder.toString()); + assertEquals(str,Vars.convert(null,str,"Something much","larger")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "Something much","larger")); + assertEquals("set Something much to larger",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "Something much","larger")); - holder.setLength(0); - assertEquals(str = "Text without Vars",Vars.convert(holder,str)); - assertEquals(str,holder.toString()); - assertEquals(str = "Text without Vars",Vars.convert(null,str)); - - - holder.setLength(0); - assertEquals(str = "Not %1 Enough %2 Vars %3",Vars.convert(holder,str, "a","b")); - assertEquals("Not a Enough b Vars ",holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - assertEquals(str,Vars.convert(holder,bstr="Not %s Enough %s Vars %s", "a","b")); - assertEquals("Not a Enough b Vars ",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "a","b")); + holder.setLength(0); + assertEquals(str = "Text without Vars",Vars.convert(holder,str)); + assertEquals(str,holder.toString()); + assertEquals(str = "Text without Vars",Vars.convert(null,str)); + + + holder.setLength(0); + assertEquals(str = "Not %1 Enough %2 Vars %3",Vars.convert(holder,str, "a","b")); + assertEquals("Not a Enough b Vars ",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="Not %s Enough %s Vars %s", "a","b")); + assertEquals("Not a Enough b Vars ",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); - holder.setLength(0); - assertEquals(str = "!@#$%^*()-+?/,:;.",Vars.convert(holder,str, "a","b")); - assertEquals(str,holder.toString()); - assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str = "!@#$%^*()-+?/,:;.",Vars.convert(holder,str, "a","b")); + assertEquals(str,holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); - holder.setLength(0); - bstr = "%s !@#$%^*()-+?/,:;."; - str = "%1 !@#$%^*()-+?/,:;."; - assertEquals(str,Vars.convert(holder,bstr, "Not Acceptable")); - assertEquals("Not Acceptable !@#$%^*()-+?/,:;.",holder.toString()); - assertEquals(str ,Vars.convert(null,bstr, "Not Acceptable")); - } - + holder.setLength(0); + bstr = "%s !@#$%^*()-+?/,:;."; + str = "%1 !@#$%^*()-+?/,:;."; + assertEquals(str,Vars.convert(holder,bstr, "Not Acceptable")); + assertEquals("Not Acceptable !@#$%^*()-+?/,:;.",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "Not Acceptable")); + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java index 0d7bdc2c..eca34963 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java @@ -26,138 +26,138 @@ import org.onap.aaf.cadi.wsse.WSSEParser; public class JU_WSSEParser { - @Test - public void test() { - @SuppressWarnings("unused") - WSSEParser wp = new WSSEParser(); + @Test + public void test() { + @SuppressWarnings("unused") + WSSEParser wp = new WSSEParser(); - // TODO: test the rest of this class -// final BasicCred bc = new BasicCred() { -// private String user; -// private byte[] password; + // TODO: test the rest of this class +// final BasicCred bc = new BasicCred() { +// private String user; +// private byte[] password; // -// public void setUser(String user) { this.user = user; } -// public void setCred(byte[] passwd) { this.password = passwd; } -// public String getUser() { return user; } -// public byte[] getCred() { return password; } -// }; +// public void setUser(String user) { this.user = user; } +// public void setCred(byte[] passwd) { this.password = passwd; } +// public String getUser() { return user; } +// public byte[] getCred() { return password; } +// }; -// FileInputStream fis; -// fis = new FileInputStream("test/example.xml"); -// BufferedServletInputStream is = new BufferedServletInputStream(fis); -// try { -// is.mark(1536); -// try { -// assertNull(wp.parse(bc, is)); -// } finally { -// is.reset(); -// assertEquals(814,is.buffered()); -// } -// String password = new String(bc.getCred()); -// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); -// assertEquals("some_user", bc.getUser()); -// assertEquals("some_password", password); -// -// } finally { -// fis.close(); -// } +// FileInputStream fis; +// fis = new FileInputStream("test/example.xml"); +// BufferedServletInputStream is = new BufferedServletInputStream(fis); +// try { +// is.mark(1536); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// is.reset(); +// assertEquals(814,is.buffered()); +// } +// String password = new String(bc.getCred()); +// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); +// assertEquals("some_user", bc.getUser()); +// assertEquals("some_password", password); +// +// } finally { +// fis.close(); +// } // -// // CBUS (larger) -// fis = new FileInputStream("test/CBUSevent.xml"); -// is = new BufferedServletInputStream(fis); -// try { -// is.mark(1536); -// try { -// assertNull(wp.parse(bc, is)); -// } finally { -// is.reset(); -// assertEquals(667,is.buffered()); -// } -// String password = new String(bc.getCred()); -// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); -// assertEquals("none", bc.getUser()); -// assertEquals("none", password); -// -// } finally { -// fis.close(); -// } +// // CBUS (larger) +// fis = new FileInputStream("test/CBUSevent.xml"); +// is = new BufferedServletInputStream(fis); +// try { +// is.mark(1536); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// is.reset(); +// assertEquals(667,is.buffered()); +// } +// String password = new String(bc.getCred()); +// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); +// assertEquals("none", bc.getUser()); +// assertEquals("none", password); +// +// } finally { +// fis.close(); +// } // -// // Closed Stream -// fis = new FileInputStream("test/example.xml"); -// fis.close(); -// bc.setCred(null); -// bc.setUser(null); -// XMLStreamException ex = wp.parse(bc, fis); -// assertNotNull(ex); -// assertNull(bc.getUser()); -// assertNull(bc.getCred()); +// // Closed Stream +// fis = new FileInputStream("test/example.xml"); +// fis.close(); +// bc.setCred(null); +// bc.setUser(null); +// XMLStreamException ex = wp.parse(bc, fis); +// assertNotNull(ex); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); // // -// fis = new FileInputStream("test/exampleNoSecurity.xml"); -// try { -// bc.setCred(null); -// bc.setUser(null); -// assertNull(wp.parse(bc, fis)); -// assertNull(bc.getUser()); -// assertNull(bc.getCred()); -// } finally { -// fis.close(); -// } +// fis = new FileInputStream("test/exampleNoSecurity.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } // -// fis = new FileInputStream("test/exampleBad1.xml"); -// try { -// bc.setCred(null); -// bc.setUser(null); -// assertNull(wp.parse(bc, fis)); -// assertNull(bc.getUser()); -// assertNull(bc.getCred()); -// } finally { -// fis.close(); -// } +// fis = new FileInputStream("test/exampleBad1.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } // -// XMLStreamException e = wp.parse(bc, new ByteArrayInputStream("Not XML".getBytes())); // empty -// assertNotNull(e); +// XMLStreamException e = wp.parse(bc, new ByteArrayInputStream("Not XML".getBytes())); // empty +// assertNotNull(e); // -// e = wp.parse(bc, new ByteArrayInputStream("".getBytes())); // empty -// assertNotNull(e); -// -// -// long start, count = 0L; -// int iter = 30000; -// File f = new File("test/CBUSevent.xml"); -// fis = new FileInputStream(f); -// is = new BufferedServletInputStream(fis); -// is.mark(0); -// try { -// while(is.read()>=0); -// } finally { -// fis.close(); -// } +// e = wp.parse(bc, new ByteArrayInputStream("".getBytes())); // empty +// assertNotNull(e); +// +// +// long start, count = 0L; +// int iter = 30000; +// File f = new File("test/CBUSevent.xml"); +// fis = new FileInputStream(f); +// is = new BufferedServletInputStream(fis); +// is.mark(0); +// try { +// while(is.read()>=0); +// } finally { +// fis.close(); +// } // -// for(int i=0;i<iter;++i) { -// start = System.nanoTime(); -// is.reset(); -// try { -// assertNull(wp.parse(bc, is)); -// } finally { -// count += System.nanoTime()-start; -// } -// } -// float ms = count/1000000f; -// System.out.println("Executed " + iter + " WSSE reads from Memory Stream in " + ms + "ms. " + ms/iter + "ms per trans"); -// -// // SPECIFIC ISSUES -// -// fis = new FileInputStream("test/error2013_04_23.xml"); -// try { -// bc.setCred(null); -// bc.setUser(null); -// assertNull(wp.parse(bc, fis)); -// assertNull(bc.getUser()); -// assertNull(bc.getCred()); -// } finally { -// fis.close(); -// } - } +// for(int i=0;i<iter;++i) { +// start = System.nanoTime(); +// is.reset(); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// count += System.nanoTime()-start; +// } +// } +// float ms = count/1000000f; +// System.out.println("Executed " + iter + " WSSE reads from Memory Stream in " + ms + "ms. " + ms/iter + "ms per trans"); +// +// // SPECIFIC ISSUES +// +// fis = new FileInputStream("test/error2013_04_23.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java index e75cea4e..36de053c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java @@ -40,113 +40,113 @@ import org.onap.aaf.cadi.wsse.XReader; public class JU_XReader { - private final static String TEST_DIR_NAME = "src/test/resources"; - private final static String TEST_XML_NAME = "test.xml"; - private static File testXML; - - private final static String COMMENT = "a comment"; - private final static String OUTER_TAG = "outerTag"; - private final static String INNER_TAG = "innerTag"; - private final static String DATA_TAG = "dataTag"; - private final static String DATA = "some text that represents data"; - private final static String SELF_CLOSING_TAG = "selfClosingTag"; - private final static String PREFIX = "prefix"; - private final static String SUFFIX = "suffix"; - - @BeforeClass - public static void setupOnce() throws IOException { - testXML = setupXMLFile(); - } - - @AfterClass - public static void tearDownOnce() { - testXML.delete(); - } - - @Test - public void test() throws XMLStreamException, IOException { - FileInputStream fis = new FileInputStream(TEST_DIR_NAME + '/' + TEST_XML_NAME); - try { - XReader xr = new XReader(fis); - assertThat(xr.hasNext(), is(true)); - XEvent xe; - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.START_DOCUMENT)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.COMMENT)); - assertThat(((XEvent.Comment)xe).value, is(COMMENT)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); - assertThat(xe.asStartElement().getName().toString(), is(OUTER_TAG)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); - assertThat(xe.asStartElement().getName().toString(), is(INNER_TAG)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); - assertThat(xe.asStartElement().getName().toString(), is(DATA_TAG)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.CHARACTERS)); - assertThat(xe.asCharacters().getData().toString(), is(DATA)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); - assertThat(xe.asEndElement().getName().toString(), is(DATA_TAG)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); - assertThat(xe.asStartElement().getName().toString(), is(SELF_CLOSING_TAG)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); - assertThat(xe.asStartElement().getName().toString(), is(SUFFIX)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); - assertThat(xe.asEndElement().getName().toString(), is(INNER_TAG)); - - xe = getNextEvent(xr); - assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); - assertThat(xe.asEndElement().getName().toString(), is(OUTER_TAG)); - - assertThat(xr.hasNext(), is(false)); - - } finally { - fis.close(); - } - } - - private static XEvent getNextEvent(XReader xr) throws XMLStreamException { - if (xr.hasNext()) { - return xr.nextEvent(); - } - return null; - } - - private static File setupXMLFile() throws IOException { - File xmlFile = new File(TEST_DIR_NAME, TEST_XML_NAME); - PrintWriter writer = new PrintWriter(xmlFile); - writer.println(" "); // Whitespace before the document - this is for coverage - writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - writer.println("<!DOCTYPE xml>"); - writer.println("<!--" + COMMENT + "-->"); - writer.println("<" + OUTER_TAG + ">"); - writer.println(" <" + INNER_TAG + ">"); - writer.println(" <" + DATA_TAG + ">" + DATA + "</" + DATA_TAG + ">"); - writer.println(" <" + SELF_CLOSING_TAG + " withAnAttribute=\"That has nested \\\" marks\" />"); - writer.println(" <" + PREFIX + ":" + SUFFIX + "/>"); - writer.println(" </" + INNER_TAG + ">"); - writer.println("</" + OUTER_TAG + ">"); - writer.flush(); - writer.close(); - return xmlFile; - } + private final static String TEST_DIR_NAME = "src/test/resources"; + private final static String TEST_XML_NAME = "test.xml"; + private static File testXML; + + private final static String COMMENT = "a comment"; + private final static String OUTER_TAG = "outerTag"; + private final static String INNER_TAG = "innerTag"; + private final static String DATA_TAG = "dataTag"; + private final static String DATA = "some text that represents data"; + private final static String SELF_CLOSING_TAG = "selfClosingTag"; + private final static String PREFIX = "prefix"; + private final static String SUFFIX = "suffix"; + + @BeforeClass + public static void setupOnce() throws IOException { + testXML = setupXMLFile(); + } + + @AfterClass + public static void tearDownOnce() { + testXML.delete(); + } + + @Test + public void test() throws XMLStreamException, IOException { + FileInputStream fis = new FileInputStream(TEST_DIR_NAME + '/' + TEST_XML_NAME); + try { + XReader xr = new XReader(fis); + assertThat(xr.hasNext(), is(true)); + XEvent xe; + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_DOCUMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.COMMENT)); + assertThat(((XEvent.Comment)xe).value, is(COMMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(OUTER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(INNER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(DATA_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.CHARACTERS)); + assertThat(xe.asCharacters().getData().toString(), is(DATA)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(DATA_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(SELF_CLOSING_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(SUFFIX)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(INNER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(OUTER_TAG)); + + assertThat(xr.hasNext(), is(false)); + + } finally { + fis.close(); + } + } + + private static XEvent getNextEvent(XReader xr) throws XMLStreamException { + if (xr.hasNext()) { + return xr.nextEvent(); + } + return null; + } + + private static File setupXMLFile() throws IOException { + File xmlFile = new File(TEST_DIR_NAME, TEST_XML_NAME); + PrintWriter writer = new PrintWriter(xmlFile); + writer.println(" "); // Whitespace before the document - this is for coverage + writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); + writer.println("<!DOCTYPE xml>"); + writer.println("<!--" + COMMENT + "-->"); + writer.println("<" + OUTER_TAG + ">"); + writer.println(" <" + INNER_TAG + ">"); + writer.println(" <" + DATA_TAG + ">" + DATA + "</" + DATA_TAG + ">"); + writer.println(" <" + SELF_CLOSING_TAG + " withAnAttribute=\"That has nested \\\" marks\" />"); + writer.println(" <" + PREFIX + ":" + SUFFIX + "/>"); + writer.println(" </" + INNER_TAG + ">"); + writer.println("</" + OUTER_TAG + ">"); + writer.flush(); + writer.close(); + return xmlFile; + } } |