diff options
author | Ryan Young <ry303t@att.com> | 2018-06-28 17:22:47 -0400 |
---|---|---|
committer | Takamune Cho <tc012c@att.com> | 2018-08-09 21:10:37 +0000 |
commit | e35c3a0387e68bbeb3df8c5d614e0b99f5c4f743 (patch) | |
tree | 912679b50bc48e7ff3e4c4e1246ad897b51ce194 /appc-core/appc-common-bundle/src/test/java | |
parent | 344a44f3bb0762e5bc32a4ef760fb3b42ef4688d (diff) |
Update appc-common to Karaf 4
update appc-common to karaf 4 feature
Change-Id: Ib0ce37032e63ffc61bef94345701f3ab58785153
Signed-off-by: Ryan Young <ry303t@att.com>
Issue-ID: APPC-1022
Diffstat (limited to 'appc-core/appc-common-bundle/src/test/java')
35 files changed, 4379 insertions, 0 deletions
diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/CmdLineTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/CmdLineTest.java new file mode 100644 index 000000000..1162d7649 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/CmdLineTest.java @@ -0,0 +1,41 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc;
+
+import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+
+public class CmdLineTest {
+ @Test
+ public void testMain() {
+ String argv[];
+ argv = new String[] {"encrypt","abc","ghi"};
+ CmdLine.main(argv);
+ argv = new String[0];
+ CmdLine.main(argv);
+ argv = new String[] {"encrypt","abc"};
+ CmdLine.main(argv);
+
+ CmdLine cmdLine = new CmdLine();
+ assertNotNull(cmdLine);
+ }
+}
diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/ConstantsTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/ConstantsTest.java new file mode 100644 index 000000000..47f3e6a0d --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/ConstantsTest.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc; + +import org.junit.Test; + +public class ConstantsTest { + @Test (expected = IllegalAccessError.class) + public void testConstructor() throws Exception { + Constants constants = new Constants(); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/CacheStrategiesTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/CacheStrategiesTest.java new file mode 100644 index 000000000..901130e79 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/CacheStrategiesTest.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache; + +import org.junit.Assert; +import org.junit.Test; + +public class CacheStrategiesTest { + private CacheStrategies cacheStrategies = CacheStrategies.LRU; + + @Test + public void testName() throws Exception { + Assert.assertEquals("Should have name LRU", "LRU", cacheStrategies.name()); + } + + @Test + public void testToString() throws Exception { + Assert.assertEquals("Should return String LRU", "LRU", cacheStrategies.toString()); + } + + @Test + public void testEquals() throws Exception { + Assert.assertTrue(cacheStrategies.equals(CacheStrategies.LRU)); + Assert.assertFalse(cacheStrategies.equals(null)); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/LRUCacheTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/LRUCacheTest.java new file mode 100644 index 000000000..2eca72a07 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/LRUCacheTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import org.junit.Assert; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +import java.util.Map; + +public class LRUCacheTest { + + @Test + public void testConstructor() throws Exception { + LRUCache cache = new LRUCache(20); + Map internalMap = Whitebox.getInternalState(cache, "map"); + Assert.assertTrue(internalMap != null); + Assert.assertTrue(internalMap.size() == 0); + } + + @Test + public void testGetAndPutObject() throws Exception { + LRUCache cache = new LRUCache(20); + + String key = "testing key"; + Assert.assertTrue(cache.getObject(key) == null); + + String value = "testing value"; + cache.putObject(key, value); + Map internalMap = Whitebox.getInternalState(cache, "map"); + Assert.assertTrue(internalMap.containsKey(key)); + Assert.assertTrue(internalMap.containsValue(value)); + Assert.assertTrue(internalMap.size() == 1); + + Assert.assertEquals(value, cache.getObject(key)); + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/MetadataCacheFactoryTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/MetadataCacheFactoryTest.java new file mode 100644 index 000000000..9f2d1a05c --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/MetadataCacheFactoryTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import static org.mockito.Mockito.mock; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.appc.cache.CacheStrategies; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({MetadataCacheFactory.class, MetadataCacheImpl.class}) +public class MetadataCacheFactoryTest { + @Test + public void testConstructor() throws Exception { + Whitebox.invokeConstructor(MetadataCacheFactory.class); + } + + @Test + public void testGetInstance() throws Exception { + Assert.assertTrue("Should not return null", MetadataCacheFactory.getInstance() != null); + Assert.assertEquals("Should always return the same object", + MetadataCacheFactory.getInstance(), MetadataCacheFactory.getInstance()); + } + + @Test + public void testGetMetadataCacheWithNoArgument() throws Exception { + MetadataCacheImpl mockImpl = mock(MetadataCacheImpl.class); + PowerMockito.whenNew(MetadataCacheImpl.class).withNoArguments().thenReturn(mockImpl); + Assert.assertEquals(mockImpl, MetadataCacheFactory.getInstance().getMetadataCache()); + } + + @Test + public void testGetMetadataCacheWithArgument() throws Exception { + CacheStrategies cacheStrategies = CacheStrategies.LRU; + MetadataCacheImpl mockImpl = mock(MetadataCacheImpl.class); + PowerMockito.whenNew(MetadataCacheImpl.class).withArguments(cacheStrategies) + .thenReturn(mockImpl); + Assert.assertEquals(mockImpl, + MetadataCacheFactory.getInstance().getMetadataCache(cacheStrategies)); + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/MetadataCacheImplTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/MetadataCacheImplTest.java new file mode 100644 index 000000000..f3c678441 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/cache/impl/MetadataCacheImplTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.cache.impl; + +import static org.mockito.Mockito.spy; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.cache.CacheStrategies; +import org.powermock.reflect.Whitebox; + +public class MetadataCacheImplTest { + @Test + public void testConstructor() throws Exception { + // test without parameter + MetadataCacheImpl impl = new MetadataCacheImpl<>(); + Assert.assertTrue("Should have initialized strategy", + Whitebox.getInternalState(impl, "strategy") != null); + + // test with parameter + impl = new MetadataCacheImpl<>(CacheStrategies.LRU); + Assert.assertTrue("Should have initialized strategy", + Whitebox.getInternalState(impl, "strategy") != null); + + impl = new MetadataCacheImpl<>(null); + Assert.assertTrue("Should not initialized strategy", + Whitebox.getInternalState(impl, "strategy") == null); + } + + @Test + public void testGetAndPutObject() throws Exception { + MetadataCacheImpl impl = spy(new MetadataCacheImpl<>()); + + String key = "testing key"; + Assert.assertTrue(impl.getObject(key) == null); + + String value = "testing value"; + impl.putObject(key, value); + Assert.assertEquals(value, impl.getObject(key)); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/concurrent/TestSignal.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/concurrent/TestSignal.java new file mode 100644 index 000000000..4b5eadd7a --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/concurrent/TestSignal.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modification Copyright (C) 2018 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.concurrent; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.TimeoutException; + +import org.junit.Test; +import org.onap.appc.concurrent.Signal; + + + +public class TestSignal { + + private static final DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS"); + public static final String SIGNAL_READY = "READY"; + public static final String SIGNAL_SHUTDOWN = "SHUTDOWN"; + + @Test + public void TestSimpleSignal() throws TimeoutException { + + Signal mySignal = new Signal(Thread.currentThread()); + mySignal.setTimeout(5000L); + Fred fred = new Fred(mySignal); + Thread t1 = new Thread(fred); + + /* + * Verify that fred is dead, then start him and wait for him to signal us he is ready to proceed + */ + assertFalse(t1.isAlive()); + t1.start(); + System.out.println(formatter.format(new Date()) + " MAIN: Waiting for Ready..."); + mySignal.waitFor(SIGNAL_READY); + System.out.println(formatter.format(new Date()) + " MAIN: Signal Ready received"); + + /* + * Verify that fred is still alive and we will sleep for a while (simulate doing things) + */ + assertTrue(t1.isAlive()); + try { + Thread.sleep(250L); + } catch (InterruptedException e) { + // ignored + } + + /* + * Verify that fred is still alive and signal him to shutdown + */ + assertTrue(t1.isAlive()); + System.out.println(formatter.format(new Date()) + " MAIN: Signaling shutdown"); + fred.getSignal().signal(SIGNAL_SHUTDOWN); + + /* + * Wait a little bit + */ + try { + Thread.sleep(250L); + } catch (InterruptedException e) { + // ignored + } + + /* + * Verify that fred is dead now and that he completed normally + */ + System.out.println(formatter.format(new Date()) + " MAIN: Shutting down..."); + assertFalse(t1.isAlive()); + assertTrue(fred.isCompleted()); + } + + public class Fred implements Runnable { + private Signal signal; + private Signal parentSignal; + private boolean completed = false; + + public Fred(Signal parentSignal) { + this.parentSignal = parentSignal; + } + + @Override + public void run() { + signal = new Signal(Thread.currentThread()); + signal.setTimeout(5000L); + try { + Thread.sleep(250L); + } catch (InterruptedException e) { + // Ignore + } + + System.out.println(formatter.format(new Date()) + " FRED: Signaling ready..."); + parentSignal.signal(SIGNAL_READY); + + try { + System.out.println(formatter.format(new Date()) + " FRED: Waiting for shutdown..."); + signal.waitFor(SIGNAL_SHUTDOWN); + System.out.println(formatter.format(new Date()) + " FRED: Received shutdown"); + completed = true; + } catch (TimeoutException e) { + + } + } + + public boolean isCompleted() { + return completed; + } + + public Signal getSignal() { + return signal; + } + } + + @Test + public void testWaitForAny() throws Exception + { + Signal mySignal = new Signal(Thread.currentThread()); + mySignal.setTimeout(50L); + String receivedSignal= mySignal.waitForAny(SIGNAL_READY); + assertEquals("READY", receivedSignal); + } + + @Test(expected=TimeoutException.class) + public void testWaitForAnyForEmptySignal() throws TimeoutException + { + Signal mySignal = new Signal(Thread.currentThread()); + mySignal.setTimeout(50L); + mySignal.waitForAny(); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/configuration/ConfigurationFactoryTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/configuration/ConfigurationFactoryTest.java new file mode 100644 index 000000000..7d0206467 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/configuration/ConfigurationFactoryTest.java @@ -0,0 +1,15 @@ +package org.onap.appc.configuration; + +import org.junit.Assert; +import org.junit.Test; + +import static org.onap.appc.configuration.ConfigurationFactory.getConfiguration; + +public class ConfigurationFactoryTest { + @Test + public void should_returnDefaultConfiguration(){ + Configuration conf = null; + + Assert.assertTrue(getConfiguration() instanceof DefaultConfiguration); + } +}
\ No newline at end of file diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/configuration/DefaultConfigurationTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/configuration/DefaultConfigurationTest.java new file mode 100644 index 000000000..aed414192 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/configuration/DefaultConfigurationTest.java @@ -0,0 +1,347 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modification Copyright (C) 2018 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.configuration; + +import static org.mockito.Mockito.mock; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.powermock.reflect.Whitebox; + +public class DefaultConfigurationTest { + private static final String propKey1 = "testKey1"; + private static final String propKey2 = "testKey2"; + private static final String propValue1 = "testValue1"; + private static final String propValue2 = "testValue2"; + + private Properties prop = new Properties(); + private DefaultConfiguration defaultConfiguration; + + @Before + public void setUp() throws Exception { + prop.setProperty(propKey1, propValue1); + prop.setProperty(propKey2, propValue2); + + defaultConfiguration = new DefaultConfiguration(); + } + + @Test + public void testClear() throws Exception { + Whitebox.setInternalState(defaultConfiguration, "properties", prop); + defaultConfiguration.clear(); + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertTrue("internal properties should be cleared", internalProp.isEmpty()); + } + + @Test + public void testClone() throws Exception { + Object clonedObject = defaultConfiguration.clone(); + Assert.assertTrue("Should be DefaultConfiguration", + clonedObject instanceof DefaultConfiguration); + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Properties clonedInternalProp = Whitebox.getInternalState(clonedObject, "properties"); + Assert.assertEquals(internalProp, clonedInternalProp); + } + + @Test + public void testEquals() throws Exception { + // test compare with null + Assert.assertFalse(defaultConfiguration.equals(null)); + // test with non-DefaultConfiguration object + Assert.assertFalse(defaultConfiguration.equals("abc")); + + // test with not match DefaultConfiguration object + defaultConfiguration.setProperties(prop); + DefaultConfiguration newConfig = new DefaultConfiguration(); + Assert.assertFalse(defaultConfiguration.equals(newConfig)); + + // test with matching DefaultConfiguration object + newConfig.setProperties(prop); + Assert.assertTrue(defaultConfiguration.equals(newConfig)); + } + + @Test + public void testSetPropAndGetBooleanProperty() throws Exception { + String booleanKey = "booleanKey"; + // test default value + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); + // test match value true + defaultConfiguration.setProperty(booleanKey, "true"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); + defaultConfiguration.setProperty(booleanKey, "True"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); + defaultConfiguration.setProperty(booleanKey, "TrUe"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey)); + // test not matching true values + defaultConfiguration.setProperty(booleanKey, "false"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); + defaultConfiguration.setProperty(booleanKey, "abc"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); + } + + @Test + public void testSetPropAndGetBooleanPropertyForEncryptedValue() + { + String booleanKey = "booleanKey"; + defaultConfiguration.setProperty(booleanKey, "enc:true"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey)); + } + + + @Test + public void testSetPropAndGetBooleanPropertyWithDefaultValue() throws Exception { + String booleanKey = "booleanKey"; + // test default value + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, false)); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, true)); + // test match value true + defaultConfiguration.setProperty(booleanKey, "true"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); + defaultConfiguration.setProperty(booleanKey, "True"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); + defaultConfiguration.setProperty(booleanKey, "TrUe"); + Assert.assertTrue(defaultConfiguration.getBooleanProperty(booleanKey, false)); + // test not matching true values + defaultConfiguration.setProperty(booleanKey, "false"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, true)); + defaultConfiguration.setProperty(booleanKey, "abc"); + Assert.assertFalse(defaultConfiguration.getBooleanProperty(booleanKey, true)); + } + + @Test + public void testSetPropAndGetDoubleProperty() throws Exception { + String doubleKey = "doubleKey"; + // test default value + Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey)); + // test NumberFormatException + defaultConfiguration.setProperty(doubleKey, "abc"); + Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey)); + // test normal + defaultConfiguration.setProperty(doubleKey, "1.1"); + Assert.assertTrue(1.1 == defaultConfiguration.getDoubleProperty(doubleKey)); + } + + @Test + public void testSetPropAndGetDoublePropertyWithDefaultValue() throws Exception { + String doubleKey = "doubleKey"; + // test default value + Assert.assertTrue(2.2 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); + // test NumberFormatException + defaultConfiguration.setProperty(doubleKey, "abc"); + Assert.assertTrue(0.0 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); + // test normal + defaultConfiguration.setProperty(doubleKey, "1.1"); + Assert.assertTrue(1.1 == defaultConfiguration.getDoubleProperty(doubleKey, 2.2)); + } + + @Test + public void testSetPropAndGetIntegerProperty() throws Exception { + String integerKey = "integerKey"; + // test default value + Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey)); + // test NumberFormatException + defaultConfiguration.setProperty(integerKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey)); + // test normal + defaultConfiguration.setProperty(integerKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey)); + } + + @Test + public void testSetPropAndGetIntegerPropertyWithDefaultValue() throws Exception { + String integerKey = "integerKey"; + // test default value + Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey, 100)); + // test NumberFormatException + defaultConfiguration.setProperty(integerKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getIntegerProperty(integerKey, 100)); + // test normal + defaultConfiguration.setProperty(integerKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getIntegerProperty(integerKey, 10)); + } + + @Test + public void testSetPropAndGetLongProperty() throws Exception { + String longKey = "longKey"; + // test default value + Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey)); + // test NumberFormatException + defaultConfiguration.setProperty(longKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey)); + // test normal + defaultConfiguration.setProperty(longKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getLongProperty(longKey)); + } + + @Test + public void testSetPropAndGetLongPropertyWithDefaultVaue() throws Exception { + String longKey = "longKey"; + // test default value + Assert.assertTrue(10 == defaultConfiguration.getLongProperty(longKey, 10)); + // test NumberFormatException + defaultConfiguration.setProperty(longKey, "abc"); + Assert.assertTrue(0 == defaultConfiguration.getLongProperty(longKey, 10)); + // test normal + defaultConfiguration.setProperty(longKey, "100"); + Assert.assertTrue(100 == defaultConfiguration.getLongProperty(longKey, 10)); + } + + @Test + public void testSetAndGetProperties() throws Exception { + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertEquals(internalProp, defaultConfiguration.getProperties()); + + defaultConfiguration.setProperties(prop); + internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertEquals(internalProp, defaultConfiguration.getProperties()); + } + + @Test + public void testSetAndGetProperty() throws Exception { + String key = "key"; + // test default value + Assert.assertTrue(null == defaultConfiguration.getProperty(key)); + // test normal + defaultConfiguration.setProperty(key, "abc"); + Assert.assertEquals("abc", defaultConfiguration.getProperty(key)); + } + + @Test + public void testSetPropAndGetPropertyWithDefaultValue() throws Exception { + String key = "key"; + // test default value + Assert.assertTrue(null == defaultConfiguration.getProperty(key, null)); + Assert.assertEquals("abc", defaultConfiguration.getProperty(key, "abc")); + // test normal + defaultConfiguration.setProperty(key, "abc"); + Assert.assertEquals("abc", defaultConfiguration.getProperty(key, "abcd")); + } + + @Test + public void testHashCode() throws Exception { + Properties properties = null; + Whitebox.setInternalState(defaultConfiguration, "properties", properties); + Assert.assertEquals(0, defaultConfiguration.hashCode()); + + + Whitebox.setInternalState(defaultConfiguration, "properties", prop); + Assert.assertEquals(prop.hashCode(), defaultConfiguration.hashCode()); + } + + @Test + public void testIsPropertyDefined() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isPropertyDefined(key)); + // test exist + defaultConfiguration.setProperty(key, "abc"); + Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); + } + + @Test + public void testIsValidBoolean() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidBoolean(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidBoolean(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "True"); + Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); + defaultConfiguration.setProperty(key, "FaLse"); + Assert.assertTrue(defaultConfiguration.isPropertyDefined(key)); + } + + @Test + public void testIsValidDouble() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidDouble(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidDouble(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "2"); + Assert.assertTrue(defaultConfiguration.isValidDouble(key)); + defaultConfiguration.setProperty(key, "3.45"); + Assert.assertTrue(defaultConfiguration.isValidDouble(key)); + } + + @Test + public void testIsValidInteger() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidInteger(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidInteger(key)); + defaultConfiguration.setProperty(key, "3.45"); + Assert.assertFalse(defaultConfiguration.isValidInteger(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "2"); + Assert.assertTrue(defaultConfiguration.isValidInteger(key)); + } + + @Test + public void testIsValidLong() throws Exception { + String key = "key"; + // test not exist + Assert.assertFalse(defaultConfiguration.isValidLong(key)); + // test exist with invalid + defaultConfiguration.setProperty(key, "abc"); + Assert.assertFalse(defaultConfiguration.isValidLong(key)); + defaultConfiguration.setProperty(key, "3.45"); + Assert.assertFalse(defaultConfiguration.isValidLong(key)); + // test exist with valid + defaultConfiguration.setProperty(key, "2"); + Assert.assertTrue(defaultConfiguration.isValidLong(key)); + } + + @Test + public void testSetPropertiesWithInputStream() throws Exception { + InputStream mockIS = mock(InputStream.class); + defaultConfiguration.setProperties(mockIS); + + Properties mockProp = mock(Properties.class); + Mockito.doThrow(new IOException("testing exception")).when(mockProp).load(mockIS); + Whitebox.setInternalState(defaultConfiguration, "properties", mockProp); + defaultConfiguration.setProperties(mockIS); + // Should come here without exception + } + + @Test + public void testToString() throws Exception { + Properties internalProp = Whitebox.getInternalState(defaultConfiguration, "properties"); + Assert.assertEquals(String.format("Configuration: %d properties, keys:[%s]", + internalProp.size(), internalProp.keySet().toString()), + defaultConfiguration.toString()); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/encryption/EncryptionToolTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/encryption/EncryptionToolTest.java new file mode 100644 index 000000000..ae6de6dcc --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/encryption/EncryptionToolTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.encryption; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class EncryptionToolTest { + + private static final String PLAIN_TEXT = "text to encrypt"; + private static final String EMPTY_STR = ""; + + private EncryptionTool encryptionTool = EncryptionTool.getInstance(); + + @Test + public void should_return_prefix_given_empty_string() { + assertEquals("enc:", encryptionTool.encrypt(EMPTY_STR)); + } + + @Test + public void should_return_null_given_null() { + assertNull(encryptionTool.encrypt(null)); + } + + @Test + public void should_encrypt_given_string() { + String encrypted = encryptionTool.encrypt(PLAIN_TEXT); + + assertNotEquals(encrypted, PLAIN_TEXT); + assertTrue(encrypted.startsWith(EncryptionTool.ENCRYPTED_VALUE_PREFIX)); + } + + @Test + public void should_not_decrypt_string_when_not_starting_with_prefix() { + + assertNull(encryptionTool.decrypt(null)); + assertEquals("mdi/12!dsao91", encryptionTool.decrypt("mdi/12!dsao91")); + } + + @Test + public void should_decrypt_given_encrypted_string() { + String encrypted = encryptionTool.encrypt(PLAIN_TEXT); + + assertEquals(PLAIN_TEXT, encryptionTool.decrypt(encrypted)); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/encryption/HexHelperTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/encryption/HexHelperTest.java new file mode 100644 index 000000000..3af421a0f --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/encryption/HexHelperTest.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.appc.encryption; + +import static com.google.common.collect.Lists.newArrayList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import org.junit.Test; + +public class HexHelperTest { + + private final List<Character> hexChars = + newArrayList('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C', 'D', 'E', 'F'); + + @Test(expected = EncryptionException.class) + public void convertHexToBytes_should_throw_given_null() throws EncryptionException { + + HexHelper.convertHexToBytes(null); + } + + @Test(expected = EncryptionException.class) + public void convertHexToBytes_should_throw_given_non_hexadecimal_string() throws EncryptionException { + + HexHelper.convertHexToBytes("125FET4A"); + } + + @Test + public void convertHexToBytes_should_convert_hexadecimal_string_to_byte_array() throws EncryptionException { + + byte[] result = HexHelper.convertHexToBytes("125FE4A"); + + assertNotEquals(0, result.length); + } + + + @Test(expected = EncryptionException.class) + public void convertBytesToHex_should_throw_given_null() throws EncryptionException { + + HexHelper.convertBytesToHex(null); + } + + + @Test + public void convertBytesToHex_should_convert_byte_array_to_hexadecimal_string() throws EncryptionException { + + String resultString = HexHelper.convertBytesToHex(new byte[]{24, -1, 85, 99}); + for (char ch : resultString.toCharArray()) { + assertTrue(hexChars.contains(ch)); + } + + byte[] resultArray = HexHelper.convertHexToBytes("A56C9ED17"); + assertEquals("0A56C9ED17", HexHelper.convertBytesToHex(resultArray)); + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/APPCExceptionTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/APPCExceptionTest.java new file mode 100644 index 000000000..f79be0e9d --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/APPCExceptionTest.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + + +public class APPCExceptionTest { + + @Test + public void testConstructorNoArgument() throws Exception { + APPCException appcException = new APPCException(); + Assert.assertTrue(appcException.getCause() == null); + Assert.assertTrue(appcException.getLocalizedMessage() == null); + Assert.assertTrue(appcException.getMessage() == null); + } + + @Test + public void testConstructorWithMessaqge() throws Exception { + String message = "testing message"; + APPCException appcException = new APPCException(message); + Assert.assertTrue(appcException.getCause() == null); + Assert.assertEquals(message, appcException.getLocalizedMessage()); + Assert.assertEquals(message, appcException.getMessage()); + } + + @Test + public void testConstructorWithThrowable() throws Exception { + String message = "testing message"; + Throwable throwable = new Throwable(message); + APPCException appcException = new APPCException(throwable); + Assert.assertEquals(throwable, appcException.getCause()); + Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); + Assert.assertTrue(appcException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithMessageAndThrowable() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + APPCException appcException = new APPCException(message, throwable); + Assert.assertEquals(throwable, appcException.getCause()); + Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); + Assert.assertTrue(appcException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithFourArguments() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + APPCException appcException = new APPCException(message, throwable, true, true); + Assert.assertEquals(throwable, appcException.getCause()); + Assert.assertTrue(appcException.getLocalizedMessage().contains(message)); + Assert.assertTrue(appcException.getMessage().contains(message)); + + Assert.assertTrue(Whitebox.getInternalState(appcException, "stackTrace") != null); + Assert.assertTrue(Whitebox.getInternalState(appcException, "suppressedExceptions") != null); + + appcException = new APPCException(message, throwable, false, false); + Assert.assertTrue(Whitebox.getInternalState(appcException, "stackTrace") == null); + Assert.assertTrue(Whitebox.getInternalState(appcException, "suppressedExceptions") == null); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/InvalidInputExceptionTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/InvalidInputExceptionTest.java new file mode 100644 index 000000000..4e30ed5f6 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/InvalidInputExceptionTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; + +public class InvalidInputExceptionTest { + @Test + public void testConstructor() throws Exception { + String message = "testing message"; + InvalidInputException invalidInputException = new InvalidInputException(message); + Assert.assertTrue(invalidInputException.getCause() == null); + Assert.assertEquals(message, invalidInputException.getLocalizedMessage()); + Assert.assertEquals(message, invalidInputException.getMessage()); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/InvalidStateExceptionTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/InvalidStateExceptionTest.java new file mode 100644 index 000000000..21374dae6 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/InvalidStateExceptionTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; + +public class InvalidStateExceptionTest { + @Test + public void testConstructor() throws Exception { + String message = "testing message"; + InvalidStateException invalidStateException = new InvalidStateException(message); + Assert.assertTrue(invalidStateException.getCause() == null); + Assert.assertEquals(message, invalidStateException.getLocalizedMessage()); + Assert.assertEquals(message, invalidStateException.getMessage()); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/UnknownProviderExceptionTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/UnknownProviderExceptionTest.java new file mode 100644 index 000000000..c969c0cff --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/exceptions/UnknownProviderExceptionTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.exceptions; + +import org.junit.Assert; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +public class UnknownProviderExceptionTest { + + @Test + public void testConstructorNoArgument() throws Exception { + UnknownProviderException unknownProviderException = new UnknownProviderException(); + Assert.assertTrue(unknownProviderException.getCause() == null); + Assert.assertTrue(unknownProviderException.getLocalizedMessage() == null); + Assert.assertTrue(unknownProviderException.getMessage() == null); + } + + @Test + public void testConstructorWithMessaqge() throws Exception { + String message = "testing message"; + UnknownProviderException unknownProviderException = new UnknownProviderException(message); + Assert.assertTrue(unknownProviderException.getCause() == null); + Assert.assertEquals(message, unknownProviderException.getLocalizedMessage()); + Assert.assertEquals(message, unknownProviderException.getMessage()); + } + + @Test + public void testConstructorWithThrowable() throws Exception { + String message = "testing message"; + Throwable throwable = new Throwable(message); + UnknownProviderException unknownProviderException = new UnknownProviderException(throwable); + Assert.assertEquals(throwable, unknownProviderException.getCause()); + Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); + Assert.assertTrue(unknownProviderException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithMessageAndThrowable() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + UnknownProviderException unknownProviderException = + new UnknownProviderException(message, throwable); + Assert.assertEquals(throwable, unknownProviderException.getCause()); + Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); + Assert.assertTrue(unknownProviderException.getMessage().contains(message)); + } + + @Test + public void testConstructorWithFourArguements() throws Exception { + String message = "testing message"; + String tMessage = "throwable message"; + Throwable throwable = new Throwable(tMessage); + UnknownProviderException unknownProviderException = + new UnknownProviderException(message, throwable, true, true); + Assert.assertEquals(throwable, unknownProviderException.getCause()); + Assert.assertTrue(unknownProviderException.getLocalizedMessage().contains(message)); + Assert.assertTrue(unknownProviderException.getMessage().contains(message)); + + Assert.assertTrue( + Whitebox.getInternalState(unknownProviderException, "stackTrace") != null); + Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, + "suppressedExceptions") != null); + + unknownProviderException = new UnknownProviderException(message, throwable, false, false); + Assert.assertTrue( + Whitebox.getInternalState(unknownProviderException, "stackTrace") == null); + Assert.assertTrue(Whitebox.getInternalState(unknownProviderException, + "suppressedExceptions") == null); + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/i18n/MsgTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/i18n/MsgTest.java new file mode 100644 index 000000000..5fbcac13d --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/i18n/MsgTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.i18n; + +import org.junit.Assert; +import org.junit.Test; + +public class MsgTest { + @Test + public void testNameAndToString() throws Exception { + for (Msg msg : Msg.values()) { + Assert.assertEquals(msg.name(), msg.toString()); + } + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/logging/LoggingConstantsTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/logging/LoggingConstantsTest.java new file mode 100644 index 000000000..b2519fe00 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/logging/LoggingConstantsTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.logging; + +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +public class LoggingConstantsTest { + @Test (expected = IllegalAccessError.class) + public void testConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.class); + } + + @Test (expected = IllegalAccessError.class) + public void testMdcKeysConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.MDCKeys.class); + } + + @Test (expected = IllegalAccessError.class) + public void testStatusCodesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.StatusCodes.class); + } + + @Test (expected = IllegalAccessError.class) + public void testTargetNamesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.TargetNames.class); + } + + @Test (expected = IllegalAccessError.class) + public void testTargetServiceNamesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.TargetServiceNames.class); + } + + @Test (expected = IllegalAccessError.class) + public void testAAIServiceNamesConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingConstants.TargetServiceNames.AAIServiceNames.class); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/logging/LoggingUtilsTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/logging/LoggingUtilsTest.java new file mode 100644 index 000000000..cc7216018 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/logging/LoggingUtilsTest.java @@ -0,0 +1,357 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.logging; + +import org.junit.Test; +import org.powermock.reflect.Whitebox; +import org.slf4j.MDC; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import java.lang.Class; +import java.lang.reflect.Method; +import java.time.Instant; + +public class LoggingUtilsTest { + @Test(expected = IllegalAccessError.class) + public void testConstructor() throws Exception { + Whitebox.invokeConstructor(LoggingUtils.class); + } + + @Test + public void testLogErrorMessageStringStringStringStringStringString() { + try { + LoggingUtils.logErrorMessage("ERROR_CODE", "ERROR_DESCRIPTION", "TARGET_ENTITY", "TARGET_SERVICE_NAME", "ADDITIONAL_MESSAGE", "CLASS_NAME"); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking logErrorMessage: " + e.toString()); + } + } + + @Test + public void testLogErrorMessageStringStringStringString() { + try { + LoggingUtils.logErrorMessage("TARGET_ENTITY", "TARGET_SERVICE_NAME", "ADDITIONAL_MESSAGE", "CLASS_NAME"); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking logErrorMessage: " + e.toString()); + } + } + + @Test + public void testLogErrorMessageStringStringString() { + try { + LoggingUtils.logErrorMessage("TARGET_SERVICE_NAME", "ADDITIONAL_MESSAGE", "CLASS_NAME"); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking logErrorMessage: " + e.toString()); + } + } + + @Test + public void testLogError() { + try { + Class<?>[] paramString = { String.class, String.class, String.class, String.class, String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("logError", paramString); + m.setAccessible(true); + m.invoke(null, "ERROR_CODE", "ERROR_DESCRIPTION", "TARGET_ENTITY", "TARGET_SERVICE_NAME", "ADDITIONAL_MESSAGE", "CLASS_NAME"); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking logError: " + e.toString()); + } + } + + @Test + public void testLogAuditMessage() { + try { + Class<?>[] paramString = { Instant.class, Instant.class, String.class, String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("logAuditMessage", paramString); + m.setAccessible(true); + java.util.Date timestamp = new java.util.Date(); + m.invoke(null, timestamp.toInstant(), timestamp.toInstant(), "CODE", "RESPONSE_DESCRIPTION", "CLASS_NAME"); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking logAuditMessage: " + e.toString()); + } + } + + @Test + public void testAuditInfo() { + try { + EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + auditLogger.info("Audit logging test info"); + } catch (Exception e) { + fail("Exception invoking testAuditInfo: " + e.toString()); + } + } + + @Test + public void testAuditWarn() { + try { + EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + auditLogger.warn("Audit logging test warning"); + } catch (Exception e) { + fail("Exception invoking testAuditWarn: " + e.toString()); + } + } + + @Test + public void testLogMetricsMessage() { + try { + java.util.Date timestamp = new java.util.Date(); + LoggingUtils.logMetricsMessage(timestamp.toInstant(), timestamp.toInstant(), "TARGET_ENTITY", "TARGET_SERVICE_NAME", "STATUS_CODE", "RESPONSE_CODE", "RESPONSE_DESCRIPTION", "CLASS_NAME"); + assertNull(MDC.get(LoggingConstants.MDCKeys.STATUS_CODE)); + + } catch (Exception e) { + fail("Exception invoking logMetricsMessage: " + e.toString()); + } + } + + @Test + public void testPopulateAuditLogContext() { + try { + Class<?>[] paramString = { Instant.class, Instant.class, String.class, String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("populateAuditLogContext", paramString); + m.setAccessible(true); + java.util.Date timestamp = new java.util.Date(); + m.invoke(null, timestamp.toInstant(), timestamp.toInstant(), "100", "RESPONSE_DESCRIPTION", "CLASS_NAME"); + assertEquals("COMPLETE", MDC.get(LoggingConstants.MDCKeys.STATUS_CODE)); + assertEquals("100", MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE)); + assertEquals("RESPONSE_DESCRIPTION", MDC.get(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION)); + } catch (Exception e) { + fail("Exception invoking populateAuditLogContext: " + e.toString()); + } + } + + @Test + public void testCleanAuditErrorContext() { + try { + Method m = LoggingUtils.class.getDeclaredMethod("cleanAuditErrorContext"); + m.setAccessible(true); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, "STATUS_CODE"); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, "RESPONSE_CODE"); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, "RESPONSE_DESCRIPTION"); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, "CLASS_NAME"); + m.invoke(null); + assertNull(MDC.get(LoggingConstants.MDCKeys.STATUS_CODE)); + assertNull(MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE)); + assertNull(MDC.get(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION)); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking cleanAuditErrorLogContext: " + e.toString()); + } + } + + @Test + public void testPopulateErrorLogContext() { + try { + Class<?>[] paramString = { String.class, String.class, String.class, String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("populateErrorLogContext", paramString); + m.setAccessible(true); + m.invoke(null, "ERROR_CODE", "ERROR_DESCRIPTION", "TARGET_ENTITY", "TARGET_SERVICENAME", "CLASS_NAME"); + assertEquals("CLASS_NAME", MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking populateErrorLogContext: " + e.toString()); + } + } + + @Test + public void testCleanErrorLogContext() { + try { + Method m = LoggingUtils.class.getDeclaredMethod("cleanErrorLogContext"); + m.setAccessible(true); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, "CLASS_NAME"); + m.invoke(null); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking cleanErrorLogContext: " + e.toString()); + } + } + + @Test + public void testPopulateMetricLogContext() { + try { + Class<?>[] paramString = { Instant.class, Instant.class, String.class, String.class, String.class, + String.class, String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("populateMetricLogContext", paramString); + m.setAccessible(true); + java.util.Date timestamp = new java.util.Date(); + m.invoke(null, timestamp.toInstant(), timestamp.toInstant(), "TARGET_ENTITY", "TARGET_SERVICE_NAME", "STATUS_CODE", "RESPONSE_CODE", "RESPONSE_DESCRIPTION", "CLASS_NAME"); + assertEquals("STATUS_CODE", MDC.get(LoggingConstants.MDCKeys.STATUS_CODE)); + assertEquals("RESPONSE_CODE", MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE)); + assertEquals("RESPONSE_DESCRIPTION", MDC.get(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION)); + } catch (Exception e) { + fail("Exception invoking populateMetricLogContext: " + e.toString()); + } + } + + @Test + public void testCleanMetricContext() { + try { + Method m = LoggingUtils.class.getDeclaredMethod("cleanMetricContext"); + m.setAccessible(true); + MDC.put(LoggingConstants.MDCKeys.CLASS_NAME, "CLASS_NAME"); + m.invoke(null); + assertNull(MDC.get(LoggingConstants.MDCKeys.CLASS_NAME)); + } catch (Exception e) { + fail("Exception invoking cleanMetricContext: " + e.toString()); + } + } + + @Test + public void testPopulateTargetContext() { + try { + Class<?>[] paramString = { String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("populateTargetContext", paramString); + m.setAccessible(true); + m.invoke(null, "TARGET_ENTITY", "TARGET_SERVICE_NAME"); + assertEquals("TARGET_ENTITY", MDC.get(LoggingConstants.MDCKeys.TARGET_ENTITY)); + assertEquals("TARGET_SERVICE_NAME", MDC.get(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME)); + } catch (Exception e) { + fail("Exception invoking populateTargetContext: " + e.toString()); + } + } + + @Test + public void testCleanTargetContext() { + try { + Method m = LoggingUtils.class.getDeclaredMethod("cleanTargetContext"); + m.setAccessible(true); + MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "TARGET_ENTITY"); + MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "TARGET_SERVICE_NAME"); + m.invoke(null); + assertNull(MDC.get(LoggingConstants.MDCKeys.TARGET_ENTITY)); + assertNull(MDC.get(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME)); + } catch (Exception e) { + fail("Exception invoking cleanTargetContext: " + e.toString()); + } + } + + @Test + public void testPopulateTimeContext() { + try { + Class<?>[] paramString = { Instant.class, Instant.class }; + Method m = LoggingUtils.class.getDeclaredMethod("populateTimeContext", paramString); + m.setAccessible(true); + java.util.Date timestamp = new java.util.Date(); + m.invoke(null, timestamp.toInstant(), timestamp.toInstant()); + } catch (Exception e) { + fail("Exception invoking populateTimeContext: " + e.toString()); + } + } + + @Test + public void testGenerateTimestampStr() { + try { + Class<?>[] paramString = { Instant.class }; + Method m = LoggingUtils.class.getDeclaredMethod("generateTimestampStr", paramString); + m.setAccessible(true); + java.util.Date timestamp = new java.util.Date(); + assertNotNull((String) m.invoke(null, timestamp.toInstant())); + } catch (Exception e) { + fail("Exception invoking testGenerateTimestampStr: " + e.toString()); + } + + } + + @Test + public void testCleanTimeContext() { + try { + Method m = LoggingUtils.class.getDeclaredMethod("cleanTimeContext"); + m.setAccessible(true); + MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, "BEGIN_TIMESTAMP"); + MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, "END_TIMESTAMP"); + MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "ELAPSED_TIME"); + m.invoke(null); + assertNull(MDC.get(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP)); + assertNull(MDC.get(LoggingConstants.MDCKeys.END_TIMESTAMP)); + assertNull(MDC.get(LoggingConstants.MDCKeys.ELAPSED_TIME)); + } catch (Exception e) { + fail("Exception invoking cleanErrorContext: " + e.toString()); + } + } + + @Test + public void testPopulateResponseContext() { + try { + Class<?>[] paramString = { String.class, String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("populateResponseContext", paramString); + m.setAccessible(true); + m.invoke(null, "STATUS_CODE", "RESPONSE_CODE", "RESPONSE_DESCRIPTION"); + assertEquals("STATUS_CODE", MDC.get(LoggingConstants.MDCKeys.STATUS_CODE)); + assertEquals("RESPONSE_CODE", MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE)); + assertEquals("RESPONSE_DESCRIPTION", MDC.get(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION)); + } catch (Exception e) { + fail("Exception invoking populateResponseContext: " + e.toString()); + } + } + + @Test + public void testCleanResponseContext() { + try { + Method m = LoggingUtils.class.getDeclaredMethod("cleanResponseContext"); + m.setAccessible(true); + MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, "STATUS_CODE"); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_CODE, "RESPONSE_CODE"); + MDC.put(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION, "RESPONSE_DESCRIPTION"); + m.invoke(null); + assertNull(MDC.get(LoggingConstants.MDCKeys.STATUS_CODE)); + assertNull(MDC.get(LoggingConstants.MDCKeys.RESPONSE_CODE)); + assertNull(MDC.get(LoggingConstants.MDCKeys.RESPONSE_DESCRIPTION)); + } catch (Exception e) { + fail("Exception invoking cleanErrorContext: " + e.toString()); + } + } + + @Test + public void testPopulateErrorContext() { + try { + Class<?>[] paramString = { String.class, String.class }; + Method m = LoggingUtils.class.getDeclaredMethod("populateErrorContext", paramString); + m.setAccessible(true); + m.invoke(null, "ERROR_CODE", "ERROR_DESCRIPTION"); + assertEquals("ERROR_CODE", MDC.get(LoggingConstants.MDCKeys.ERROR_CODE)); + assertEquals("ERROR_DESCRIPTION", MDC.get(LoggingConstants.MDCKeys.ERROR_DESCRIPTION)); + } catch (Exception e) { + fail("Exception invoking populateErrorContext: " + e.toString()); + } + } + + @Test + public void testCleanErrorContext() { + try { + Method m = LoggingUtils.class.getDeclaredMethod("cleanErrorContext"); + m.setAccessible(true); + MDC.put(LoggingConstants.MDCKeys.ERROR_CODE, "ERROR_CODE"); + MDC.put(LoggingConstants.MDCKeys.ERROR_DESCRIPTION, "ERROR_DESCRIPTION"); + m.invoke(null); + assertNull(MDC.get(LoggingConstants.MDCKeys.ERROR_CODE)); + assertNull(MDC.get(LoggingConstants.MDCKeys.ERROR_DESCRIPTION)); + } catch (Exception e) { + fail("Exception invoking cleanErrorContext: " + e.toString()); + } + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/metadata/impl/MetadataServiceImplTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/metadata/impl/MetadataServiceImplTest.java new file mode 100644 index 000000000..90ad524b2 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/metadata/impl/MetadataServiceImplTest.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.appc.metadata.impl; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.sql.SQLException; +import java.util.ArrayList; +import javax.sql.rowset.CachedRowSet; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.cache.MetadataCache; +import org.onap.appc.metadata.objects.DependencyModelIdentifier; +import org.onap.ccsdk.sli.core.dblib.DbLibService; + +public class MetadataServiceImplTest { + + + private MetadataServiceImpl metadataService = new MetadataServiceImpl(); + private DbLibService mockDbLibService = mock(DbLibService.class); + private CachedRowSet mockCachedRowSet = mock(CachedRowSet.class); + private MetadataCache<DependencyModelIdentifier, String> mockCache = mock(MetadataCache.class); + private DependencyModelIdentifier mockModelIdentifier = mock(DependencyModelIdentifier.class); + + @Before + public void setup() throws SQLException { + metadataService.setDbLibService(mockDbLibService); + metadataService.setCache(mockCache); + } + + @Test + public void getVnfModel_should_return_vnfModel_when_present_in_cache() throws SQLException { + when(mockCache.getObject(mockModelIdentifier)).thenReturn("test-vnf-model"); + + assertEquals("test-vnf-model", metadataService.getVnfModel(mockModelIdentifier)); + + verify(mockCache).getObject(mockModelIdentifier); + verify(mockDbLibService, never()).getData(anyString(), any(ArrayList.class), anyString()); + verify(mockCache, never()).putObject(any(DependencyModelIdentifier.class), anyString()); + } + + @Test + public void getVnfModel_should_read_from_database_when_null_vnfName_and_return_when_found() + throws SQLException { + + when(mockCache.getObject(any(DependencyModelIdentifier.class))).thenReturn(null); + when(mockModelIdentifier.getCatalogVersion()).thenReturn("test-vnf-catalog-version"); + when(mockDbLibService.getData(anyString(), any(ArrayList.class), anyString())).thenReturn(mockCachedRowSet); + when(mockCachedRowSet.first()).thenReturn(true); + when(mockCachedRowSet.getString("ARTIFACT_CONTENT")).thenReturn("test-vnf-model"); + + assertEquals("test-vnf-model", metadataService.getVnfModel(mockModelIdentifier)); + + verify(mockDbLibService).getData(anyString(), any(ArrayList.class), anyString()); + verify(mockCachedRowSet).getString("ARTIFACT_CONTENT"); + verify(mockCache).putObject(mockModelIdentifier, "test-vnf-model"); + } + + @Test(expected = RuntimeException.class) + public void getVnfModel_should_read_from_database_when_null_vnfName_and_throw_when_invalid_dependency_model() + throws SQLException { + + when(mockCache.getObject(any(DependencyModelIdentifier.class))).thenReturn(null); + when(mockModelIdentifier.getCatalogVersion()).thenReturn(null); + + when(mockDbLibService.getData(anyString(), any(ArrayList.class), anyString())).thenReturn(mockCachedRowSet); + when(mockCachedRowSet.first()).thenReturn(true); + when(mockCachedRowSet.getString("ARTIFACT_CONTENT")).thenReturn(null); + + assertEquals(null, metadataService.getVnfModel(mockModelIdentifier)); + + verify(mockDbLibService).getData(anyString(), any(ArrayList.class), anyString()); + verify(mockCachedRowSet).getString("ARTIFACT_CONTENT"); + verify(mockCache, never()).putObject(mockModelIdentifier, "test-vnf-model"); + + } + + @Test(expected = RuntimeException.class) + public void getVnfModel_should_read_from_database_when_null_vnfName_and_throw_when_database_error() + throws SQLException { + + when(mockCache.getObject(any(DependencyModelIdentifier.class))).thenReturn(null); + when(mockModelIdentifier.getCatalogVersion()).thenReturn(null); + when(mockDbLibService.getData(anyString(), any(ArrayList.class), anyString())).thenThrow(new SQLException()); + + assertEquals(null, metadataService.getVnfModel(mockModelIdentifier)); + + verify(mockDbLibService).getData(anyString(), any(ArrayList.class), anyString()); + verify(mockCachedRowSet, times(0)).getString("ARTIFACT_CONTENT"); + verify(mockCache, never()).putObject(any(DependencyModelIdentifier.class), anyString()); + } + + + @Test + public void getVnfModel_should_read_from_database_when_null_vnfName_and_return_null_when_not_found() + throws SQLException { + + when(mockCache.getObject(any(DependencyModelIdentifier.class))).thenReturn(null); + when(mockModelIdentifier.getCatalogVersion()).thenReturn(null); + when(mockDbLibService.getData(anyString(), any(ArrayList.class), anyString())).thenReturn(mockCachedRowSet); + when(mockCachedRowSet.first()).thenReturn(false); + + assertEquals(null, metadataService.getVnfModel(mockModelIdentifier)); + + verify(mockDbLibService).getData(anyString(), any(ArrayList.class), anyString()); + verify(mockCachedRowSet, times(0)).getString("ARTIFACT_CONTENT"); + verify(mockCache, never()).putObject(any(DependencyModelIdentifier.class), anyString()); + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/metadata/objects/DependencyModelIdentifierTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/metadata/objects/DependencyModelIdentifierTest.java new file mode 100644 index 000000000..f9aae99f5 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/metadata/objects/DependencyModelIdentifierTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.metadata.objects; + +import static org.onap.appc.metadata.objects.DependencyModelIdentifier.prime; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +public class DependencyModelIdentifierTest { + private static final String vnfType = "vnfType"; + private static final String vnfType2 = "vnfType2"; + private static final String cVersion = "catalogVersion"; + private DependencyModelIdentifier identifier; + private DependencyModelIdentifier identifier1; + private DependencyModelIdentifier identifier2; + private DependencyModelIdentifier identifier3; + + @Before + public void setUp() throws Exception { + identifier = new DependencyModelIdentifier(vnfType, cVersion); + identifier1 = new DependencyModelIdentifier(null, null); + identifier2 = new DependencyModelIdentifier(vnfType, null); + identifier3 = new DependencyModelIdentifier(null, cVersion); + } + + @Test + public void testConstructorAndGetterAndToString() throws Exception { + Assert.assertEquals(vnfType, Whitebox.getInternalState(identifier, "vnfType")); + Assert.assertEquals(cVersion, Whitebox.getInternalState(identifier, "catalogVersion")); + + Assert.assertEquals(vnfType, identifier.getVnfType()); + Assert.assertEquals(cVersion, identifier.getCatalogVersion()); + + Assert.assertEquals( + String.format(DependencyModelIdentifier.TO_STRING_FORMAT, vnfType, cVersion), + identifier.toString()); + } + + @Test + public void testHashCode() throws Exception { + Assert.assertEquals((prime + vnfType.hashCode()) * prime + cVersion.hashCode(), + identifier.hashCode()); + Assert.assertEquals(prime * prime, identifier1.hashCode()); + Assert.assertEquals((prime + vnfType.hashCode()) * prime, identifier2.hashCode()); + Assert.assertEquals(prime * prime + cVersion.hashCode(), identifier3.hashCode()); + } + + @Test + public void testEquals() throws Exception { + // other object is null + Assert.assertFalse(identifier.equals(null)); + // other object is wrong data type + Assert.assertFalse(identifier.equals("abc")); + + // my vnfType is null + Assert.assertFalse(identifier1.equals(identifier)); + // different vnfType + DependencyModelIdentifier identifier4 = new DependencyModelIdentifier(vnfType2, cVersion); + Assert.assertFalse(identifier.equals(identifier4)); + // same vnfType, my catalogVerson is null + Assert.assertFalse(identifier2.equals(identifier)); + // same vnfType and both catalogVersion are null + identifier4 = new DependencyModelIdentifier(vnfType, null); + Assert.assertTrue(identifier2.equals(identifier4)); + + Assert.assertFalse(identifier.equals(identifier1)); + Assert.assertFalse(identifier.equals(identifier2)); + Assert.assertFalse(identifier.equals(identifier3)); + + Assert.assertFalse(identifier2.equals(identifier1)); + Assert.assertFalse(identifier2.equals(identifier3)); + + + Assert.assertFalse(identifier3.equals(identifier)); + Assert.assertFalse(identifier3.equals(identifier1)); + Assert.assertFalse(identifier3.equals(identifier2)); + + identifier4 = new DependencyModelIdentifier(vnfType, cVersion); + Assert.assertTrue(identifier.equals(identifier4)); + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/CachedElementTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/CachedElementTest.java new file mode 100644 index 000000000..02bdd3be3 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/CachedElementTest.java @@ -0,0 +1,275 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.pool.Allocator; +import org.onap.appc.pool.CachedElement; +import org.onap.appc.pool.Destructor; +import org.onap.appc.pool.Pool; +import org.onap.appc.pool.PoolDrainedException; +import org.onap.appc.pool.PoolExtensionException; +import org.onap.appc.pool.PoolSpecificationException; +import org.onap.appc.pool.*; + + +public class CachedElementTest implements Allocator<Testable>, Destructor<Testable> { + private static final int MIN = 10; + private static final int MAX = 100; + private Pool<Testable> pool; + private int index = 0; + private int destroyCount = 0; + + /** + * setup + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Before + public void setup() throws PoolSpecificationException { + pool = new Pool<>(MIN, MAX); + } + + /** + * Test state + */ + @Test + public void testAllocator() { + assertNull(pool.getAllocator()); + pool.setAllocator(this); + assertNotNull(pool.getAllocator()); + } + + /** + * Test state + */ + @Test + public void testDestructor() { + assertNull(pool.getDestructor()); + pool.setDestructor(this); + assertNotNull(pool.getDestructor()); + } + + /** + * Test that we can allocate and release elements and that the pool maintains them in MRU order + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @Test + public void testAllocateAndRelease() throws PoolExtensionException, PoolDrainedException { + pool.setAllocator(this); + + assertFalse(pool.isDrained()); + + /* + * Allocate three elements + */ + Testable value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 1), Integer.valueOf(value1.getId())); + assertEquals(1, pool.getAllocatedSize()); + assertEquals(MIN - 1, pool.getFreeSize()); + assertEquals(1, pool.getAllocatedSize()); + + Testable value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), Integer.valueOf(value2.getId())); + assertEquals(2, pool.getAllocatedSize()); + assertEquals(MIN - 2, pool.getFreeSize()); + assertEquals(2, pool.getAllocatedSize()); + + Testable value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 3), Integer.valueOf(value3.getId())); + assertEquals(3, pool.getAllocatedSize()); + assertEquals(MIN - 3, pool.getFreeSize()); + assertEquals(3, pool.getAllocatedSize()); + + /* + * Now, release them in the order obtained + */ + pool.release(value1); + pool.release(value2); + pool.release(value3); + + assertEquals(0, pool.getAllocatedSize()); + assertEquals(MIN, pool.getFreeSize()); + + /* + * Now, allocate them again, but their values should be reversed (3, 2, 1) representing the most recently used + * to the least recently used. + */ + value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 3), Integer.valueOf(value1.getId())); + + value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), Integer.valueOf(value2.getId())); + + value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 1), Integer.valueOf(value3.getId())); + } + + /** + * Test that we can trim the pool to a desired size + * + * @throws PoolDrainedException + * If the caller is trying to release or reserve an element from a drained pool + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws IllegalAccessException + * if this Method object is enforcing Java language access control and the underlying method is + * inaccessible. + * @throws IllegalArgumentException + * if the method is an instance method and the specified object argument is not an instance of the class + * or interface declaring the underlying method (or of a subclass or implementor thereof); if the number + * of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or + * if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal + * parameter type by a method invocation conversion. + * @throws InvocationTargetException + * if the underlying method throws an exception. + * @throws SecurityException + * If a security manager, s, is present and any of the following conditions is met: + * <ul> + * <li>invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared method</li> + * <li>the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class</li> + * </ul> + * @throws NoSuchMethodException + * if a matching method is not found. + */ + @SuppressWarnings("nls") + @Test + public void testTrim() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, + PoolDrainedException, PoolExtensionException, NoSuchMethodException, SecurityException { + + pool.setAllocator(this); + int SIZE = 50; + Testable[] array = new Testable[SIZE]; + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < SIZE; i++) { + pool.release(array[i]); + } + assertEquals(0, pool.getAllocatedSize()); + + assertEquals(SIZE, pool.getFreeSize()); + + Method trimMethod = Pool.class.getDeclaredMethod("trim", new Class[] { + Integer.TYPE + }); + trimMethod.setAccessible(true); + trimMethod.invoke(pool, new Object[] { + SIZE - MIN + }); + + assertEquals(MIN, pool.getFreeSize()); + } + + /** + * Test that we can drain a pool containing a mix of free and allocated elements + * + * @throws PoolDrainedException + * If the caller is trying to release or reserve an element from a drained pool + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws IOException + * if an I/O error occurs + */ + @Test + public void testDrain() throws PoolExtensionException, PoolDrainedException, IOException { + int SIZE = 50; + int FREE = 20; + int ALLOC = SIZE - FREE; + + Testable[] array = new Testable[SIZE]; + pool.setAllocator(this); + pool.setDestructor(this); + + assertFalse(pool.isDrained()); + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < FREE; i++) { + array[i].close(); + } + assertEquals(ALLOC, pool.getAllocatedSize()); + assertEquals(FREE, pool.getFreeSize()); + + pool.drain(); + assertEquals(0, pool.getFreeSize()); + assertEquals(0, pool.getAllocatedSize()); + assertTrue(pool.isDrained()); + + assertEquals(SIZE, destroyCount); + } + + /** + * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) + */ + @Override + public Testable allocate(Pool<Testable> pool) { + Testable element = new Element(index++); + Testable ce = CachedElement.newInstance(pool, element, new Class[] { + Testable.class + }); + return ce; + } + + /** + * @see org.onap.appc.pool.Destructor#destroy(java.io.Closeable, org.onap.appc.pool.Pool) + */ + @Override + public void destroy(Testable obj, Pool<Testable> pool) { + destroyCount++; + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/Element.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/Element.java new file mode 100644 index 000000000..14f3e0e15 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/Element.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import java.io.IOException; + +public class Element implements Testable { + private boolean closed; + private Integer id; + + public Element(int id) { + this.id = Integer.valueOf(id); + closed = false; + } + + @Override + public boolean equals(Object obj) { + boolean result = false; + if (obj instanceof Element) { + Element other = (Element) obj; + result = this.id.equals(other.id); + } + + return result; + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + /** + * @see java.io.Closeable#close() + */ + @Override + public void close() throws IOException { + closed = true; + } + + @Override + public Boolean isClosed() { + return Boolean.valueOf(closed); + } + + @Override + public String toString() { + return Integer.toString(id); + } + + @Override + public Integer getId() { + return id; + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolDrainedExceptionTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolDrainedExceptionTest.java new file mode 100644 index 000000000..c7b03f33c --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolDrainedExceptionTest.java @@ -0,0 +1,36 @@ +/*-
+* ============LICENSE_START=======================================================
+* ONAP : APPC
+* ================================================================================
+* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+* =============================================================================
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+* ============LICENSE_END=========================================================
+*/
+package org.onap.appc.pool;
+
+import org.junit.Assert;
+
+import org.junit.Test;
+
+public class PoolDrainedExceptionTest {
+
+ @Test
+ public void testPoolDrainedException() {
+ String message = "test message";
+ PoolDrainedException poolDrainedExp = new PoolDrainedException(message);
+ Assert.assertEquals(message, poolDrainedExp.getMessage());
+ Assert.assertEquals(message, poolDrainedExp.getLocalizedMessage());
+ }
+
+}
diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolExceptionTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolExceptionTest.java new file mode 100644 index 000000000..34ecd85e0 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolExceptionTest.java @@ -0,0 +1,73 @@ +/*-
+* ============LICENSE_START=======================================================
+* ONAP : APPC
+* ================================================================================
+* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+* =============================================================================
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+* ============LICENSE_END=========================================================
+*/
+package org.onap.appc.pool;
+
+import org.junit.Assert;
+
+import org.junit.Test;
+
+public class PoolExceptionTest {
+
+ @Test
+ public void testPoolException() {
+ PoolException poolException = new PoolException();
+ Assert.assertTrue(poolException.getCause() == null);
+ Assert.assertTrue(poolException.getMessage() == null);
+ }
+
+ @Test
+ public void testPoolExceptionString() {
+ String message = "test message";
+ PoolException poolException = new PoolException(message);
+ Assert.assertEquals(message, poolException.getMessage());
+ Assert.assertEquals(message, poolException.getLocalizedMessage());
+ }
+
+ @Test
+ public void testPoolExceptionThrowable() {
+ String tMessage = "throwable message";
+ Throwable throwable = new Throwable(tMessage);
+ PoolException poolException = new PoolException(throwable);
+ Assert.assertEquals(throwable, poolException.getCause());
+ }
+
+ @Test
+ public void testPoolExceptionStringThrowable() {
+ String message = "my test message";
+ String tMessage = "throwable message";
+ Throwable throwable = new Throwable(tMessage);
+ PoolException poolException = new PoolException(message, throwable);
+ Assert.assertEquals(throwable, poolException.getCause());
+ Assert.assertTrue(poolException.getMessage().contains(message));
+ Assert.assertEquals(message, poolException.getLocalizedMessage());
+ }
+
+ @Test
+ public void testPoolExceptionStringThrowableBooleanBoolean() {
+ String message = "my test message";
+ String tMessage = "throwable message";
+ Throwable throwable = new Throwable(tMessage);
+ PoolException poolException = new PoolException(message, throwable, true, true);
+ Assert.assertEquals(throwable, poolException.getCause());
+ Assert.assertTrue(poolException.getMessage().contains(message));
+ Assert.assertEquals(message, poolException.getLocalizedMessage());
+ }
+
+}
diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolExtensionExceptionTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolExtensionExceptionTest.java new file mode 100644 index 000000000..615233d74 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolExtensionExceptionTest.java @@ -0,0 +1,36 @@ +/*-
+* ============LICENSE_START=======================================================
+* ONAP : APPC
+* ================================================================================
+* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+* =============================================================================
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+* ============LICENSE_END=========================================================
+*/
+package org.onap.appc.pool;
+
+import org.junit.Assert;
+
+import org.junit.Test;
+
+public class PoolExtensionExceptionTest {
+
+ @Test
+ public void testPoolExtensionException() {
+ String message = "test message";
+ PoolExtensionException poolExtExcpt = new PoolExtensionException(message);
+ Assert.assertEquals(message, poolExtExcpt.getMessage());
+ Assert.assertEquals(message, poolExtExcpt.getLocalizedMessage());
+ }
+
+}
diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolTest.java new file mode 100644 index 000000000..d61296ac6 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/PoolTest.java @@ -0,0 +1,332 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modifications Copyright (C) 2018 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.pool; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.pool.Allocator; +import org.onap.appc.pool.Destructor; +import org.onap.appc.pool.Pool; +import org.onap.appc.pool.PoolDrainedException; +import org.onap.appc.pool.PoolExtensionException; +import org.onap.appc.pool.PoolSpecificationException; +import org.onap.appc.pool.*; + + +public class PoolTest implements Allocator<Testable>, Destructor<Testable> { + + private Pool<Testable> pool; + private static final int MIN = 10; + private static final int MAX = 100; + private int index = 0; + private int destroyCount = 0; + + /** + * Set up the test by allocating a pool with MIN-MAX size (bounded pool) + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Before + public void setup() throws PoolSpecificationException { + pool = new Pool<>(MIN, MAX); + index = 0; + destroyCount = 0; + } + + /** + * Test that trying to construct a pool with a bad minimum throws an exception + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Test(expected = PoolSpecificationException.class) + public void testInvalidMinSize() throws PoolSpecificationException { + pool = new Pool<>(-1, MAX); + } + + /** + * Test that trying to construct a pool with a bad maximum throws an exception + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Test(expected = PoolSpecificationException.class) + public void testInvalidMaxSize() throws PoolSpecificationException { + pool = new Pool<>(MIN, -1); + } + + /** + * Test creation of a pool where max is less than min fails + * + * @throws PoolSpecificationException + * If the minimum size is less than 0, or if the max size is non-zero and less than the min size. + */ + @Test(expected = PoolSpecificationException.class) + public void testInvalidSizeRange() throws PoolSpecificationException { + pool = new Pool<>(MAX, MIN); + } + + /** + * Test state + */ + @Test + public void testMinPool() { + assertEquals(MIN, pool.getMinPool()); + } + + /** + * Test state + */ + @Test + public void testMaxPool() { + assertEquals(MAX, pool.getMaxPool()); + } + + /** + * Test state + */ + @Test + public void testAllocator() { + assertNull(pool.getAllocator()); + pool.setAllocator(this); + assertNotNull(pool.getAllocator()); + } + + /** + * Test state + */ + @Test + public void testDestructor() { + assertNull(pool.getDestructor()); + pool.setDestructor(this); + assertNotNull(pool.getDestructor()); + } + + /** + * Test that we can allocate and release elements and that the pool maintains them in MRU order + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @Test + public void testAllocateAndRelease() throws PoolExtensionException, PoolDrainedException { + pool.setAllocator(this); + + assertFalse(pool.isDrained()); + + /* + * Allocate three elements + */ + Testable value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 1), value1.getId()); + assertEquals(1, pool.getAllocatedSize()); + assertEquals(MIN - 1, pool.getFreeSize()); + assertEquals(1, pool.getAllocatedSize()); + + Testable value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), value2.getId()); + assertEquals(2, pool.getAllocatedSize()); + assertEquals(MIN - 2, pool.getFreeSize()); + assertEquals(2, pool.getAllocatedSize()); + + Testable value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 3), value3.getId()); + assertEquals(3, pool.getAllocatedSize()); + assertEquals(MIN - 3, pool.getFreeSize()); + assertEquals(3, pool.getAllocatedSize()); + + /* + * Now, release them in the order obtained + */ + pool.release(value1); + pool.release(value2); + pool.release(value3); + + assertEquals(0, pool.getAllocatedSize()); + assertEquals(MIN, pool.getFreeSize()); + + /* + * Now, allocate them again, but their values should be reversed (3, 2, 1) representing the most recently used + * to the least recently used. + */ + value1 = pool.reserve(); + assertNotNull(value1); + assertEquals(Integer.valueOf(MIN - 3), value1.getId()); + + value2 = pool.reserve(); + assertNotNull(value2); + assertEquals(Integer.valueOf(MIN - 2), value2.getId()); + + value3 = pool.reserve(); + assertNotNull(value3); + assertEquals(Integer.valueOf(MIN - 1), value3.getId()); + } + + /** + * Test that we can trim the pool to a desired size + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws NoSuchMethodException + * if a matching method is not found. + * @throws SecurityException + * if the request is denied. + * @throws IllegalAccessException + * if this Method object is enforcing Java language access control and the underlying method is + * inaccessible. + * @throws IllegalArgumentException + * if the method is an instance method and the specified object argument is not an instance of the class + * or interface declaring the underlying method (or of a subclass or implementor thereof); if the number + * of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or + * if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal + * parameter type by a method invocation conversion. + * @throws InvocationTargetException + * if the underlying method throws an exception. + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @SuppressWarnings("nls") + @Test + public void testTrim() throws PoolExtensionException, NoSuchMethodException, SecurityException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException, PoolDrainedException { + pool.setAllocator(this); + int SIZE = 50; + Proxy[] array = new Proxy[SIZE]; + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = (Proxy) pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < SIZE; i++) { + pool.release((Testable) array[i]); + } + assertEquals(0, pool.getAllocatedSize()); + + assertEquals(SIZE, pool.getFreeSize()); + + Method trimMethod = Pool.class.getDeclaredMethod("trim", new Class[] { + Integer.TYPE + }); + trimMethod.setAccessible(true); + trimMethod.invoke(pool, new Object[] { + SIZE - MIN + }); + + assertEquals(MIN, pool.getFreeSize()); + } + + /** + * Test that we can drain a pool containing a mix of free and allocated elements + * + * @throws PoolExtensionException + * If the pool cannot be extended + * @throws PoolDrainedException + * If the caller is trying to reserve an element from a drained pool + */ + @Test + public void testDrain() throws PoolExtensionException, PoolDrainedException { + int SIZE = 50; + int FREE = 20; + int ALLOC = SIZE - FREE; + + Proxy[] array = new Proxy[SIZE]; + pool.setAllocator(this); + pool.setDestructor(this); + + assertFalse(pool.isDrained()); + + assertEquals(0, pool.getAllocatedSize()); + for (int i = 0; i < SIZE; i++) { + array[i] = (Proxy) pool.reserve(); + } + assertEquals(SIZE, pool.getAllocatedSize()); + + for (int i = 0; i < FREE; i++) { + pool.release((Testable) array[i]); + } + assertEquals(ALLOC, pool.getAllocatedSize()); + assertEquals(FREE, pool.getFreeSize()); + + pool.drain(); + assertEquals(0, pool.getFreeSize()); + assertEquals(0, pool.getAllocatedSize()); + assertTrue(pool.isDrained()); + + assertEquals(SIZE, destroyCount); + } + + /** + * @see org.onap.appc.pool.Destructor#destroy(java.io.Closeable, org.onap.appc.pool.Pool) + */ + @Override + public void destroy(Testable obj, Pool<Testable> pool) { + destroyCount++; + try { + obj.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * @see org.onap.appc.pool.Allocator#allocate(org.onap.appc.pool.Pool) + */ + @Override + public Testable allocate(Pool<Testable> pool) { + Testable e = new Element(index++); + + return e; + } + + @Test + public void testGetAndSetProperties() throws PoolSpecificationException + { + pool= new Pool<Testable>(3, 5); + pool.setProperty("key1", "value1"); + assertEquals("value1", pool.getProperty("key1")); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/Testable.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/Testable.java new file mode 100644 index 000000000..22c940895 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/pool/Testable.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.pool; + +import java.io.Closeable; + +public interface Testable extends Closeable { + + Integer getId(); + + Boolean isClosed(); +} + diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/JsonUtilTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/JsonUtilTest.java new file mode 100644 index 000000000..9de45545c --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/JsonUtilTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import java.io.FileNotFoundException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; + + +public class JsonUtilTest { + + @Test(expected = NullPointerException.class) + public void should_throw_exception_when_json_string_is_null() throws IOException { + + JsonUtil.convertJsonStringToFlatMap(null); + } + + @Test(expected = JsonParseException.class) + public void should_throw_exception_when_invalid_json_string() throws IOException { + + JsonUtil.convertJsonStringToFlatMap("{key: value}"); + } + + @Test + public void should_convert_json_string_to_flat_map() throws IOException { + + String jsonString = "{\"A\":\"A-value\",\"B\":{\"C\":\"B.C-value\",\"D\":\"B.D-value\"}}"; + Map<String, String> flatMap = JsonUtil.convertJsonStringToFlatMap(jsonString); + + Map<String, String> expectedMap = new HashMap<>(); + expectedMap.put("A", "A-value"); + expectedMap.put("B.C", "B.C-value"); + expectedMap.put("B.D", "B.D-value"); + + assertEquals(expectedMap, flatMap); + assertNotNull(flatMap); + } + + @Test + public void should_convert_json_string_to_flat_map_with_nested_json() throws IOException { + + String jsonString = "{\"A\":\"A-value\",\"B\":\"{\\\"C\\\":\\\"C-value\\\",\\\"D\\\":\\\"D-value\\\"}\"}"; + Map<String, String> flatMap = JsonUtil.convertJsonStringToFlatMap(jsonString); + + Map<String, String> expectedMap = new HashMap<>(); + expectedMap.put("A", "A-value"); + expectedMap.put("B", "{\"C\":\"C-value\",\"D\":\"D-value\"}"); + + assertEquals(expectedMap, flatMap); + assertNotNull(flatMap); + } + + @Test(expected = FileNotFoundException.class) + public void should_throw_exception_when_not_found_json_file() throws IOException { + JsonUtil.readInputJson("not-existing.json", DummyClass.class); + } + + + @Test(expected = JsonParseException.class) + public void should_throw_exception_when_invalid_json_file() throws IOException { + JsonUtil.readInputJson("/invalid.json", DummyClass.class); + } + + @Test + public void should_parse_valid_json_file () throws IOException { + DummyClass dummyClass = JsonUtil.readInputJson("/valid.json", DummyClass.class); + + assertEquals("dummy name", dummyClass.getName()); + assertEquals(99, dummyClass.getValue()); + } + + private static class DummyClass { + + private String name; + private int value; + + public DummyClass(@JsonProperty("name") String name, @JsonProperty("value") int someValue) { + this.name = name; + this.value = someValue; + } + + public String getName() { + return name; + } + + public int getValue() { + return value; + } + } +} + + diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/MessageFormatterTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/MessageFormatterTest.java new file mode 100644 index 000000000..fe7d1a532 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/MessageFormatterTest.java @@ -0,0 +1,78 @@ +package org.onap.appc.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Maps; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +public class MessageFormatterTest { + + @Test + public void format_should_return_empty_string_when_given_null_or_empty_message_template() { + assertEquals(StringUtils.EMPTY, MessageFormatter.format(null, Maps.newHashMap())); + assertEquals(StringUtils.EMPTY, MessageFormatter.format(StringUtils.EMPTY, Maps.newHashMap())); + } + + @Test + public void should_return_same_string_when_given_null_or_empty_params() { + String message = "message"; + + assertEquals(message, MessageFormatter.format(message, null)); + assertEquals(message, MessageFormatter.format(message, Maps.newHashMap())); + } + + @Test + public void should_return_same_string_when_given_non_dollar_string() { + String msg = "vnfid"; + + Map<String, Object> respMsg = new HashMap<>(); + respMsg.put("vnfid", "SYNC_NEW201"); + + assertEquals(msg, MessageFormatter.format(msg, respMsg)); + } + + + @Test + public void should_replace_dollar_sign_statement_with_map_value() { + String message = "${vnfid} some sample text ${pnfid} additional sample text"; + + Map<String, Object> respMsg = new HashMap<>(); + respMsg.put("vnfid", "SYNC_NEW201"); + respMsg.put("pnfid", "TEST-ID"); + + assertEquals("SYNC_NEW201 some sample text TEST-ID additional sample text", + MessageFormatter.format(message, respMsg)); + } + + @Test + public void getParamsNamesList_should_return_null_when_given_null_or_empty_message_template() { + assertEquals(null, MessageFormatter.getParamsNamesList(null)); + assertEquals(null, MessageFormatter.getParamsNamesList(StringUtils.EMPTY)); + + assertEquals(null, MessageFormatter.getParamsNamesSet(null)); + assertEquals(null, MessageFormatter.getParamsNamesSet(StringUtils.EMPTY)); + } + + @Test + public void should_recognize_params_inside_message_string() { + String message = "${vnfid} some sample text ${pnfid} additional sample text"; + + List<String> resultList = MessageFormatter.getParamsNamesList(message); + + assertEquals(2, resultList.size()); + assertTrue(resultList.contains("vnfid")); + assertTrue(resultList.contains("pnfid")); + + Set<String> resultSet = MessageFormatter.getParamsNamesSet(message); + + assertEquals(2, resultList.size()); + assertTrue(resultSet.contains("vnfid")); + assertTrue(resultSet.contains("pnfid")); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/PathContextTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/PathContextTest.java new file mode 100644 index 000000000..ef538d2e1 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/PathContextTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ +package org.onap.appc.util; + +import static org.junit.Assert.*; + +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class PathContextTest { + + private PathContext pathContext; + + @Before + public void setup() { + pathContext = new PathContext(); + } + + @Test(expected = IllegalArgumentException.class) + public void should_throw_exception_when_pushed_null_token() { + pathContext.pushToken(null); + } + + @Test(expected = IllegalStateException.class) + public void should_throw_exception_when_popped_token_from_empty_path() { + pathContext.popToken(); + } + + @Test + public void should_delimit_tokens_with_dot() { + pathContext.pushToken("test"); + pathContext.pushToken("token"); + + assertEquals("test.token", pathContext.getPath()); + } + + @Test + public void should_pop_tokens() { + pathContext.pushToken("test"); + pathContext.pushToken("token"); + pathContext.pushToken("token2"); + + pathContext.popToken(); + + assertEquals("test.token", pathContext.getPath()); + } + + @Test(expected = IllegalArgumentException.class) + public void should_throw_exception_when_pushed_null_modifier() { + pathContext.pushModifier(null); + } + + @Test(expected = IllegalStateException.class) + public void should_throw_exception_when_popped_modifier_from_empty_path() { + pathContext.popModifier(); + } + + @Test + public void should_not_delimit_modifiers() { + pathContext.pushModifier("test"); + pathContext.pushModifier("modifier"); + + assertEquals("testmodifier", pathContext.getPath()); + } + + @Test + public void should_pop_modifiers() { + pathContext.pushModifier("test"); + pathContext.pushModifier("modifier"); + pathContext.pushModifier("modifier2"); + + pathContext.popModifier(); + + assertEquals("testmodifier", pathContext.getPath()); + } + + @Test + public void should_pop_modifiers_and_tokens() { + pathContext.pushModifier("test"); + pathContext.pushModifier("modifier"); + pathContext.pushToken("token"); + + //TODO popToken() and popModifier() actually work the same. + //TODO Is there sense to keep same method under different names then? + + pathContext.popToken(); + assertEquals("testmodifier", pathContext.getPath()); + + pathContext.popModifier(); + assertEquals("test", pathContext.getPath()); + } + + @Test + public void should_add_entries(){ + pathContext.entry("name", "value"); + + Map<String, String> entries = pathContext.entries(); + assertEquals("value", entries.get("name")); + } + +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/StreamHelperTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/StreamHelperTest.java new file mode 100644 index 000000000..73c32d644 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/StreamHelperTest.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; + +import org.junit.Test; +import org.onap.appc.util.StreamHelper; + +public class StreamHelperTest { + + private static final String text = "Filler text (also placeholder text or dummy text) is text that shares " + + "some characteristics of a real written text, but is random or otherwise generated. It may be used " + + "to display a sample of fonts, generate text for testing, or to spoof an e-mail spam filter. The " + + "process of using filler text is sometimes called greeking, although the text itself may be nonsense, " + + "or largely Latin, as in Lorem ipsum.\nASDF is the sequence of letters that appear on the first four " + + "keys on the home row of a QWERTY or QWERTZ keyboard. They are often used as a sample or test case " + + "or as random, meaningless nonsense. It is also a common learning tool for keyboard classes, since " + + "all four keys are located on Home row.\nETAOIN SHRDLU is the approximate order of frequency of the " + + "twelve most commonly used letters in the English language, best known as a nonsense phrase that " + + "sometimes appeared in print in the days of \"hot type\" publishing due to a custom of Linotype " + + "machine operators.\nLorem ipsum... is one of the most common filler texts, popular with " + + "typesetters and graphic designers. \"Li Europan lingues...\" is another similar example.\n" + + "Now is the time for all good men to come to the aid of the party\" is a phrase first proposed " + + "as a typing drill by instructor Charles E. Weller; its use is recounted in his book The Early " + + "History of the Typewriter, p. 21 (1918).[1] Frank E. McGurrin, an expert on the early Remington " + + "typewriter, used it in demonstrating his touch typing abilities in January 1889.[2] It has " + + "appeared in a number of typing books, often in the form \"Now is the time for all good men to " + + "come to the aid of their country.\"\nThe quick brown fox jumps over the lazy dog - A coherent, " + + "short phrase that uses every letter of the alphabet. See pangram for more examples.\nNew Petitions" + + " and Building Code - Many B movies of the 1940s, 50s, and 60s utilized the \"spinning newspaper\" " + + "effect to narrate important plot points that occurred offscreen. The effect necessitated the " + + "appearance of a realistic front page, which consisted of a main headline relevant to the plot, " + + "and several smaller headlines used as filler. A large number of these spinning newspapers " + + "included stories titled \"New Petitions Against Tax\" and \"Building Code Under Fire.\" These " + + "phrases have become running jokes among B movie fans, and particularly fans of Mystery " + + "Science Theater 3000. \nCharacter Generator Protocol - The Character Generator Protocol " + + "(CHARGEN) service is an Internet protocol intended for testing, debugging, and measurement " + + "purposes.\n!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefgh\n\"" + + "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghi\n" + + "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghij\n" + + "$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijk\n"; + + @Test + public void should_return_empty_string_when_given_null_input_stream() { + assertNotNull(StreamHelper.getStringFromInputStream(null)); + assertEquals("", StreamHelper.getStringFromInputStream(null)); + } + + @Test + public void should_return_empty_string_when_given_empty_byte_array() { + ByteArrayInputStream emptyInputStream = new ByteArrayInputStream(new byte[0]); + + assertEquals("", StreamHelper.getStringFromInputStream(emptyInputStream)); + } + + @Test + public void should_return_string_when_given_byte_array() { + ByteArrayInputStream inputStream = new ByteArrayInputStream(text.getBytes()); + + assertEquals(text, StreamHelper.getStringFromInputStream(inputStream)); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/StringHelperTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/StringHelperTest.java new file mode 100644 index 000000000..1022440b0 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/StringHelperTest.java @@ -0,0 +1,403 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * Modifications Copyright (C) 2018 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Date; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.onap.appc.util.StringHelper; + + +public class StringHelperTest { + + //TODO write more tests for convertToRegex method + + @Test + public void convertToRegex_should_return_regex_matching_all_string_when_given_null_or_empty_string(){ + assertEquals(".*", StringHelper.convertToRegex(null)); + assertEquals(".*", StringHelper.convertToRegex("")); + assertEquals(".*", StringHelper.convertToRegex(" ")); + } + + @Test + public void convertToRegex_should_return_proper_regex_when_we_provide_a_proper_string_expression(){ + String expected=".*test\\.jpg.test123\\.jpeg$"; + assertEquals(expected,StringHelper.convertToRegex("*test.jpg+test123.jpeg")); + } + + @Test + public void test_ResolveToType_with_null_as_input(){ + assertNull(StringHelper.resolveToType(null)); + } + + @Test + public void test_ResolveToType_with_integer_as_input(){ + Integer expected=-112; + assertEquals(expected,StringHelper.resolveToType("-112")); + } + + @Test + public void test_ResolveToType_with_double_as_input(){ + Double expected=-112.12; + assertEquals(expected,StringHelper.resolveToType("-112.12")); + } + + @Test + public void test_ResolveToType_with_boolean_as_input(){ + Boolean expected=true; + assertEquals(expected,StringHelper.resolveToType("true")); + } + + @Test + public void test_ResolveToType_with_date_as_input(){ + assertTrue(StringHelper.resolveToType("1994-11-05T08:15:30-05:00") instanceof Date); + } + + + @Test + public void getShortenedString_should_return_null_when_given_null(){ + assertNull(StringHelper.getShortenedString(null, 2)); + } + + @Test + public void getShortenedString_should_return_given_string_when_length_is_lower_than_4(){ + assertEquals("str", StringHelper.getShortenedString("str", 3)); + assertEquals("str", StringHelper.getShortenedString("str", 2)); + assertEquals("test", StringHelper.getShortenedString("test", 3)); + } + + @Test + public void getShortenedString_should_shorten_string_and_append_ellipsis(){ + + assertEquals("s...", StringHelper.getShortenedString("sample", 4)); + assertEquals("test...", StringHelper.getShortenedString("test string", 7)); + } + + @Test + public void isNotNullNotEmpty_should_return_true_if_string_is_not_null_or_not_empty(){ + assertFalse(StringHelper.isNotNullNotEmpty(null)); + assertFalse(StringHelper.isNotNullNotEmpty("")); + assertFalse(StringHelper.isNotNullNotEmpty(" ")); + assertTrue(StringHelper.isNotNullNotEmpty("test")); + } + + @Test + public void isNullOrEmpty_should_return_true_if_string_is_null_or_empty(){ + assertTrue(StringHelper.isNullOrEmpty(null)); + assertTrue(StringHelper.isNullOrEmpty("")); + assertTrue(StringHelper.isNullOrEmpty(" ")); + assertFalse(StringHelper.isNullOrEmpty("test")); + } + + @Test + public void areEqual_should_return_true_when_both_null(){ + assertTrue(StringHelper.areEqual(null, null)); + } + + @Test + public void areEqual_should_return_false_when_one_string_is_null(){ + assertFalse(StringHelper.areEqual(null, "test")); + } + + @Test + public void areEqual_should_compare_two_string(){ + assertFalse(StringHelper.areEqual("test2", "test")); + assertFalse(StringHelper.areEqual("test", "Test")); + } + + @Test + public void equalsIgnoreCase_should_compare_two_string_case_insensitive(){ + assertFalse(StringHelper.equalsIgnoreCase("test2", "test")); + assertTrue(StringHelper.equalsIgnoreCase("test", "Test")); + } + + @Test + public void mangleName_should_pad_string_when_given_null_or_empty(){ + assertEquals("aaaa", StringHelper.mangleName(null, 3, 6)); + assertEquals("aaaa", StringHelper.mangleName(StringUtils.EMPTY, 3, 6)); + + assertEquals("aa", StringHelper.mangleName(null, 1, 6)); + assertEquals("aa", StringHelper.mangleName(StringUtils.EMPTY, 1, 6)); + + assertEquals("aaaaaaaaa", StringHelper.mangleName(null, 8, 12)); + assertEquals("aaaaaaaaa", StringHelper.mangleName(StringUtils.EMPTY, 8, 12)); + + } + + @Test + public void mangleName_should_remove_all_illegal_characters(){ + assertEquals("ab45", StringHelper.mangleName("ab45 ", 3, 6)); + assertEquals("ab45", StringHelper.mangleName("ab!45", 3, 6)); + assertEquals("ab45", StringHelper.mangleName("a b!45", 3, 6)); + } + + @Test + public void mangleName_should_convert_all_character_to_lowercase(){ + assertEquals("test", StringHelper.mangleName("TeSt", 3, 6)); + assertEquals("abb45fgr", StringHelper.mangleName("abB!4 5FGR", 6, 8)); + } + + @Test + public void mangleName_should_pad_string_when_result_is_too_short(){ + assertEquals("testaaa", StringHelper.mangleName("TeSt", 6, 10)); + assertEquals("abb45fgraaaaa", StringHelper.mangleName("abB!4 5FGR", 12, 15)); + } + + @Test + public void mangleName_should_truncate_string_when_too_long(){ + assertEquals("tst", StringHelper.mangleName("TeSt", 0, 3)); + assertEquals("tt", StringHelper.mangleName("TeSt", 0, 2)); + assertEquals("agr", StringHelper.mangleName("abb45fgr", 0, 3)); + assertEquals("abgr", StringHelper.mangleName("abb45fgr", 0, 4)); + } + + @Test + public void normalizeString_should_return_null_when_given_null_or_empty_string(){ + assertNull(StringHelper.normalizeString(null)); + assertNull(StringHelper.normalizeString(StringUtils.EMPTY)); + } + + @Test + public void normalizeString_should_trim_string(){ + assertEquals("this is test sequence", + StringHelper.normalizeString(" this is test sequence ")); + assertEquals("this is test sequence", + StringHelper.normalizeString(" this is test sequence ")); + } + + @Test + public void stripCRLFs_should_return_null_when_given_null() { + assertNull(StringHelper.stripCRLF(null)); + } + + @Test + public void stripCRLF_should_strip_all_CRLF_and_LF() { + assertEquals(StringUtils.EMPTY, StringHelper.toUnixLines(StringUtils.EMPTY)); + assertEquals("this is test sequence", StringHelper.stripCRLF("this is test sequence")); + assertEquals("this is testsequence", StringHelper.stripCRLF("this is test\nsequence")); + assertEquals("this istestsequence", StringHelper.stripCRLF("this is\ntest\r\nsequence")); + assertEquals("this istestsequence", StringHelper.stripCRLF("this is\r\ntest\n\rsequence")); + } + + @Test + public void toDOSLines_should_return_null_when_given_null() { + assertNull(StringHelper.toDOSLines(null)); + } + + @Test + public void toUnixLines_should_replace_LF_with_CRLF() { + assertEquals(StringUtils.EMPTY, StringHelper.toUnixLines(StringUtils.EMPTY)); + assertEquals("this is test sequence", StringHelper.toDOSLines("this is test sequence")); + assertEquals("this is test\r\nsequence", StringHelper.toDOSLines("this is test\nsequence")); + assertEquals("this is test\rsequence", StringHelper.toDOSLines("this is test\rsequence")); + assertEquals("this is\r\ntest\n\rsequence", StringHelper.toDOSLines("this is\r\ntest\n\rsequence")); + } + + @Test + public void toUnixLines_should_return_null_when_given_null() { + assertNull(StringHelper.toUnixLines(null)); + } + + @Test + public void toUnixLines_should_replace_CRLF_with_LF() { + assertEquals(StringUtils.EMPTY, StringHelper.toUnixLines(StringUtils.EMPTY)); + assertEquals("this is test sequence", StringHelper.toUnixLines("this is test sequence")); + assertEquals("this is test\nsequence", StringHelper.toUnixLines("this is test\nsequence")); + assertEquals("this is\ntest\nsequence", StringHelper.toUnixLines("this is\r\ntest\n\rsequence")); + } + + @Test + public void translate_should_return_null_when_given_null_sequence() { + assertNull(StringHelper.translate(null, "abc", "def")); + } + + @Test + public void translate_should_translate_sequence() { + + assertEquals(StringUtils.EMPTY, StringHelper.translate(StringUtils.EMPTY, "abc", "def")); + assertEquals("ahis is absa sbqubccb", + StringHelper.translate("this is test sequence", "ten", "abc")); + } + + + @Test + public void translate_should_translate_sequence_given_replacement_longer_then_match() { + assertEquals("ahis is absa sbqubccb", + StringHelper.translate("this is test sequence", "ten", "abcde")); + } + + @Test + public void translate_should_translate_sequence_given_replacement_shorter_then_match() { + assertEquals("ahas as absa sbqubccb", + StringHelper.translate("this is test sequence", "teni", "abc")); + } + + @Test + public void validIdentifier_should_return_null_when_given_null() { + assertNull(StringHelper.validIdentifier(null)); + } + + + @Test + public void validIdentifier_should_return_valid_identifier() { + assertEquals(StringUtils.EMPTY, StringHelper.validIdentifier(StringUtils.EMPTY)); + assertEquals("abcd", StringHelper.validIdentifier("abcd")); + assertEquals("abc_", StringHelper.validIdentifier("abc!")); + assertEquals("ab_cd", StringHelper.validIdentifier("ab cd")); + assertEquals("ab_cd_", StringHelper.validIdentifier("ab cd!")); + } + + @Test + public void verify_should_return_null_when_given_null_sequence() { + assertNull(StringHelper.verify(null, "abc", 'r')); + } + + @Test + public void verify_should_return_empty_string_when_given_empty_sequence() { + assertEquals(StringUtils.EMPTY, StringHelper.verify("", "abc", 'r')); + } + + @Test + public void verify_should_replace_illegal_characters() { + assertEquals("trir ir tert rerterre", + StringHelper.verify("this is test sentence", "iet ", 'r')); + } + + @Test + public void toList_should_return_empty_string_when_given_null_or_empty_list() { + assertEquals(StringUtils.EMPTY, StringHelper.asList((List<String>) null)); + assertEquals(StringUtils.EMPTY, StringHelper.asList((Lists.newArrayList()))); + } + + @Test + public void toList_should_return_element_when_given_one_element_list() { + assertEquals("test", StringHelper.asList(Lists.newArrayList("test"))); + } + + @Test + public void toList_should_convert_to_string_given_list() { + assertEquals("test, test2, test3", + StringHelper.asList(Lists.newArrayList("test", "test2", "test3"))); + } + + @Test + public void toList_should_return_empty_string_when_given_null_or_empty_map() { + assertEquals(StringUtils.EMPTY, StringHelper.asList((Map<String, String>) null)); + assertEquals(StringUtils.EMPTY, StringHelper.asList((Maps.newHashMap()))); + } + + @Test + public void toList_should_return_entry_when_given_one_entry_map() { + Map<String, String> testMap = new HashMap<>(); + testMap.put("key1", "value1"); + + assertEquals("key1=value1", StringHelper.asList(testMap)); + } + + @Test + public void toList_should_convert_to_string_given_map() { + Map<String, String> testMap = new HashMap<>(); + testMap.put("key1", "value1"); + testMap.put("key2", "value2"); + + assertEquals("key1=value1, key2=value2", StringHelper.asList(testMap)); + } + + @Test + public void toList_should_return_string_representation_of_empty_array_when_given_null() { + String value = StringHelper.asList((String[]) null); + assertNotNull(value); + assertEquals("[]", value); + } + + @Test + public void toList_should_return_string_representation_of_empty_array_when_given_empty_array() { + String value = StringHelper.asList(new String[]{}); + assertNotNull(value); + assertEquals("[]", value); + } + + @Test + public void toList_should_return_string_representation_of_one_element_array() { + String value = StringHelper.asList("one"); + assertNotNull(value); + assertEquals("[one]", value); + } + + @Test + public void toList_should_return_string_representation_of_array() { + String value = StringHelper.asList("one", "two", "three", "four", "five"); + assertNotNull(value); + assertEquals("[one,two,three,four,five]", value); + } + + @Test + public void propertiesToString_should_return_null_when_given_null_properties() { + + assertEquals(null, StringHelper.propertiesToString(null)); + } + + @Test + public void propertiesToString_should_return_string_representation_of_empty_array_when_given_empty_properties() { + + Properties props = new Properties(); + + String result = StringHelper.propertiesToString(props); + assertNotNull(result); + assertEquals("[ ]", result); + } + + @Test + public void propertiesToString_should_return_convert_properties_to_string() { + Properties props = new Properties(); + props.setProperty("key1", "value1"); + props.setProperty("key2", "value2"); + + String result = StringHelper.propertiesToString(props); + + assertTrue(result.startsWith("[ ")); + assertTrue(result.contains("key1")); + assertTrue(result.contains("value1")); + assertTrue(result.contains("key2")); + assertTrue(result.contains("value2")); + assertTrue(result.endsWith(" ]")); + assertTrue(result.lastIndexOf(",") < result.length() - 3); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/TestStructuredPropertyHelper.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/TestStructuredPropertyHelper.java new file mode 100644 index 000000000..e61531a8b --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/TestStructuredPropertyHelper.java @@ -0,0 +1,284 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modifications Copyright (C) 2018 IBM. + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.util; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.util.StructuredPropertyHelper; +import org.onap.appc.util.StructuredPropertyHelper.Node; + +/** + * This class is used to test the structured property helper class. + * <p> + * A structured property is one where the name is constructed from a compound set of elements, concatenated by a period, + * and optionally being enumerated using a sequence number suffix. A java package name is an example of a structured + * name, where each element of the name represents a directory or name in the namespace hierarchy. Property names may + * also be structured. This class constructs a graph of the structured properties and this test case is used to verify + * its operation. + * </p> + * + */ +public class TestStructuredPropertyHelper { + + /** + * The properties to be parsed + */ + private Properties properties; + + /** + * The result of parsing the properties + */ + private List<Node> nodes = new ArrayList<>(); + + /** + * Initialize the test environment + */ + @SuppressWarnings("nls") + @Before + public void setup() { + nodes.clear(); + + properties = new Properties(); + + properties.setProperty("provider1.name", "provider1Name"); + properties.setProperty("provider1.type", "provider1type"); + properties.setProperty("provider1.URL", "provider1URL"); + properties.setProperty("provider2.name", "provider2Name"); + properties.setProperty("provider2.type", "provider2type"); + properties.setProperty("provider2.URL", "provider2URL"); + properties.setProperty("provider003.name", "provider3Name"); + properties.setProperty("provider003.type", "provider3type"); + properties.setProperty("provider003.URL", "provider3URL"); + + properties.setProperty("node1.level1.value1.key", "1.1.1"); + properties.setProperty("node1.level1.value2.key", "1.1.2"); + properties.setProperty("node1.level1.value3.key", "1.1.3"); + properties.setProperty("node1.level2.value1.key", "1.2.1"); + properties.setProperty("node1.level2.value2.key", "1.2.2"); + properties.setProperty("node1.level2.value3.key", "1.2.3"); + properties.setProperty("node1.level3.value1.key", "1.3.1"); + properties.setProperty("node1.level3.value2.key", "1.3.2"); + properties.setProperty("node1.level3.value3.key", "1.3.3"); + properties.setProperty("node2.level1.value1.key", "2.1.1"); + properties.setProperty("node2.level1.value2.key", "2.1.2"); + properties.setProperty("node2.level1.value3.key", "2.1.3"); + properties.setProperty("node2.level2.value1.key", "2.2.1"); + properties.setProperty("node2.level2.value2.key", "2.2.2"); + properties.setProperty("node2.level2.value3.key", "2.2.3"); + properties.setProperty("node2.level3.value1.key", "2.3.1"); + properties.setProperty("node2.level3.value2.key", "2.3.2"); + properties.setProperty("node2.level3.value3.key", "2.3.3"); + properties.setProperty("node3.level1.value1.key", "3.1.1"); + properties.setProperty("node3.level1.value2.key", "3.1.2"); + properties.setProperty("node3.level1.value3.key", "3.1.3"); + properties.setProperty("node3.level2.value1.key", "3.2.1"); + properties.setProperty("node3.level2.value2.key", "3.2.2"); + properties.setProperty("node3.level2.value3.key", "3.2.3"); + properties.setProperty("node3.level3.value1.key", "3.3.1"); + properties.setProperty("node3.level3.value2.key", "3.3.2"); + properties.setProperty("node3.level3.value3.key", "3.3.3"); + + properties.setProperty("other.property", "bogus"); + properties.setProperty("yet.another.property", "bogus"); + properties.setProperty("simpleProperty", "bogus"); + + } + + /** + * Test that a simple namespace works + */ + @SuppressWarnings("nls") + @Test + public void testSimpleNamespace() { + nodes = StructuredPropertyHelper.getStructuredProperties(properties, "provider"); + + assertNotNull(nodes); + assertFalse(nodes.isEmpty()); + + assertEquals(3, nodes.size()); + + List<Node> children; + for (Node node : nodes) { + switch (node.getName()) { + case "provider1": + assertNull(node.getValue()); + children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + switch (child.getName()) { + case "URL": + assertEquals("provider1URL", child.getValue()); + break; + case "type": + assertEquals("provider1type", child.getValue()); + break; + case "name": + assertEquals("provider1Name", child.getValue()); + break; + default: + fail("Unknown child of " + node.getName() + " with value " + child.toString()); + } + } + break; + case "provider2": + assertNull(node.getValue()); + children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + switch (child.getName()) { + case "URL": + assertEquals("provider2URL", child.getValue()); + break; + case "type": + assertEquals("provider2type", child.getValue()); + break; + case "name": + assertEquals("provider2Name", child.getValue()); + break; + default: + fail("Unknown child of " + node.getName() + " with value " + child.toString()); + } + } + break; + case "provider3": + /* + * Note that the helper normalizes any ordinal suffixes (003 became 3) + */ + assertNull(node.getValue()); + children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + switch (child.getName()) { + case "URL": + assertEquals("provider3URL", child.getValue()); + break; + case "type": + assertEquals("provider3type", child.getValue()); + break; + case "name": + assertEquals("provider3Name", child.getValue()); + break; + default: + fail("Unknown child of " + node.getName() + " with value " + child.toString()); + } + } + break; + default: + fail("Unknown provider " + node.toString()); + } + } + // System.out.println(nodes); + } + + /** + * Test a multi-dimensional namespace (3X3X3) + */ + @SuppressWarnings("nls") + @Test + public void testMultiLevelNamespace() { + nodes = StructuredPropertyHelper.getStructuredProperties(properties, "node"); + + assertNotNull(nodes); + assertFalse(nodes.isEmpty()); + + assertEquals(3, nodes.size()); + for (Node node : nodes) { + assertNull(node.getValue()); + List<Node> children = node.getChildren(); + assertNotNull(children); + assertEquals(3, children.size()); + for (Node child : children) { + assertNull(child.getValue()); + List<Node> grandChildren = child.getChildren(); + assertNotNull(grandChildren); + assertEquals(3, grandChildren.size()); + for (Node greatGrandChild : grandChildren) { + assertNull(greatGrandChild.getValue()); + List<Node> greatGrandChildren = greatGrandChild.getChildren(); + assertNotNull(greatGrandChildren); + assertEquals(1, greatGrandChildren.size()); + } + } + } + // System.out.println(nodes); + } + + @Test + public void testToStringWithValue() + { + nodes = StructuredPropertyHelper.getStructuredProperties(properties, "node"); + Node node = nodes.get(0); + node.setName("testName"); + node.setValue("testValue"); + String str= node.toString(); + assertEquals("testName = testValue",str); + } + + @Test + public void testEquals() + { + Node node0 = new Node(); + node0.setName("testName"); + node0.setValue("testValue"); + Node node1 = new Node(); + node1.setName("testName"); + node1.setValue("testValue"); + assertTrue(node0.equals(node1)); + } + + @Test + public void testEqualsWithSameNameAndDifferentValue() + { + Node node0 = new Node(); + node0.setName("testName"); + node0.setValue("testValue1"); + Node node1 = new Node(); + node1.setName("testName"); + node1.setValue("testValue2"); + assertFalse(node0.equals(node1)); + } + + @Test + public void testEqualsWithSameValueAndDifferentName() + { + Node node0 = new Node(); + node0.setName("testName1"); + node0.setValue("testValue"); + Node node1 = new Node(); + node1.setName("testName2"); + node1.setValue("testValue"); + assertFalse(node0.equals(node1)); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/TimeTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/TimeTest.java new file mode 100644 index 000000000..961a62c0a --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/TimeTest.java @@ -0,0 +1,150 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 IBM + * ============================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END========================================================= + */ + + +package org.onap.appc.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.text.ParseException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import javax.xml.datatype.XMLGregorianCalendar; + +import org.junit.Test; + + +public class TimeTest { + + @Test + public void testAddTime() { + + final Date dateNow = new Date(); + long dateNowMSec = dateNow.getTime(); + Date dateSecLater = Time.addTime(dateNow, 0, 0, 0, 0, 1); + long dateSecLaterMSec = dateSecLater.getTime(); + assertEquals(dateNowMSec + 1000, dateSecLaterMSec); + + } + + @Test + public void testDateOnly() { + + final Date dateNow = new Date(); + Calendar cal = Calendar.getInstance(); + cal.setTime(dateNow); + + Time.dateOnly(cal); + + long msecFromBegin = cal.get(Calendar.HOUR_OF_DAY)*60*60*1000 + + cal.get(Calendar.MINUTE)*60*1000 + + cal.get(Calendar.SECOND)*1000 + + cal.get(Calendar.MILLISECOND); + + assertEquals( msecFromBegin, 0); + + } + + @Test + public void testGetCurrentUTCDate() { + + Date utcDate = Time.getCurrentUTCDate(); + + ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC); + + long epochSecs = utc.toEpochSecond(); + + long utcSecs = utcDate.getTime() / 1000; + + assertEquals(epochSecs, utcSecs); + } + + @Test + public void testEndOfDayLocal() { + final Date dateNow = new Date(); + assertTrue(Time.endOfDayLocal(dateNow) instanceof Date); + } + + @Test + public void testGetDateByLocaleAndTimeZone() { + final Date dateNow = new Date("19-Jul-2018"); + Locale locale = new Locale("fr"); + TimeZone timeZone = TimeZone.getTimeZone("Europe/France"); + assertNotNull(Time.getDateByLocaleAndTimeZone(dateNow,locale,timeZone)); + assertTrue(Time.getDateByLocaleAndTimeZone(dateNow,locale,timeZone) instanceof String); + } + + @Test + public void testUtcFormat() { + final Date date = new Date("19-Jul-2018"); + assertNotNull(Time.utcFormat(date)); + assertTrue(Time.utcFormat(date) instanceof String); + } + + //this test succeeds if localTime() does not throw an exception + @Test + public void testLocalTime() { + Time.localTime(1532083631); + } + + @Test + public void testSetDate() { + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.YEAR, 2018); + cal.set(Calendar.MONTH, 07); + cal.set(Calendar.DAY_OF_MONTH, 03); + Calendar cal1= Time.setDate(cal, 2018, 07, 03); + assertEquals(cal, cal1); + } + + @Test + public void testStartOfDayLocal() { + assertTrue(Time.startOfDayLocal() instanceof Date); + } + + @Test + public void testTimeStamp() { + assertTrue(Time.timestamp() instanceof XMLGregorianCalendar); + } + + @Test + public void testDateToStringConverterMillis() { + String dateString=Time.dateToStringConverterMillis(new Date("02/09/2004")); + String expected="2004-02-09 00:00:00:000"; + assertEquals(expected, dateString); + } + + @Test + public void testStringToDateConverterMillis() throws ParseException{ + Date date=Time.stringToDateConverterMillis("2004-02-09 00:00:00:000"); + Date expected=new Date("02/09/2004"); + assertEquals(expected, date); + } +} diff --git a/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/UnmodifiablePropertiesTest.java b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/UnmodifiablePropertiesTest.java new file mode 100644 index 000000000..87646d9c7 --- /dev/null +++ b/appc-core/appc-common-bundle/src/test/java/org/onap/appc/util/UnmodifiablePropertiesTest.java @@ -0,0 +1,342 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.util;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.hamcrest.CoreMatchers;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.StringReader;
+import java.util.Enumeration;
+import java.util.Properties;
+
+public class UnmodifiablePropertiesTest {
+
+ private static final String propKey1 = "testKey1";
+ private static final String propKey2 = "testKey2";
+ private static final String propValue1 = "testValue1";
+ private static final String propValue2 = "testValue2";
+ private static final String noKey = "unusedKey";
+ private static final String noValue = "unusedValue";
+ private static final String propHeader = "test header";
+ private Properties properties = new Properties();
+
+ private UnmodifiableProperties unmodifiableProperties = new UnmodifiableProperties(properties);
+ private String desiredMessage = "Property cannot be modified!";
+
+ @Before
+ public void setUp() throws Exception {
+ properties.setProperty(propKey1, propValue1);
+ properties.setProperty(propKey2, propValue2);
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testClear() {
+ try {
+ unmodifiableProperties.clear();
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testClone() {
+ try {
+ unmodifiableProperties.clone();
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test
+ public final void testContainsObject() {
+ Assert.assertTrue(unmodifiableProperties.contains(propValue2));
+ Assert.assertFalse(unmodifiableProperties.contains(noValue));
+ }
+
+ @Test
+ public final void testContainsKeyObject() {
+ Assert.assertTrue(unmodifiableProperties.containsKey(propKey1));
+ Assert.assertFalse(unmodifiableProperties.containsKey(noKey));
+ }
+
+ @Test
+ public final void testContainsValueObject() {
+ Assert.assertTrue(unmodifiableProperties.containsValue(propValue1));
+ Assert.assertFalse(unmodifiableProperties.containsValue(noValue));
+ }
+
+ @Test
+ public final void testElements() {
+ Enumeration<Object> propValues = unmodifiableProperties.elements();
+ Assert.assertEquals(propValue2, propValues.nextElement());
+ Assert.assertEquals(propValue1, propValues.nextElement());
+ }
+
+ @Test
+ public final void testEntrySet() {
+ // Expect entrySet=[testKey2=testValue2, testKey1=testValue1].
+ Assert.assertEquals("Should match my properties K/V entries in setUp", properties.entrySet(),
+ unmodifiableProperties.entrySet());
+ }
+
+ @Test
+ public final void testEqualsObject() {
+ Assert.assertTrue(unmodifiableProperties.equals(properties));
+ }
+
+ @Test
+ public final void testGetObject() {
+ Assert.assertEquals(propValue2, unmodifiableProperties.get(propKey2));
+ }
+
+ @Test
+ public final void testGetPropertyString() {
+ Assert.assertEquals(propValue1, unmodifiableProperties.getProperty("testKey1"));
+ }
+
+ @Test
+ public final void testGetPropertyStringString() {
+ Assert.assertEquals(propValue2, unmodifiableProperties.getProperty(propKey2, noValue));
+ Assert.assertEquals(propValue2, unmodifiableProperties.getProperty(noKey, propValue2));
+ }
+
+ @Test
+ public final void testHashCode() {
+ Assert.assertEquals("Should match my properties.hashcode() int.", properties.hashCode(),
+ unmodifiableProperties.hashCode());
+ }
+
+ @Test
+ public final void testIsEmpty() {
+ Assert.assertFalse(unmodifiableProperties.isEmpty());
+ }
+
+ @Test
+ public final void testKeys() {
+ Enumeration<Object> propKeys = unmodifiableProperties.keys();
+ Assert.assertEquals(propKey2, propKeys.nextElement());
+ Assert.assertEquals(propKey1, propKeys.nextElement());
+ }
+
+ @Test
+ public final void testKeySet() {
+ // Expect keySet=[testKey2, testKey1].
+ Assert.assertEquals("Should match my properties key entries in SetUp", properties.keySet(),
+ unmodifiableProperties.keySet());
+ }
+
+ @Test
+ public final void testListPrintStream() {
+ ByteArrayOutputStream propByteArray = new ByteArrayOutputStream();
+ PrintStream listOut = new PrintStream(propByteArray);
+ unmodifiableProperties.list(listOut);
+ String propList = new String(propByteArray.toByteArray());
+ Assert.assertThat(propList, CoreMatchers.containsString("testKey2=testValue2"));
+ Assert.assertThat(propList, CoreMatchers.containsString("testKey1=testValue1"));
+ }
+
+ @Test
+ public final void testListPrintWriter() {
+ StringWriter listOut = new StringWriter();
+ PrintWriter writer = new PrintWriter(listOut);
+ unmodifiableProperties.list(writer);
+ String propList = listOut.toString();
+ Assert.assertThat(propList, CoreMatchers.containsString("testKey2=testValue2"));
+ Assert.assertThat(propList, CoreMatchers.containsString("testKey1=testValue1"));
+ }
+
+ @Test
+ public final void testLoadInputStream() throws IOException {
+ InputStream mockInStream = Mockito.mock(InputStream.class);
+ try {
+ unmodifiableProperties.load(mockInStream);
+ } catch (IOException ex) {
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ }
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public final void testLoadReader() throws IOException {
+ String dummyPair = "key3=testKey3\nvalue3=testValue3";
+ StringReader reader = new StringReader(dummyPair);
+ try {
+ unmodifiableProperties.load(reader);
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test
+ public final void testLoadFromXMLInputStream() throws IOException {
+ InputStream mockInStream = Mockito.mock(InputStream.class);
+ try {
+ unmodifiableProperties.loadFromXML(mockInStream);
+ } catch (IOException ex) {
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ }
+ }
+
+ @Test
+ public final void testPropertyNames() {
+ Enumeration<?> propNames = unmodifiableProperties.propertyNames();
+ Assert.assertEquals(propKey2, propNames.nextElement());
+ Assert.assertEquals(propKey1, propNames.nextElement());
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public final void testPutObjectObject() {
+ try {
+ unmodifiableProperties.put(propKey2, propValue1);
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public final void testPutAllMapOfQextendsObjectQextendsObject() {
+ try {
+ unmodifiableProperties.putAll(properties);
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public final void testRehash() {
+ try {
+ unmodifiableProperties.rehash();
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public final void testRemoveObject() {
+ try {
+ unmodifiableProperties.remove(propKey1);
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test
+ public final void testSaveOutputStreamString() {
+ // Appl method is deprecated, but I still added this test since it is reachable.
+ OutputStream propByteArray = new ByteArrayOutputStream();
+ unmodifiableProperties.save(propByteArray, propHeader);
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.startsWith("#test header"));
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.containsString("testKey2=testValue2"));
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.containsString("testKey1=testValue1"));
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public final void testSetPropertyStringString() {
+ try {
+ unmodifiableProperties.setProperty(propKey1, propValue2);
+ } catch (UnsupportedOperationException exceptionMessage) {
+ Assert.assertEquals(desiredMessage, exceptionMessage.getMessage());
+ throw exceptionMessage;
+ }
+ }
+
+ @Test
+ public final void testSize() {
+ Assert.assertEquals(2, unmodifiableProperties.size());
+ }
+
+ @Test
+ public final void testStoreOutputStreamString() throws IOException {
+ OutputStream propByteArray = new ByteArrayOutputStream();
+ unmodifiableProperties.store(propByteArray, propHeader);
+ // adds comment header and streams/appends properties file into propByteArray
+ // expected = "#test header\n#<Date>\ntestKey2=testValue2\ntestKey1=testValue1"
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.startsWith("#test header"));
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.containsString("testKey2=testValue2"));
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.containsString("testKey1=testValue1"));
+ }
+
+ @Test
+ public final void testStoreWriterString() throws IOException {
+ StringWriter writer = new StringWriter();
+ unmodifiableProperties.store(writer, propHeader);
+ Assert.assertThat(writer.toString(), CoreMatchers.startsWith("#test header"));
+ Assert.assertThat(writer.toString(), CoreMatchers.containsString("testKey2=testValue2"));
+ Assert.assertThat(writer.toString(), CoreMatchers.containsString("testKey1=testValue1"));
+ }
+
+ @Test
+ public final void testStoreToXMLOutputStreamString() throws IOException {
+ OutputStream propByteArray = new ByteArrayOutputStream();
+ unmodifiableProperties.storeToXML(propByteArray, propHeader);
+ // adds XML comment header and streams/appends XML properties file into propByteArray
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.containsString("<comment>test header</comment>"));
+ Assert.assertThat(propByteArray.toString(),
+ CoreMatchers.containsString("<entry key=\"testKey2\">testValue2</entry>"));
+ Assert.assertThat(propByteArray.toString(),
+ CoreMatchers.containsString("<entry key=\"testKey1\">testValue1</entry>"));
+ }
+
+ @Test
+ public final void testStoreToXMLOutputStreamStringString() throws IOException {
+ OutputStream propByteArray = new ByteArrayOutputStream();
+ unmodifiableProperties.storeToXML(propByteArray, propHeader, "UTF-8");
+ // adds XML comment header and streams/appends XML properties file into propByteArray
+ Assert.assertThat(propByteArray.toString(), CoreMatchers.containsString("<comment>test header</comment>"));
+ Assert.assertThat(propByteArray.toString(),
+ CoreMatchers.containsString("<entry key=\"testKey2\">testValue2</entry>"));
+ Assert.assertThat(propByteArray.toString(),
+ CoreMatchers.containsString("<entry key=\"testKey1\">testValue1</entry>"));
+ }
+
+ @Test
+ public final void testStringPropertyNames() {
+ Assert.assertEquals(properties.stringPropertyNames(), unmodifiableProperties.stringPropertyNames());
+ }
+
+ @Test
+ public final void testToString() {
+ // toString=[{testKey2=testValue2, testKey1=testValue1}]
+ Assert.assertEquals(properties.toString(), unmodifiableProperties.toString());
+ }
+
+ @Test
+ public final void testValues() {
+ Assert.assertEquals(properties.values().toString(), unmodifiableProperties.values().toString());
+ }
+}
|