diff options
Diffstat (limited to 'music-core/src/test/java')
34 files changed, 4393 insertions, 0 deletions
diff --git a/music-core/src/test/java/LICENSE.txt b/music-core/src/test/java/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/music-core/src/test/java/LICENSE.txt @@ -0,0 +1,24 @@ + +The following license applies to all files in this and sub-directories. Licenses +are included in individual source files where appropriate, and if it differs +from this text, it supersedes this. Any file that does not have license text +defaults to being covered by this text; not all files support the addition of +licenses. +# +# ------------------------------------------------------------------------- +# Copyright (c) 2017 AT&T Intellectual Property +# +# 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. +# +# ------------------------------------------------------------------------- +#
\ No newline at end of file diff --git a/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java b/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java new file mode 100644 index 00000000..b7245d78 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java @@ -0,0 +1,345 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 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.music.cassandra; + +import static org.junit.Assert.*; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.junit.Test; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.main.MusicUtil; +//import org.onap.music.main.CorePropertiesLoader; +import org.onap.music.service.MusicCoreService; + +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.DataType; + +public class MusicUtilTest { + + private static final String XLATESTVERSION = "X-latestVersion"; + private static final String XMINORVERSION = "X-minorVersion"; + private static final String XPATCHVERSION = "X-patchVersion"; + + @Test + public void testGetCassName() { + MusicUtil.setCassName("Cassandra"); + assertTrue(MusicUtil.getCassName().equals("Cassandra")); + } + + @Test + public void testGetCassPwd() { + MusicUtil.setCassPwd("Cassandra"); + assertTrue(MusicUtil.getCassPwd().equals("Cassandra")); + } + + @Test + public void testMusicAafNs() { + MusicUtil.setMusicAafNs("ns"); + assertTrue("ns".equals(MusicUtil.getMusicAafNs())); + } + + @Test + public void testMusicCoreService() { + MusicUtil.setLockUsing(MusicUtil.CASSANDRA); + MusicCoreService mc = null; + mc = MusicUtil.getMusicCoreService(); + assertTrue(mc != null); + MusicUtil.setLockUsing("nothing"); + mc = null; + mc = MusicUtil.getMusicCoreService(); + assertTrue(mc != null); + + } + + @Test + public void testCipherEncKey() { + MusicUtil.setCipherEncKey("cipherEncKey"); + assertTrue("cipherEncKey".equals(MusicUtil.getCipherEncKey())); + } + + @Test + public void testGetMusicPropertiesFilePath() { + MusicUtil.setMusicPropertiesFilePath("filepath"); + assertEquals(MusicUtil.getMusicPropertiesFilePath(),"filepath"); + } + + @Test + public void testGetDefaultLockLeasePeriod() { + MusicUtil.setDefaultLockLeasePeriod(5000); + assertEquals(MusicUtil.getDefaultLockLeasePeriod(),5000); + } + + @Test + public void testIsDebug() { + MusicUtil.setDebug(true); + assertTrue(MusicUtil.isDebug()); + } + + @Test + public void testGetVersion() { + MusicUtil.setVersion("1.0.0"); + assertEquals(MusicUtil.getVersion(),"1.0.0"); + } + + @Test + public void testBuildVersionA() { + assertEquals(MusicUtil.buildVersion("1","2","3"),"1.2.3"); + } + + @Test + public void testBuildVersionB() { + assertEquals(MusicUtil.buildVersion("1",null,"3"),"1"); + } + + @Test + public void testBuildVersionC() { + assertEquals(MusicUtil.buildVersion("1","2",null),"1.2"); + } + + /* + @Test + public void testBuileVersionResponse() { + assertTrue(MusicUtil.buildVersionResponse("1","2","3").getClass().getSimpleName().equals("Builder")); + assertTrue(MusicUtil.buildVersionResponse("1",null,"3").getClass().getSimpleName().equals("Builder")); + assertTrue(MusicUtil.buildVersionResponse("1","2",null).getClass().getSimpleName().equals("Builder")); + assertTrue(MusicUtil.buildVersionResponse(null,null,null).getClass().getSimpleName().equals("Builder")); + } + */ + @Test + public void testGetConsistency() { + assertTrue(ConsistencyLevel.ONE.equals(MusicUtil.getConsistencyLevel("one"))); + } + + @Test + public void testRetryCount() { + MusicUtil.setRetryCount(1); + assertEquals(MusicUtil.getRetryCount(),1); + } + + @Test + public void testIsCadi() { + MusicUtil.setIsCadi(true); + assertEquals(MusicUtil.getIsCadi(),true); + } + + + @Test + public void testGetMyCassaHost() { + MusicUtil.setMyCassaHost("10.0.0.2"); + assertEquals(MusicUtil.getMyCassaHost(),"10.0.0.2"); + } + + @Test + public void testIsValidQueryObject() { + PreparedQueryObject myQueryObject = new PreparedQueryObject(); + myQueryObject.appendQueryString("select * from apple where type = ?"); + myQueryObject.addValue("macintosh"); + assertTrue(MusicUtil.isValidQueryObject(true,myQueryObject)); + + myQueryObject.appendQueryString("select * from apple"); + assertTrue(MusicUtil.isValidQueryObject(false,myQueryObject)); + + myQueryObject.appendQueryString("select * from apple where type = ?"); + assertFalse(MusicUtil.isValidQueryObject(true,myQueryObject)); + + myQueryObject = new PreparedQueryObject(); + myQueryObject.appendQueryString(""); + System.out.println("#######" + myQueryObject.getQuery().isEmpty()); + assertFalse(MusicUtil.isValidQueryObject(false,myQueryObject)); + + + } + + + + + @Test(expected = IllegalStateException.class) + public void testMusicUtil() { + System.out.println("MusicUtil Constructor Test"); + MusicUtil mu = new MusicUtil(); + System.out.println(mu.toString()); + } + + @Test + public void testConvertToCQLDataType() throws Exception { + Map<String,Object> myMap = new HashMap<String,Object>(); + myMap.put("name","tom"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.varchar(),"Happy People"),"'Happy People'"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.uuid(),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")),"29dc2afa-c2c0-47ae-afae-e72a645308ab"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.blob(),"Hi"),"Hi"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),"{'name':'tom'}"); + } + + @Test + public void testConvertToActualDataType() throws Exception { + assertEquals(MusicUtil.convertToActualDataType(DataType.varchar(),"Happy People"),"Happy People"); + assertEquals(MusicUtil.convertToActualDataType(DataType.uuid(),"29dc2afa-c2c0-47ae-afae-e72a645308ab"),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")); + assertEquals(MusicUtil.convertToActualDataType(DataType.varint(),"1234"),BigInteger.valueOf(Long.parseLong("1234"))); + assertEquals(MusicUtil.convertToActualDataType(DataType.bigint(),"123"),Long.parseLong("123")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cint(),"123"),Integer.parseInt("123")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cfloat(),"123.01"),Float.parseFloat("123.01")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cdouble(),"123.02"),Double.parseDouble("123.02")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cboolean(),"true"),Boolean.parseBoolean("true")); + List<String> myList = new ArrayList<String>(); + List<String> newList = myList; + myList.add("TOM"); + assertEquals(MusicUtil.convertToActualDataType(DataType.list(DataType.varchar()),myList),newList); + Map<String,Object> myMap = new HashMap<String,Object>(); + myMap.put("name","tom"); + Map<String,Object> newMap = myMap; + assertEquals(MusicUtil.convertToActualDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),newMap); + } + + @Test + public void testConvertToActualDataTypeByte() throws Exception { + byte[] testByte = "TOM".getBytes(); + assertEquals(MusicUtil.convertToActualDataType(DataType.blob(),testByte),ByteBuffer.wrap(testByte)); + + } + + @Test + public void testJsonMaptoSqlString() throws Exception { + Map<String,Object> myMap = new HashMap<>(); + myMap.put("name","tom"); + myMap.put("value",5); + String result = MusicUtil.jsonMaptoSqlString(myMap,","); + assertTrue(result.contains("name")); + assertTrue(result.contains("value")); + } + + @Test + public void test_generateUUID() { + //this function shouldn't be in cachingUtil + System.out.println("Testing getUUID"); + String uuid1 = MusicUtil.generateUUID(); + String uuid2 = MusicUtil.generateUUID(); + assertFalse(uuid1==uuid2); + } + + + @Test + public void testIsValidConsistency(){ + assertTrue(MusicUtil.isValidConsistency("ALL")); + assertFalse(MusicUtil.isValidConsistency("TEST")); + } + + @Test + public void testLockUsing() { + MusicUtil.setLockUsing("testlock"); + assertEquals("testlock", MusicUtil.getLockUsing()); + } + + @Test + public void testCassaPort() { + MusicUtil.setCassandraPort(1234); + assertEquals(1234, MusicUtil.getCassandraPort()); + } + + @Test + public void testBuild() { + MusicUtil.setBuild("testbuild"); + assertEquals("testbuild", MusicUtil.getBuild()); + } + + @Test + public void testTransId() { + MusicUtil.setTransIdPrefix("prefix"); + assertEquals("prefix-", MusicUtil.getTransIdPrefix()); + } + + + @Test + public void testConversationIdPrefix() { + MusicUtil.setConversationIdPrefix("prefix-"); + assertEquals("prefix-", MusicUtil.getConversationIdPrefix()); + } + + @Test + public void testClientIdPrefix() { + MusicUtil.setClientIdPrefix("clientIdPrefix"); + assertEquals("clientIdPrefix-", MusicUtil.getClientIdPrefix()); + } + + @Test + public void testMessageIdPrefix() { + MusicUtil.setMessageIdPrefix("clientIdPrefix"); + assertEquals("clientIdPrefix-", MusicUtil.getMessageIdPrefix()); + } + + @Test + public void testTransIdPrefix() { + MusicUtil.setTransIdPrefix("transIdPrefix"); + assertEquals("transIdPrefix-", MusicUtil.getTransIdPrefix()); + } + + @Test + public void testConvIdReq() { + MusicUtil.setConversationIdRequired(true); + assertEquals(true, MusicUtil.getConversationIdRequired()); + } + + @Test + public void testClientIdRequired() { + MusicUtil.setClientIdRequired(true); + assertEquals(true, MusicUtil.getClientIdRequired()); + } + + @Test + public void testMessageIdRequired() { + MusicUtil.setMessageIdRequired(true); + assertEquals(true, MusicUtil.getMessageIdRequired()); + } + + @Test + public void testTransIdRequired() { + MusicUtil.setTransIdRequired(true); + assertEquals(true,MusicUtil.getTransIdRequired()); + } + + @Test + public void testGetCassandraConnectTimeOutMS() { + MusicUtil.setCassandraConnectTimeOutMS(2000); + assertEquals(2000,MusicUtil.getCassandraConnectTimeOutMS()); + } + + @Test + public void testGetCassandraReadTimeOutMS() { + MusicUtil.setCassandraReadTimeOutMS(2000); + assertEquals(2000,MusicUtil.getCassandraReadTimeOutMS()); + } + + /* + @Test + public void testLoadProperties() { + PropertiesLoader pl = new PropertiesLoader(); + pl.loadProperties(); + } + */ +} diff --git a/music-core/src/test/java/org/onap/music/datastore/ConditionTest.java b/music-core/src/test/java/org/onap/music/datastore/ConditionTest.java new file mode 100644 index 00000000..2aac62af --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/ConditionTest.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * ============LICENSE_START========================================== org.onap.music + * =================================================================== Copyright (c) 2019 AT&T + * Intellectual Property =================================================================== + * 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.music.datastore; + +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.exceptions.MusicServiceException; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.Spy; + +public class ConditionTest { + + @Spy + private Condition condition; + private Map<String, Object> conditions; + private PreparedQueryObject selectQueryForTheRow; + + @Before + public void setup() { + conditions = Mockito.mock(Map.class); + selectQueryForTheRow = Mockito.mock(PreparedQueryObject.class); + condition = spy(new Condition(conditions, selectQueryForTheRow)); + } + + @Test + public void testCondition() throws Exception { + ResultSet rs = Mockito.mock(ResultSet.class); + Row row = Mockito.mock(Row.class); + MusicDataStore dsHandle = Mockito.mock(MusicDataStore.class); + Mockito.when(rs.one()).thenReturn(row); + Mockito.doReturn(rs).when(condition).quorumGet(Mockito.any()); + boolean result = false; + Mockito.when(dsHandle.doesRowSatisfyCondition(Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.doReturn(dsHandle).when(condition).getDSHandle(); + result = condition.testCondition(); + assertEquals(true, result); + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/MusicDataStoreTest.java b/music-core/src/test/java/org/onap/music/datastore/MusicDataStoreTest.java new file mode 100644 index 00000000..9260cd92 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/MusicDataStoreTest.java @@ -0,0 +1,436 @@ +/******************************************************************************* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * 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.music.datastore; + +import static org.junit.Assert.*; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.CodecRegistry; +import com.datastax.driver.core.ColumnDefinitions; +import com.datastax.driver.core.ColumnDefinitions.Definition; +import com.datastax.driver.core.exceptions.WriteTimeoutException; +import com.datastax.driver.core.ColumnMetadata; +import com.datastax.driver.core.Configuration; +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.KeyspaceMetadata; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; +import com.datastax.driver.core.TableMetadata; +import com.datastax.driver.core.WriteType; + +@RunWith(MockitoJUnitRunner.class) +public class MusicDataStoreTest { + + MusicDataStore dataStore; + + @Mock + Session session; + + @Mock + Cluster cluster; + + @Before + public void before() { + CodecRegistry cr = Mockito.mock(CodecRegistry.class); + Configuration config = Mockito.mock(Configuration.class); + Mockito.when(cluster.getConfiguration()).thenReturn(config); + Mockito.when(config.getCodecRegistry()).thenReturn(cr); + dataStore = new MusicDataStore(cluster, session); + } + + + @Test + public void testMusicDataStoreClusterSession() { + Session session = Mockito.mock(Session.class); + Cluster cluster = Mockito.mock(Cluster.class); + + CodecRegistry cr = Mockito.mock(CodecRegistry.class); + Configuration config = Mockito.mock(Configuration.class); + Mockito.when(cluster.getConfiguration()).thenReturn(config); + Mockito.when(config.getCodecRegistry()).thenReturn(cr); + + + MusicDataStore mds = new MusicDataStore(cluster, session); + assertEquals(session, mds.getSession()); + assertEquals(cluster, mds.getCluster()); + } + + @Test + public void testSession() { + Session session = Mockito.mock(Session.class); + dataStore.setSession(session); + assertEquals(session, dataStore.getSession()); + } + + @Test + public void testCluster() { + Cluster cluster = Mockito.mock(Cluster.class); + CodecRegistry cr = Mockito.mock(CodecRegistry.class); + Configuration config = Mockito.mock(Configuration.class); + Mockito.when(cluster.getConfiguration()).thenReturn(config); + Mockito.when(config.getCodecRegistry()).thenReturn(cr); + + dataStore.setCluster(cluster); + assertEquals(cluster, dataStore.getCluster()); + } + + @Test + public void testClose() { + dataStore.close(); + Mockito.verify(session).close(); + } + + @Test + public void testReturnColumnDataType() { + Metadata meta = Mockito.mock(Metadata.class); + Mockito.when(cluster.getMetadata()).thenReturn(meta); + KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class); + Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd); + TableMetadata tmd = Mockito.mock(TableMetadata.class); + Mockito.when(ksmd.getTable("table")).thenReturn(tmd); + ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class); + Mockito.when(tmd.getColumn("columnName")).thenReturn(cmd); + Mockito.when(cmd.getType()).thenReturn(com.datastax.driver.core.DataType.text()); + + com.datastax.driver.core.DataType dt = dataStore.returnColumnDataType("keyspace", "table", "columnName"); + assertEquals(com.datastax.driver.core.DataType.text(), dt); + } + + @Test + public void testReturnColumnMetadata() { + Metadata meta = Mockito.mock(Metadata.class); + Mockito.when(cluster.getMetadata()).thenReturn(meta); + KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class); + Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd); + TableMetadata tmd = Mockito.mock(TableMetadata.class); + Mockito.when(ksmd.getTable("tableName")).thenReturn(tmd); + + dataStore.returnColumnMetadata("keyspace", "tableName"); + assertEquals(tmd, dataStore.returnColumnMetadata("keyspace", "tableName")); + } + + @Test + public void testReturnKeyspaceMetadata() { + Metadata meta = Mockito.mock(Metadata.class); + Mockito.when(cluster.getMetadata()).thenReturn(meta); + KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class); + Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd); + + assertEquals(ksmd, dataStore.returnKeyspaceMetadata("keyspace")); + } + + @Test + public void testGetColValue() { + Row row = Mockito.mock(Row.class); + Mockito.when(row.getString("columnName")).thenReturn("value"); + UUID uuid = UUID.randomUUID(); + Mockito.when(row.getUUID("columnName")).thenReturn(uuid); + Mockito.when(row.getVarint("columnName")).thenReturn(BigInteger.ONE); + Mockito.when(row.getLong("columnName")).thenReturn((long) 117); + Mockito.when(row.getInt("columnName")).thenReturn(5); + Mockito.when(row.getFloat("columnName")).thenReturn(Float.MAX_VALUE); + Mockito.when(row.getDouble("columnName")).thenReturn(Double.valueOf("2.5")); + Mockito.when(row.getBool("columnName")).thenReturn(true); + Mockito.when(row.getMap("columnName", String.class, String.class)).thenReturn(new HashMap<String, String>()); + Mockito.when(row.getList("columnName", String.class)).thenReturn(new ArrayList<String>()); + + + assertEquals("value", dataStore.getColValue(row, "columnName", DataType.varchar())); + assertEquals(uuid, dataStore.getColValue(row, "columnName", DataType.uuid())); + assertEquals(BigInteger.ONE, dataStore.getColValue(row, "columnName", DataType.varint())); + assertEquals((long) 117, dataStore.getColValue(row, "columnName", DataType.bigint())); + assertEquals(5, dataStore.getColValue(row, "columnName", DataType.cint())); + assertEquals(Float.MAX_VALUE, dataStore.getColValue(row, "columnName", DataType.cfloat())); + assertEquals(2.5, dataStore.getColValue(row, "columnName", DataType.cdouble())); + assertEquals(true, dataStore.getColValue(row, "columnName", DataType.cboolean())); + assertEquals(0, ((Map<String, String>) dataStore.getColValue(row, "columnName", + DataType.map(DataType.varchar(), DataType.varchar()))).size()); + assertEquals(0, + ((List<String>) dataStore.getColValue(row, "columnName", DataType.list(DataType.varchar()))).size()); + } + + @Test + public void testGetBlobValue() { + Row row = Mockito.mock(Row.class); + Mockito.when(row.getBytes("col")).thenReturn(ByteBuffer.allocate(16)); + + byte[] byteArray = dataStore.getBlobValue(row, "col", DataType.blob()); + assertEquals(16, byteArray.length); + } + + @Test + public void testDoesRowSatisfyCondition() throws Exception { + Row row = Mockito.mock(Row.class); + ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class); + Mockito.when(row.getColumnDefinitions()).thenReturn(cd); + Mockito.when(cd.getType("col1")).thenReturn(DataType.varchar()); + + Map<String, Object> condition = new HashMap<>(); + condition.put("col1", "val1"); + + Mockito.when(row.getString("col1")).thenReturn("val1"); + + assertTrue(dataStore.doesRowSatisfyCondition(row, condition)); + + condition.put("col1", "val2"); + assertFalse(dataStore.doesRowSatisfyCondition(row, condition)); + } + + @Test + public void testMarshalData() { + ResultSet results = Mockito.mock(ResultSet.class); + Row row = Mockito.mock(Row.class); + Mockito.when(row.getString("colName")).thenReturn("rowValue"); + //mock for (Row row: results) + Iterator mockIterator = Mockito.mock(Iterator.class); + //Mockito.doCallRealMethod().when(results).forEach(Mockito.any(Consumer.class)); + Mockito.when(results.iterator()).thenReturn(mockIterator); + Mockito.when(mockIterator.hasNext()).thenReturn(true, false); + Mockito.when(mockIterator.next()).thenReturn(row); + + ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class); + Mockito.when(row.getColumnDefinitions()).thenReturn(cd); + //for (Definition: colDefinitions) + Iterator mockIterator2 = Mockito.mock(Iterator.class); + //Mockito.doCallRealMethod().when(cd).forEach(Mockito.any(Consumer.class)); + Mockito.when(cd.iterator()).thenReturn(mockIterator2); + Mockito.when(mockIterator2.hasNext()).thenReturn(true, false); + Definition def = Mockito.mock(Definition.class); + Mockito.when(mockIterator2.next()).thenReturn(def); + Mockito.when(def.getType()).thenReturn(DataType.varchar()); + Mockito.when(def.getName()).thenReturn("colName"); + + Map<String, HashMap<String, Object>> data = dataStore.marshalData(results); + System.out.println("Marshalled data: " + data); + + assertTrue(data.containsKey("row 0")); + assertEquals("rowValue", data.get("row 0").get("colName")); + } + + private ArgumentCaptor<SimpleStatement> sessionExecuteResponse() { + ResultSet rs = Mockito.mock(ResultSet.class); + Mockito.when(session.execute(Mockito.any(Statement.class))).thenReturn(rs); + + ArgumentCaptor<SimpleStatement> argument = ArgumentCaptor.forClass(SimpleStatement.class); + return argument; + } + + @Test + public void testExecutePutPreparedQueryObjectString() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);"; + String lastName = "KRUIKSWIJK"; + String firstName = "Steven"; + + PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName); + dataStore.executePut(query, MusicUtil.CRITICAL); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel()); + assertEquals(queryString, argument.getValue().getQueryString()); + assertEquals(2, argument.getValue().valuesCount()); + } + + @Test + public void testExecutePut_ONE() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);"; + String lastName = "KRUIKSWIJK"; + String firstName = "Steven"; + + PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName); + dataStore.executePut(query, MusicUtil.ONE); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel()); + assertEquals(queryString, argument.getValue().getQueryString()); + assertEquals(2, argument.getValue().valuesCount()); + } + + @Test + public void testExecutePut_quorum() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);"; + String lastName = "KRUIKSWIJK"; + String firstName = "Steven"; + + PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName); + dataStore.executePut(query, MusicUtil.QUORUM); + + Mockito.verify(session).execute(argument.capture()); + //should be quorum! + assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel()); + assertEquals(queryString, argument.getValue().getQueryString()); + assertEquals(2, argument.getValue().valuesCount()); + } + + @Test + public void testExecutePut_ALL() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);"; + String lastName = "KRUIKSWIJK"; + String firstName = "Steven"; + + PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName); + dataStore.executePut(query, MusicUtil.ALL); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.ALL, argument.getValue().getConsistencyLevel()); + assertEquals(queryString, argument.getValue().getQueryString()); + assertEquals(2, argument.getValue().valuesCount()); + } + + @Test(expected = MusicQueryException.class) + public void testExecutePut_BadQueryObj() throws Exception { + String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);"; + String lastName = "KRUIKSWIJK"; + String firstName = "Steven"; + + //Provide extra value here, middle initial + PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName, "P"); + try { + dataStore.executePut(query, MusicUtil.CRITICAL); + } catch (Exception e) { + System.out.println(e.getMessage()); + throw e; + } + + fail("Should have throw error"); + } + + @Test + public void testExecutePutPreparedQueryObjectStringLong() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES ('KRUIKSWIJK','Steven');"; + + + PreparedQueryObject query = new PreparedQueryObject(queryString); + dataStore.executePut(query, MusicUtil.EVENTUAL, 10); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel()); + assertEquals(queryString, argument.getValue().getQueryString()); + } + + @Test + public void testExecuteGet() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE"); + + dataStore.executeGet(query, MusicUtil.ONE); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel()); + assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString()); + } + + @Test (expected = MusicQueryException.class) + public void testExecuteGet_badQuery() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE", "broken"); + + dataStore.executeGet(query, MusicUtil.ONE); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel()); + assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString()); + } + + @Test + public void testExecuteOneConsistencyGet() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE"); + + dataStore.executeOneConsistencyGet(query); + + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel()); + assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString()); + } + + @Test + public void testExecuteLocalQuorumConsistencyGet() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE"); + + dataStore.executeLocalQuorumConsistencyGet(query); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel()); + assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString()); + } + + @Test + public void testExecuteQuorumConsistencyGet() throws Exception { + ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse(); + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE"); + + dataStore.executeQuorumConsistencyGet(query); + + Mockito.verify(session).execute(argument.capture()); + assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel()); + assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString()); + } + + + @Test + public void testExecutePut() { + Mockito.when(session.execute(Mockito.any(SimpleStatement.class))) + .thenThrow(new WriteTimeoutException(ConsistencyLevel.QUORUM, WriteType.CAS, 1, 3)); + + try { + dataStore.executePut(new PreparedQueryObject("Test query"), "critical"); + } catch (MusicServiceException e) { + return; + } catch (MusicQueryException e) { + // should never reach here + fail(); + } + fail(); + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java b/music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java new file mode 100644 index 00000000..7ab7d148 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java @@ -0,0 +1,101 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 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 + * e + * 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.music.datastore; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class PreparedQueryObjectTest { + + private PreparedQueryObject preparedQueryObject; + + @Before + public void setUp() + { + preparedQueryObject = new PreparedQueryObject(); + } + + @Test + public void testKeyspaceName() + { + preparedQueryObject.setKeyspaceName("keyspaceName"); + assertEquals("keyspaceName", preparedQueryObject.getKeyspaceName()); + } + + @Test + public void testConsistency() + { + preparedQueryObject.setConsistency("consistency"); + assertEquals("consistency", preparedQueryObject.getConsistency()); + } + + @Test + public void testTableName() + { + preparedQueryObject.setTableName("tableName"); + assertEquals("tableName", preparedQueryObject.getTableName()); + } + + @Test + public void testoperation() + { + preparedQueryObject.setOperation("operation"); + assertEquals("operation", preparedQueryObject.getOperation()); + } + + @Test + public void testprimaryKeyValue() + { + preparedQueryObject.setPrimaryKeyValue("primaryKeyValue"); + assertEquals("primaryKeyValue", preparedQueryObject.getPrimaryKeyValue()); + } + + @Test + public void testAddValue() { + preparedQueryObject.addValue("one"); + assertEquals("one", preparedQueryObject.getValues().get(0)); + } + + @Test + public void testAddValues() { + preparedQueryObject.addValues("one", "two", "three"); + assertEquals(3, preparedQueryObject.getValues().size()); + assertEquals("two", preparedQueryObject.getValues().get(1)); + } + + @Test + public void testConstructorQuery() { + preparedQueryObject = new PreparedQueryObject("some query string"); + assertEquals("some query string", preparedQueryObject.getQuery()); + } + + @Test + public void testConstructorQueryValues() { + preparedQueryObject = new PreparedQueryObject("another query string", "a", "b", "c"); + assertEquals("another query string", preparedQueryObject.getQuery()); + assertEquals(3, preparedQueryObject.getValues().size()); + assertEquals("b", preparedQueryObject.getValues().get(1)); + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JSONObjectTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JSONObjectTest.java new file mode 100644 index 00000000..9fb549d2 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JSONObjectTest.java @@ -0,0 +1,54 @@ + +/*- + * ============LICENSE_START========================================== + * ONAP MUSIC + * =================================================================== + * Copyright (C) 2020 IBM Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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.music.datastore.jsonobjects; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class JSONObjectTest { + + @Test + public void testGetData(){ + JSONObject js=new JSONObject(); + js.setData("test"); + assertEquals(js.getData(),"test"); + + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java new file mode 100644 index 00000000..5b9cef8b --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java @@ -0,0 +1,113 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * 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.music.datastore.jsonobjects; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class JsonDeleteTest { + + JsonDelete jd = null; + + @Before + public void init() { + jd = new JsonDelete(); + } + + @Test + public void testGetConditions() { + Map<String,Object> mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + jd.setConditions(mapSo); + assertEquals("one",jd.getConditions().get("key1")); + } + + @Test + public void testGetConsistencyInfo() { + Map<String,String> mapSs = new HashMap<>(); + mapSs.put("key3","three"); + mapSs.put("key4","four"); + jd.setConsistencyInfo(mapSs); + assertEquals("three",jd.getConsistencyInfo().get("key3")); + } + + @Test + public void testGetColumns() { + List<String> ary = new ArrayList<>(); + ary.add("e1"); + ary.add("e2"); + ary.add("e3"); + jd.setColumns(ary); + assertEquals("e1",jd.getColumns().get(0)); + } + + @Test + public void testGetTtl() { + jd.setTtl("2000"); + assertEquals("2000",jd.getTtl()); + } + + @Test + public void testGetTimestamp() { + jd.setTimestamp("20:00"); + assertEquals("20:00",jd.getTimestamp()); + + } + + @Test + public void testGetKeyspaceName() { + jd.setKeyspaceName("keyspace"); + assertEquals("keyspace",jd.getKeyspaceName()); + + } + + @Test + public void testGetTableName() { + jd.setTableName("tablename"); + assertEquals("tablename",jd.getTableName()); + + } + + @Test + public void testGetPrimarKeyValue() { + jd.setPrimarKeyValue("primarykey"); + assertEquals("primarykey",jd.getPrimarKeyValue()); + + } + + @Test + public void testRowIdString() { + StringBuilder builder = new StringBuilder("testing"); + jd.setRowIdString(builder); + assertEquals(jd.getRowIdString().toString(),builder.toString()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonIndexTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonIndexTest.java new file mode 100644 index 00000000..0d89a339 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonIndexTest.java @@ -0,0 +1,74 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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.music.datastore.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.PreparedQueryObject; + +public class JsonIndexTest { + + JsonIndex ji = null; + + + @Before + public void init() { + ji = new JsonIndex(null, null, null, null); + } + + + + @Test + public void testKeyspace() { + ji.setKeyspaceName("keyspaceName"); + assertEquals("keyspaceName", ji.getKeyspaceName()); + } + + @Test + public void testIndexName() { + ji.setIndexName("indexName"); + assertEquals("indexName", ji.getIndexName()); + } + + @Test + public void testFieldName() { + ji.setFieldName("field"); + assertEquals("field", ji.getFieldName()); + } + + @Test + public void testTableName() { + ji.setTableName("table"); + assertEquals("table", ji.getTableName()); + } + + @Test + public void testCreateIndexQuery() { + JsonIndex ji2 = new JsonIndex("index", "keyspace", "table", "field"); + PreparedQueryObject query = ji2.genCreateIndexQuery(); + assertEquals("Create index if not exists index on keyspace.table (field);", query.getQuery()); + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java new file mode 100644 index 00000000..ad71c9ea --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java @@ -0,0 +1,176 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 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.music.datastore.jsonobjects; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.SerializationUtils; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.FieldSetter; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import com.datastax.driver.core.ColumnMetadata; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.Session; +//import org.mockito.internal.util.reflection.Whitebox; +import com.datastax.driver.core.TableMetadata; + + +public class JsonInsertTest { + + JsonInsert ji = new JsonInsert(); + + @Test + public void testGetKeyspaceName() { + ji.setKeyspaceName("keyspace"); + assertEquals("keyspace",ji.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + ji.setTableName("table"); + assertEquals("table",ji.getTableName()); + } + + @Test + public void testGetConsistencyInfo() { + Map<String,String> cons = new HashMap<>(); + cons.put("test","true"); + ji.setConsistencyInfo(cons); + assertEquals("true",ji.getConsistencyInfo().get("test")); + } + + @Test + public void testGetTtl() { + ji.setTtl("ttl"); + assertEquals("ttl",ji.getTtl()); + } + + @Test + public void testGetTimestamp() { + ji.setTimestamp("10:30"); + assertEquals("10:30",ji.getTimestamp()); + } + + @Test + public void testGetValues() { + Map<String,Object> cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setValues(cons); + assertEquals("one",ji.getValues().get("val1")); + } + + @Test + public void testGetRowSpecification() { + Map<String,Object> cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setRowSpecification(cons); + assertEquals("two",ji.getRowSpecification().get("val2")); + } + + @Test + public void testSerialize() { + Map<String,Object> cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ji.setTimestamp("10:30"); + ji.setRowSpecification(cons); + byte[] test1 = ji.serialize(); + byte[] ji1 = SerializationUtils.serialize(ji); + assertArrayEquals(ji1,test1); + } + + @Test + public void testObjectMap() + { + Map<String, byte[]> map = new HashMap<>(); + ji.setObjectMap(map); + assertEquals(map, ji.getObjectMap()); + } + + @Test + public void testPrimaryKey() { + ji.setPrimaryKeyVal("primKey"); + assertEquals("primKey", ji.getPrimaryKeyVal()); + } + + @Test + public void testGenInsertPreparedQueryObj() throws Exception { + ji.setKeyspaceName("keyspace"); + ji.setTableName("table"); + ji.setPrimaryKeyVal("value"); + Map<String,Object> rowSpec = new HashMap<>(); + rowSpec.put("val1","one"); + rowSpec.put("val2","two"); + ji.setRowSpecification(rowSpec); + Map<String,Object> vals = new HashMap<>(); + vals.put("val1","one"); + vals.put("val2","two"); + ji.setValues(vals); + + Map<String,String> cons = new HashMap<>(); + cons.put("type","quorum"); + ji.setConsistencyInfo(cons); + + MusicDataStore mds = Mockito.mock(MusicDataStore.class); + Session session = Mockito.mock(Session.class); + Mockito.when(mds.getSession()).thenReturn(session); + MusicDataStoreHandle mdsh = Mockito.mock(MusicDataStoreHandle.class); + FieldSetter.setField(mdsh, mdsh.getClass().getDeclaredField("mDstoreHandle"), mds); + TableMetadata tableMeta = Mockito.mock(TableMetadata.class); + Mockito.when(mds.returnColumnMetadata(Mockito.anyString(), Mockito.anyString())) + .thenReturn(tableMeta); + + ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class); + List<ColumnMetadata> listcmd = new ArrayList<>(); + listcmd.add(cmd); + Mockito.when(tableMeta.getPrimaryKey()).thenReturn(listcmd); + Mockito.when(cmd.getName()).thenReturn("val1"); + Mockito.when(tableMeta.getColumn("val1")).thenReturn(cmd); + Mockito.when(tableMeta.getColumn("val2")).thenReturn(cmd); + Mockito.when(cmd.getType()).thenReturn(DataType.text()); + + PreparedQueryObject query = ji.genInsertPreparedQueryObj(); + System.out.println(query.getQuery()); + System.out.println(query.getValues()); + + + assertEquals("INSERT INTO keyspace.table (vector_ts,val2,val1) VALUES (?,?,?);", query.getQuery()); + assertTrue(query.getValues().containsAll(vals.values())); + } + +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java new file mode 100644 index 00000000..a3fa58e4 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java @@ -0,0 +1,72 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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.music.datastore.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class JsonKeySpaceTest { + + JsonKeySpace jk = null; + + + @Before + public void init() { + jk = new JsonKeySpace(); + } + + + + @Test + public void testGetConsistencyInfo() { + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jk.setConsistencyInfo(mapSs); + assertEquals("one",jk.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetReplicationInfo() { + Map<String,Object> mapSo = new HashMap<>(); + mapSo.put("k1", "one"); + jk.setReplicationInfo(mapSo); + assertEquals("one",jk.getReplicationInfo().get("k1")); + + } + + @Test + public void testGetDurabilityOfWrites() { + jk.setDurabilityOfWrites("1"); + assertEquals("1",jk.getDurabilityOfWrites()); + } + + @Test + public void testGetKeyspaceName() { + jk.setKeyspaceName("Keyspace"); + assertEquals("Keyspace",jk.getKeyspaceName()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonLockTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonLockTest.java new file mode 100644 index 00000000..75db75e5 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonLockTest.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * 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.music.datastore.jsonobjects; + +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.lockingservice.cassandra.LockType; + +public class JsonLockTest { + + JsonLock jsonLock; + + @Before + public void setup() { + jsonLock = new JsonLock(); + } + + @Test + public void testSetLockType() { + jsonLock.setLockType(LockType.READ); + assertEquals(LockType.READ, jsonLock.getLocktype()); + + jsonLock.setLockType(LockType.WRITE); + assertEquals(LockType.WRITE, jsonLock.getLocktype()); + + jsonLock.setLockType(LockType.PROMOTING); + assertEquals(LockType.PROMOTING, jsonLock.getLocktype()); + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java new file mode 100644 index 00000000..baada1d5 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java @@ -0,0 +1,68 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2018-2019 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.music.datastore.jsonobjects; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class JsonSelectTest { + JsonSelect js = new JsonSelect(); + + @Test + public void testGetConsistencyInfo() { + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + js.setConsistencyInfo(mapSs); + assertEquals("one", js.getConsistencyInfo().get("k1")); + } + + @Test + public void testSerialize() throws IOException { + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("Key", "Value"); + js.setConsistencyInfo(mapSs); + js.serialize(); + } + + @Test + public void testGetKeyspaceName() { + js.setKeyspaceName("testkeyspace"); + assertEquals("testkeyspace",js.getKeyspaceName()); + + } + + @Test + public void testGetTableName() { + js.setTableName("testkeyspace"); + assertEquals("testkeyspace",js.getTableName()); + + } + +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java new file mode 100644 index 00000000..3ab32d40 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java @@ -0,0 +1,153 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 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.music.datastore.jsonobjects; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.exceptions.MusicQueryException; + +public class JsonTableTest { + + JsonTable jt = null; + + @Before + public void init() { + jt = new JsonTable(); + } + + @Test + public void testGetConsistencyInfo() { + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jt.setConsistencyInfo(mapSs); + assertEquals("one",jt.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetProperties() { + Map<String, Object> properties = new HashMap<>(); + properties.put("k1", "one"); + jt.setProperties(properties); + assertEquals(properties.size(), jt.getProperties().size()); + } + + @Test + public void testGetFields() { + Map<String, String> fields = new HashMap<>(); + fields.put("k1", "one"); + jt.setFields(fields); + assertEquals("one",jt.getFields().get("k1")); + } + + @Test + public void testGetKeyspaceName() { + String keyspace = "keyspace"; + jt.setKeyspaceName(keyspace); + assertEquals(keyspace,jt.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + String table = "table"; + jt.setTableName(table); + assertEquals(table,jt.getTableName()); + } + + @Test + public void testGetClusteringOrder() { + String clusteringOrder = "clusteringOrder"; + jt.setClusteringOrder(clusteringOrder); + assertEquals(clusteringOrder,jt.getClusteringOrder()); + } + + @Test + public void testGetClusterKey() { + String clusterKey = "clusterKey"; + jt.setClusteringKey(clusterKey); + assertEquals(clusterKey, jt.getClusteringKey()); + } + + @Test + public void testGetPrimaryKey() { + String primaryKey = "primaryKey"; + jt.setPrimaryKey(primaryKey); + assertEquals(primaryKey,jt.getPrimaryKey()); + } + + @Test + public void testFilteringKey() { + jt.setFilteringKey("FilteringKey"); + assertEquals("FilteringKey",jt.getFilteringKey()); + } + + @Test + public void testPartitionKey() { + jt.setPartitionKey("ParitionKey"); + assertEquals("ParitionKey",jt.getPartitionKey()); + } + + @Test + public void genCreateTableQuery() throws MusicQueryException { + JsonTable jt2 = new JsonTable(); + jt2.setKeyspaceName("keyspace"); + jt2.setTableName("table"); + Map<String, String> fields = new HashMap<>(); + fields.put("k1", "one"); + jt2.setFields(fields); + jt2.setPrimaryKey("k1"); + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jt2.setConsistencyInfo(mapSs); + String clusteringOrder = "clusteringOrder"; + jt.setClusteringOrder(clusteringOrder); + String clusterKey = "clusterKey"; + jt.setClusteringKey(clusterKey); + + System.out.println(jt2.genCreateTableQuery().getQuery()); + assertEquals("CREATE TABLE keyspace.table (vector_ts text,k1 one, PRIMARY KEY ( (k1) ));", + jt2.genCreateTableQuery().getQuery()); + } + + @Test + public void genDropTableQuery() throws MusicQueryException { + JsonTable jt2 = new JsonTable(); + jt2.setKeyspaceName("keyspace"); + jt2.setTableName("table"); + Map<String, String> fields = new HashMap<>(); + fields.put("k1", "one"); + jt2.setFields(fields); + jt2.setPrimaryKey("k1"); + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + jt.setConsistencyInfo(mapSs); + + System.out.println(jt2.genDropTableQuery().getQuery()); + assertEquals("DROP TABLE keyspace.table;", + jt2.genDropTableQuery().getQuery()); + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java new file mode 100644 index 00000000..37c729f4 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java @@ -0,0 +1,166 @@ +/******************************************************************************* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2018 AT&T Intellectual Property + * =================================================================== + * Modifications Copyright (c) 2019 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.music.datastore.jsonobjects; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.music.datastore.jsonobjects.JsonUpdate.RowIdentifier; +import com.datastax.driver.core.ColumnMetadata; +import com.datastax.driver.core.DataType; +import com.datastax.driver.core.TableMetadata; + +public class JsonUpdateTest { + + JsonUpdate ju = null; + + @Before + public void init() { + ju = new JsonUpdate(); + } + + + @Test + public void testGetConditions() { + Map<String,Object> mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + ju.setConditions(mapSo); + assertEquals("one",ju.getConditions().get("key1")); + } + + @Test + public void testGetRow_specification() { + Map<String,Object> mapSo = new HashMap<>(); + mapSo.put("key1","one"); + mapSo.put("key2","two"); + ju.setRow_specification(mapSo); + assertEquals("one",ju.getRow_specification().get("key1")); + } + + @Test + public void testGetKeyspaceName() { + String keyspace = "keyspace"; + ju.setKeyspaceName(keyspace); + assertEquals(keyspace,ju.getKeyspaceName()); + } + + @Test + public void testGetTableName() { + String table = "table"; + ju.setTableName(table); + assertEquals(table,ju.getTableName()); + } + + @Test + public void testGetConsistencyInfo() { + Map<String, String> mapSs = new HashMap<>(); + mapSs.put("k1", "one"); + ju.setConsistencyInfo(mapSs); + assertEquals("one",ju.getConsistencyInfo().get("k1")); + } + + @Test + public void testGetTtl() { + ju.setTtl("2000"); + assertEquals("2000",ju.getTtl()); + } + + @Test + public void testGetTimestamp() { + ju.setTimestamp("20:00"); + assertEquals("20:00",ju.getTimestamp()); + + } + + @Test + public void testGetValues() { + Map<String,Object> cons = new HashMap<>(); + cons.put("val1","one"); + cons.put("val2","two"); + ju.setValues(cons); + assertEquals("one",ju.getValues().get("val1")); + } + + @Test + public void testSerialize() { + assertTrue(ju.serialize() instanceof byte[]); + } + + @Test + public void testRowIdString() { + ju.setRowIdString("testing"); + assertEquals("testing", ju.getRowIdString()); + } + + @Test + public void testPrimaryKeyValue() { + ju.setPrimarKeyValue("primeKey"); + assertEquals("primeKey", ju.getPrimarKeyValue()); + } + + @Test + public void testGenUpdatePreparedQueryObj() throws Exception { + JsonUpdate ju = Mockito.spy(JsonUpdate.class); + MultivaluedMap<String, String> rowParams = Mockito.mock(MultivaluedMap.class); + + ju.setKeyspaceName("keyspace"); + ju.setTableName("table"); + ju.setPrimarKeyValue("primaryKeyValue"); + Map<String, String> consistencyInfo = new HashMap<>(); + consistencyInfo.put("type", "critical"); + ju.setConsistencyInfo(consistencyInfo); + Map<String, Object> values = new HashMap<>(); + values.put("col1", "val1"); + ju.setValues(values); + + TableMetadata tmd = Mockito.mock(TableMetadata.class); + Mockito.doReturn(tmd).when(ju).returnColumnMetadata(Mockito.anyString(), Mockito.anyString()); + ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class); + Mockito.when(tmd.getColumn("col1")).thenReturn(cmd); + List<ColumnMetadata> colList = new ArrayList<>(); + colList.add(cmd); + Mockito.when(tmd.getPrimaryKey()).thenReturn(colList); + Mockito.when(cmd.getType()).thenReturn(DataType.varchar()); + + RowIdentifier rowId = Mockito.mock(RowIdentifier.class); + Mockito.doReturn(rowId).when(ju).getRowIdentifier(Mockito.anyString(), Mockito.anyString(), Mockito.any(), + Mockito.any()); + + Mockito.when(rowId.getRowIdString()).thenReturn("col1"); + Mockito.when(rowId.getPrimaryKeyValue()).thenReturn("val1"); + + + assertEquals("UPDATE keyspace.table SET vector_ts=?,col1= ? WHERE col1;", + ju.genUpdatePreparedQueryObj(rowParams).getQuery()); + } +} diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/RowIdentifierTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/RowIdentifierTest.java new file mode 100644 index 00000000..e29f0377 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/RowIdentifierTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START========================================== + * ONAP MUSIC + * =================================================================== + * Copyright (C) 2020 IBM Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software 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. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * 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.music.datastore.jsonobjects; + +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class RowIdentifierTest { + String primarykey="primarykey"; + String rowIdString="123"; + PreparedQueryObject queryObject=new PreparedQueryObject("select * from employee"); + JsonUpdate ju=new JsonUpdate(); + JsonUpdate.RowIdentifier rowId= ju.new RowIdentifier(primarykey,rowIdString,queryObject); + @Test + public void testConstructor(){ + rowId.setPrimaryKeyValue(primarykey); + rowId.setRowIdString(rowIdString); + assertEquals(rowId.getPrimaryKeyValue(),"primarykey"); + assertEquals(rowId.getRowIdString(),"123"); + } +} diff --git a/music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java b/music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java new file mode 100644 index 00000000..cba9c7c2 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.eelf.logging.format; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class AppMessagesTest { + + private AppMessages messages; + + @Before + public void setUp() { + messages= AppMessages.ALREADYEXIST; + } + + @Test + public void testDetails() + { + messages.setDetails("details"); + assertEquals("details", messages.getDetails()); + } + + @Test + public void testResolution() + { + messages.setResolution("Resolution"); + assertEquals("Resolution", messages.getResolution()); + } + + @Test + public void testErrorCode() + { + messages.setErrorCode("ErrorCode"); + assertEquals("ErrorCode", messages.getErrorCode()); + } + + @Test + public void testErrorDescription() + { + messages.setErrorDescription("ErrorDescription"); + assertEquals("ErrorDescription", messages.getErrorDescription()); + } +} diff --git a/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorSeverityTest.java b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorSeverityTest.java new file mode 100644 index 00000000..b2b0fafa --- /dev/null +++ b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorSeverityTest.java @@ -0,0 +1,41 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.eelf.logging.format; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ErrorSeverityTest { + + @Test + public void TestErrorServerity() + { + assertEquals("INFO",ErrorSeverity.INFO.name()); + assertEquals("WARN",ErrorSeverity.WARN.name()); + assertEquals("ERROR",ErrorSeverity.ERROR.name()); + assertEquals("FATAL",ErrorSeverity.FATAL.name()); + assertEquals("CRITICAL",ErrorSeverity.CRITICAL.name()); + assertEquals("MAJOR",ErrorSeverity.MAJOR.name()); + assertEquals("MINOR",ErrorSeverity.MINOR.name()); + assertEquals("NONE",ErrorSeverity.NONE.name()); + } +} diff --git a/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorTypesTest.java b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorTypesTest.java new file mode 100644 index 00000000..ff7b188b --- /dev/null +++ b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorTypesTest.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * Modifications Copyright (C) 2019 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.music.eelf.logging.format; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ErrorTypesTest { + + @Test + public void Test1() + { + assertEquals("CONNECTIONERROR",ErrorTypes.CONNECTIONERROR.name()); + assertEquals("SESSIONEXPIRED",ErrorTypes.SESSIONEXPIRED.name()); + assertEquals("AUTHENTICATIONERROR",ErrorTypes.AUTHENTICATIONERROR.name()); + assertEquals("CACHEERROR",ErrorTypes.CACHEERROR.name()); + assertEquals("SERVICEUNAVAILABLE",ErrorTypes.SERVICEUNAVAILABLE.name()); + assertEquals("QUERYERROR",ErrorTypes.QUERYERROR.name()); + assertEquals("DATAERROR",ErrorTypes.DATAERROR.name()); + assertEquals("GENERALSERVICEERROR",ErrorTypes.GENERALSERVICEERROR.name()); + assertEquals("MUSICSERVICEERROR",ErrorTypes.MUSICSERVICEERROR.name()); + assertEquals("LOCKINGERROR",ErrorTypes.LOCKINGERROR.name()); + assertEquals("UNKNOWN",ErrorTypes.UNKNOWN.name()); + + } +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicDeadlockExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicDeadlockExceptionTest.java new file mode 100644 index 00000000..db0e10ea --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicDeadlockExceptionTest.java @@ -0,0 +1,135 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicDeadlockExceptionTest { + + private String owner = "tester"; + private String keyspace = "testing"; + private String table = "lockq"; + private String key = "test"; + + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicDeadlockException(); + } + } catch (MusicDeadlockException mde) { + assertEquals("org.onap.music.exceptions.MusicDeadlockException", mde.getClass().getName()); + } + + } + + @Test + public void TestException6() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicDeadlockException("org.onap.music.exceptions.MusicDeadlockException"); + } + } catch (MusicDeadlockException mde) { + assertEquals(mde.getMessage(),"org.onap.music.exceptions.MusicDeadlockException"); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicDeadlockException("MusicDeadlockException Exception occured.."); + } + } catch (MusicDeadlockException mde) { + assertEquals(mde.getMessage(), "MusicDeadlockException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicDeadlockException(new Throwable()); + } + } catch (MusicDeadlockException mve) { + assertEquals("org.onap.music.exceptions.MusicDeadlockException", mve.getClass().getName()); + } + + } + + @Test + public void TestException4() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicDeadlockException(message, new Throwable()); + } + } catch (MusicDeadlockException mde) { + assertEquals("org.onap.music.exceptions.MusicDeadlockException", mde.getClass().getName()); + } + + } + + @Test + public void TestException5() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicDeadlockException(message, new Throwable(), enableSuppression, + writableStackTrace); + } + } catch (MusicDeadlockException mde) { + assertEquals("org.onap.music.exceptions.MusicDeadlockException", mde.getClass().getName()); + } + + } + + @Test + public void TestSetValues() + { + MusicDeadlockException mde=new MusicDeadlockException(); + mde.setValues(owner,keyspace,table,key); + assertEquals("tester",mde.getOwner()); + assertEquals("testing",mde.getKeyspace()); + assertEquals("lockq",mde.getTable()); + assertEquals("test",mde.getKey()); + } +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java new file mode 100644 index 00000000..583a9fd4 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java @@ -0,0 +1,104 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicLockingExceptionTest { + + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException("MusicLockingException Exception occured.."); + } + } catch (MusicLockingException mle) { + assertEquals(mle.getMessage(), "MusicLockingException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(new Throwable()); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + + @Test + public void TestException4() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(message, new Throwable()); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + + @Test + public void TestException5() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicLockingException(message, new Throwable(), enableSuppression, writableStackTrace); + } + } catch (MusicLockingException mle) { + assertEquals("org.onap.music.exceptions.MusicLockingException", mle.getClass().getName()); + } + + } + +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java new file mode 100644 index 00000000..22e2d728 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java @@ -0,0 +1,106 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicPolicyVoilationExceptionTest { + + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException("MusicPolicyVoilationException Exception occured.."); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals(mve.getMessage(), "MusicPolicyVoilationException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(new Throwable()); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + + @Test + public void TestException4() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(message, new Throwable()); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + + @Test + public void TestException5() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicPolicyVoilationException(message, new Throwable(), enableSuppression, + writableStackTrace); + } + } catch (MusicPolicyVoilationException mve) { + assertEquals("org.onap.music.exceptions.MusicPolicyVoilationException", mve.getClass().getName()); + } + + } + +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java new file mode 100644 index 00000000..9096506a --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java @@ -0,0 +1,118 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicQueryExceptionTest { + + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException("MusicQueryException Exception occured.."); + } + } catch (MusicQueryException mqe) { + assertEquals(mqe.getMessage(), "MusicQueryException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException("MusicQueryException Exception occured..", 001); + } + } catch (MusicQueryException mqe) { + assertEquals(mqe.getMessage(), "MusicQueryException Exception occured.."); + } + + } + + @Test + public void TestException4() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(new Throwable()); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + + @Test + public void TestException5() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(message, new Throwable()); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + + @Test + public void TestException6() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicQueryException(message, new Throwable(), enableSuppression, writableStackTrace); + } + } catch (MusicQueryException mqe) { + assertEquals("org.onap.music.exceptions.MusicQueryException", mqe.getClass().getName()); + } + + } + +} diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java new file mode 100644 index 00000000..bf056b61 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java @@ -0,0 +1,145 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MusicServiceExceptionTest { + @Test + public void TestException1() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void TestException2() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException("MusicServiceException Exception occured.."); + } + } catch (MusicServiceException mse) { + assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); + } + + } + + @Test + public void TestException3() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException("MusicServiceException Exception occured..", 001); + } + } catch (MusicServiceException mse) { + assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); + } + + } + + @Test + public void TestException4() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException("MusicServiceException Exception occured..", 001, "errorMsg"); + } + } catch (MusicServiceException mse) { + assertEquals(mse.getMessage(), "MusicServiceException Exception occured.."); + } + + } + + @Test + public void TestException5() { + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(new Throwable()); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void TestException6() { + String message = "Exception occured"; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(message, new Throwable()); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void TestException7() { + String message = "Exception occured"; + boolean enableSuppression = true; + boolean writableStackTrace = false; + String s1 = "Value1"; + String s2 = "value2"; + try { + if (!s1.equalsIgnoreCase(s2)) { + throw new MusicServiceException(message, new Throwable(), enableSuppression, writableStackTrace); + } + } catch (MusicServiceException mse) { + assertEquals("org.onap.music.exceptions.MusicServiceException", mse.getClass().getName()); + } + + } + + @Test + public void testErrorCode() { + MusicServiceException musicServiceException = new MusicServiceException(); + musicServiceException.setErrorCode(0001); + assertEquals(0001, musicServiceException.getErrorCode()); + } + + @Test + public void testSetErrorMsg() { + MusicServiceException musicServiceException = new MusicServiceException(); + musicServiceException.setErrorMessage("errorMsg"); + assertEquals("errorMsg", musicServiceException.getErrorMessage()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/lockingservice/cassandra/CassaLockStoreTest.java b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/CassaLockStoreTest.java new file mode 100644 index 00000000..a608a970 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/CassaLockStoreTest.java @@ -0,0 +1,311 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * 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.music.lockingservice.cassandra; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import java.util.Iterator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.DeadlockDetectionUtil; +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.WriteType; +import com.datastax.driver.core.exceptions.WriteTimeoutException; + +public class CassaLockStoreTest { + + private CassaLockStore cassaLockStore; + private CassaLockStore.LockObject lockObject; + private MusicDataStore dsHandle; + + @Before + public void setUp() { + dsHandle = Mockito.mock(MusicDataStore.class); + cassaLockStore = new CassaLockStore(dsHandle); + lockObject = cassaLockStore.new LockObject(false, null, null, null, null, null); + } + + @Test + public void testLockOwner() { + lockObject.setIsLockOwner(true); + assertEquals(true, lockObject.getIsLockOwner()); + + lockObject.setIsLockOwner(false); + assertEquals(false, lockObject.getIsLockOwner()); + } + + @Test + public void testAcquireTime() { + lockObject.setAcquireTime("2019-11-11T15:42:12+00:00"); + assertEquals("2019-11-11T15:42:12+00:00", lockObject.getAcquireTime()); + } + + @Test + public void testCreateTime() { + lockObject.setCreateTime("2019-11-11T15:43:44+00:00"); + assertEquals("2019-11-11T15:43:44+00:00", lockObject.getCreateTime()); + } + + @Test + public void testLockRef() { + lockObject.setLockRef("LockReference"); + assertEquals("LockReference", lockObject.getLockRef()); + } + + @Test + public void testLockType() { + lockObject.setLocktype(LockType.READ); + assertEquals(LockType.READ, lockObject.getLocktype()); + } + + @Test + public void testOwner() { + lockObject.setOwner("Owner"); + assertEquals("Owner", lockObject.getOwner()); + } + + @Test + public void testCreateLockQueue() { + try { + Mockito.when(dsHandle.executePut(Mockito.any(), Mockito.any())).thenReturn(true); + assertEquals(true, cassaLockStore.createLockQueue("keyspace1", "table1")); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testGenLockRefandEnQueue() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + List<Row> latestGuardRow = Mockito.mock(List.class); + Mockito.when(latestGuardRow.isEmpty()).thenReturn(false); + Row row = Mockito.mock(Row.class); + Mockito.when(latestGuardRow.get(0)).thenReturn(row); + Mockito.when(row.getLong(0)).thenReturn((long) 4); + Mockito.when(resultSetMock.all()).thenReturn(latestGuardRow); + try { + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + Mockito.when(dsHandle.executePut(Mockito.any(), Mockito.any())).thenReturn(true); + assertEquals("$keyspace2.table2.lockName2$5", + cassaLockStore.genLockRefandEnQueue("keyspace2", "table2", "lockName2", LockType.READ, "owner2")); + } catch (MusicServiceException | MusicQueryException | MusicLockingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testGetLockQueue() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Iterator<Row> iterator = Mockito.mock(Iterator.class); + Mockito.when(iterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); + Row row = Mockito.mock(Row.class); + Mockito.when(row.getLong("lockReference")).thenReturn((long)1).thenReturn((long)2).thenReturn((long)3); + Mockito.when(row.get("lockType", LockType.class)).thenReturn(LockType.WRITE).thenReturn(LockType.WRITE).thenReturn(LockType.WRITE); + Mockito.when(iterator.next()).thenReturn(row).thenReturn(row).thenReturn(row); + Mockito.when(resultSetMock.iterator()).thenReturn(iterator); + + try { + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + assertEquals("2", cassaLockStore.getLockQueue("keyspace2", "table2", "key2").get(1)); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testGetLockQueueSize() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Row row = Mockito.mock(Row.class); + Mockito.when(resultSetMock.one()).thenReturn(row); + Mockito.when(row.getLong("count")).thenReturn((long) 6); + try { + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + assertEquals(6, cassaLockStore.getLockQueueSize("keyspace3", "table3", "key3")); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testPeekLockQueue() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Row row = Mockito.mock(Row.class); + Mockito.when(row.isNull("lockReference")).thenReturn(false); + Mockito.when(row.getLong("lockReference")).thenReturn((long) 6); + Mockito.when(row.getString("createTime")).thenReturn("2019-11-13T15:05:45+00:00"); + Mockito.when(row.getString("acquireTime")).thenReturn("2019-11-13T15:05:45+00:00"); + Mockito.when(row.isNull("lockReference")).thenReturn(false); + Mockito.when(resultSetMock.one()).thenReturn(row); + try { + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + assertEquals("6", cassaLockStore.peekLockQueue("keyspace4", "table4", "key4").getLockRef()); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testGetCurrentLockHolders() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Iterator<Row> iterator = Mockito.mock(Iterator.class); + Mockito.when(iterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false); + Row row = Mockito.mock(Row.class); + Mockito.when(row.getLong("lockReference")).thenReturn((long) 5).thenReturn((long) 5); + Mockito.when(row.get("lockType", LockType.class)).thenReturn(LockType.WRITE); + Mockito.when(iterator.next()).thenReturn(row).thenReturn(row); + Mockito.when(resultSetMock.iterator()).thenReturn(iterator); + try { + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + assertEquals("$keyspace5.table5.key5$5", cassaLockStore.getCurrentLockHolders("keyspace5", "table5", "key5").get(1)); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testIsLockOwner() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Iterator<Row> iterator = Mockito.mock(Iterator.class); + Mockito.when(iterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false); + Row row = Mockito.mock(Row.class); + Mockito.when(row.getLong("lockReference")).thenReturn((long) 5); + Mockito.when(row.get("lockType", LockType.class)).thenReturn(LockType.WRITE); + Mockito.when(iterator.next()).thenReturn(row).thenReturn(row); + Mockito.when(resultSetMock.iterator()).thenReturn(iterator); + try { + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + assertEquals(true, cassaLockStore.isLockOwner("keyspace5", "table5", "key5", "5")); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testGetLockInfo() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Row row = Mockito.mock(Row.class); + Mockito.when(row.isNull("lockReference")).thenReturn(false); + Mockito.when(row.getLong("lockReference")).thenReturn((long) 6); + Mockito.when(row.getString("createTime")).thenReturn("2019-11-13T15:05:45+00:00"); + Mockito.when(row.getString("acquireTime")).thenReturn("2019-11-13T15:05:45+00:00"); + LockType locktype = Mockito.mock(LockType.class); + Mockito.when(row.get("lockType", LockType.class)).thenReturn(locktype); + Mockito.when(row.getString("owner")).thenReturn("owner6"); + Mockito.when(resultSetMock.one()).thenReturn(row); + + try { + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + CassaLockStore csLockStore = Mockito.spy(cassaLockStore); + Mockito.doReturn(true).when(csLockStore).isLockOwner(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + assertEquals("6", csLockStore.getLockInfo("keyspace6", "table6", "key6", "6").getLockRef()); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testCheckForDeadlock() { + DeadlockDetectionUtil ddu = Mockito.mock(DeadlockDetectionUtil.class); + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Iterator<Row> it = Mockito.mock(Iterator.class); + Row row = Mockito.mock(Row.class); + Mockito.when(it.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); + Mockito.when(row.getString("key")).thenReturn("key8"); + Mockito.when(row.getString("owner")).thenReturn("owner8"); + Mockito.when(row.getString("acquiretime")).thenReturn("1"); + Mockito.when(it.next()).thenReturn(row).thenReturn(row).thenReturn(row); + Mockito.when(resultSetMock.iterator()).thenReturn(it); + CassaLockStore csLockStore = Mockito.spy(cassaLockStore); + Mockito.doReturn(ddu).when(csLockStore).getDeadlockDetectionUtil(); + Mockito.when(ddu.checkForDeadlock(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); + try { + Mockito.when(dsHandle.executeLocalQuorumConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + assertEquals(false, + cassaLockStore.checkForDeadlock("keyspace8", "table8", "lockName8", LockType.WRITE, "owner8", true)); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testGetAllLocksForOwner() { + ResultSet resultSetMock = Mockito.mock(ResultSet.class); + Iterator<Row> it = Mockito.mock(Iterator.class); + Mockito.when(it.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false); + Row row = Mockito.mock(Row.class); + Mockito.when(row.getString("key")).thenReturn("key10"); + Mockito.when(row.getLong("lockreference")).thenReturn((long) 10); + Mockito.when(it.next()).thenReturn(row); + Mockito.when(resultSetMock.iterator()).thenReturn(it); + try { + Mockito.when(dsHandle.executeQuorumConsistencyGet(Mockito.any())).thenReturn(resultSetMock); + assertEquals("key10$10", cassaLockStore.getAllLocksForOwner("owneer10", "keyspace10", "table10").get(1)); + } catch (MusicServiceException | MusicQueryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testDequeueLockRef() throws Exception { + cassaLockStore.deQueueLockRef("keyspace1", "table1", "key6", "6", 2); + + // note only expecting 1 call to this instance, expecting it to succeed + Mockito.verify(dsHandle, Mockito.times(1)).executePut(Mockito.any(), Mockito.anyString()); + } + + @Test + public void testDequeueLockRefWriteTimeout() throws Exception { + int retryCount = 22; + try { + Mockito.when(dsHandle.executePut(Mockito.any(), Mockito.anyString())) + .thenThrow(new MusicServiceException("Cassandra timeout during...")); + cassaLockStore.deQueueLockRef("keyspace1", "table1", "key6", "6", retryCount); + + // Should never reach here + fail(); + } catch (MusicServiceException | MusicQueryException | MusicLockingException e) { + // should throw an error + } + + Mockito.verify(dsHandle, Mockito.times(retryCount)).executePut(Mockito.any(), Mockito.anyString()); + } +} diff --git a/music-core/src/test/java/org/onap/music/lockingservice/cassandra/MusicLockStateTest.java b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/MusicLockStateTest.java new file mode 100644 index 00000000..e5b655bd --- /dev/null +++ b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/MusicLockStateTest.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 AT&T Intellectual Property + * =================================================================== + * 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.music.lockingservice.cassandra; + +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus; + +public class MusicLockStateTest { + + MusicLockState musicLockState; + + @Before + public void setup() { + musicLockState = new MusicLockState(LockStatus.LOCKED, "", true); + } + + @Test + public void testGetLeasePeriod() { + musicLockState.setLeasePeriod(200L); + assertEquals(200L, musicLockState.getLeasePeriod()); + } + + @Test + public void testIsNeedToSyncQuorum() { + assertEquals(true, musicLockState.isNeedToSyncQuorum()); + } + + @Test + public void testGetLeaseStartTime() { + musicLockState.setLeaseStartTime(200L); + assertEquals(200L, musicLockState.getLeaseStartTime()); + } + + @Test + public void testGetLockStatus() { + musicLockState.setLockStatus(LockStatus.LOCKED); + assertEquals(LockStatus.LOCKED, musicLockState.getLockStatus()); + } + + @Test + public void testGetLockHolder() { + musicLockState.setLockHolder("lockHolder"); + assertEquals("lockHolder", musicLockState.getLockHolder()); + } + + @Test + public void testGetErrorMessage() { + MusicLockState musicLockState2 = new MusicLockState("This is error message"); + assertEquals("This is error message", musicLockState2.getErrorMessage()); + } + + @Test + public void testSerialize() { + byte[] serializedBytes = musicLockState.serialize(); + MusicLockState musicLockState3 = musicLockState.deSerialize(serializedBytes); + assertEquals(musicLockState.getLeasePeriod(),musicLockState3.getLeasePeriod()); + assertEquals(musicLockState.isNeedToSyncQuorum(),musicLockState3.isNeedToSyncQuorum()); + assertEquals(musicLockState.getLeaseStartTime(),musicLockState3.getLeaseStartTime()); + assertEquals(musicLockState.getLockStatus(),musicLockState3.getLockStatus()); + assertEquals(musicLockState.getLockHolder(),musicLockState3.getLockHolder()); + assertEquals(musicLockState.getErrorMessage(),musicLockState3.getErrorMessage()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/main/CipherUtilTest.java b/music-core/src/test/java/org/onap/music/main/CipherUtilTest.java new file mode 100644 index 00000000..ff187ffd --- /dev/null +++ b/music-core/src/test/java/org/onap/music/main/CipherUtilTest.java @@ -0,0 +1,55 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.main; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class CipherUtilTest { + + private CipherUtil cipherUtil; + + @Before + public void setup() { + cipherUtil = new CipherUtil(); + } + + @Test + public void testEncryptPKC() { + String encryptedText = CipherUtil.encryptPKC("This is another string to be encrypted", + "4BFF9DCCD774F3650E20C4D3F69F8C99"); + System.out.println("*************************" + encryptedText); + assertEquals(88, encryptedText.length()); + } + + @Test + public void testDecryptPKC() { + String encryptedText = CipherUtil.encryptPKC("This is another string to be encrypted", + "4BFF9DCCD774F3650E20C4D3F69F8C99"); + assertEquals("This is another string to be encrypted", + CipherUtil.decryptPKC(encryptedText, "4BFF9DCCD774F3650E20C4D3F69F8C99")); + } + +} diff --git a/music-core/src/test/java/org/onap/music/main/DeadlockDetectionUtilTest.java b/music-core/src/test/java/org/onap/music/main/DeadlockDetectionUtilTest.java new file mode 100644 index 00000000..ab767e17 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/main/DeadlockDetectionUtilTest.java @@ -0,0 +1,87 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 IBM Intellectual Property + * =================================================================== + * 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.music.main; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.Before; +import org.junit.Test; +//import org.junit.experimental.runners.Enclosed; +//import org.junit.runner.RunWith; +import org.onap.music.main.DeadlockDetectionUtil.OwnershipType; + +//@RunWith(Enclosed.class) +public class DeadlockDetectionUtilTest { + private DeadlockDetectionUtil ddu; + + @Before + public void setup() { + ddu = new DeadlockDetectionUtil(); + } + + @Test + public void testListAllNodes() { + ddu = new DeadlockDetectionUtil(); + ddu.setExisting("r1", "o2", OwnershipType.ACQUIRED); + ddu.setExisting("r3", "o2", OwnershipType.ACQUIRED); + + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + ddu.listAllNodes(); + + /* + * String expectedOutput = "In DeadlockDetectionUtil: \n" + + * " o2 : Node [id=o2, links=r3, visited=false, onStack=false]\n" + + * " r3 : Node [id=r3, links=, visited=false, onStack=false]\n" + + * " r1 : Node [id=r1, links=o2, visited=false, onStack=false]\n"; + * assertEquals(expectedOutput, outContent.toString()); + * + * ddu = new DeadlockDetectionUtil(); ddu.setExisting("111", "222", + * OwnershipType.CREATED); ddu.setExisting("333", "222", OwnershipType.CREATED); + * outContent = new ByteArrayOutputStream(); System.setOut(new + * PrintStream(outContent)); ddu.listAllNodes(); expectedOutput = + * "In DeadlockDetectionUtil: \n" + + * " o222 : Node [id=o222, links=r111r333, visited=false, onStack=false]\n" + + * " r333 : Node [id=r333, links=, visited=false, onStack=false]\n" + + * " r111 : Node [id=r111, links=, visited=false, onStack=false]"; + * assertEquals(expectedOutput, outContent.toString()); + */ + } + + @Test + public void testcheckForDeadlock() { + ddu = new DeadlockDetectionUtil(); + ddu.setExisting("111", "222", DeadlockDetectionUtil.OwnershipType.ACQUIRED); + ddu.setExisting("333", "444", DeadlockDetectionUtil.OwnershipType.ACQUIRED); + assertEquals(false, ddu.checkForDeadlock("111", "444", DeadlockDetectionUtil.OwnershipType.CREATED)); + + ddu = new DeadlockDetectionUtil(); + ddu.setExisting("111", "222", DeadlockDetectionUtil.OwnershipType.ACQUIRED); + ddu.setExisting("333", "444", DeadlockDetectionUtil.OwnershipType.ACQUIRED); + ddu.setExisting("333", "222", DeadlockDetectionUtil.OwnershipType.CREATED); + assertEquals(true, ddu.checkForDeadlock("111", "444", DeadlockDetectionUtil.OwnershipType.CREATED)); + } +} diff --git a/music-core/src/test/java/org/onap/music/main/MusicCoreTest.java b/music-core/src/test/java/org/onap/music/main/MusicCoreTest.java new file mode 100644 index 00000000..4714778b --- /dev/null +++ b/music-core/src/test/java/org/onap/music/main/MusicCoreTest.java @@ -0,0 +1,391 @@ +/******************************************************************************* + * ============LICENSE_START========================================== org.onap.music + * =================================================================== Copyright (c) 2019 AT&T + * Intellectual Property =================================================================== + * 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.music.main; + +import static org.junit.Assert.assertEquals; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.FieldSetter; +import org.onap.music.datastore.Condition; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonIndex; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonSelect; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.datastore.jsonobjects.JsonUpdate; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.lockingservice.cassandra.MusicLockState; +import org.onap.music.service.MusicCoreService; +import com.datastax.driver.core.ResultSet; + +public class MusicCoreTest { + + MusicCore mCore; + MusicCoreService musicCore; + CassaLockStore mLockHandle; + + @Before + public void setup() { + mCore = new MusicCore(); + musicCore = Mockito.mock(MusicCoreService.class); + mLockHandle = Mockito.mock(CassaLockStore.class); + try { + FieldSetter.setField(mCore, mCore.getClass().getDeclaredField("musicCore"), musicCore); + } catch (NoSuchFieldException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testAcquireLock() throws MusicLockingException, MusicQueryException, MusicServiceException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + Mockito.when(musicCore.acquireLock(Mockito.any(), Mockito.any())).thenReturn(returnType); + result = MusicCore.acquireLock("key1", "lockid1"); + assertEquals(returnType, result); + } + + @Test + public void testacquireLockWithLease() throws MusicLockingException, MusicQueryException, MusicServiceException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + Mockito.when(musicCore.acquireLockWithLease(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong())) + .thenReturn(returnType); + result = MusicCore.acquireLockWithLease("key1", "lockid1", 100L); + assertEquals(returnType, result); + } + + @Test + public void testCreateLockReferenceAtomic() throws MusicLockingException { + String result = null; + Mockito.when(musicCore.createLockReferenceAtomic(Mockito.any())).thenReturn("lockreference1"); + result = MusicCore.createLockReferenceAtomic("key2"); + assertEquals("lockreference1", result); + } + + @Test + public void testCreateLockReference() throws MusicLockingException { + String result = null; + Mockito.when(musicCore.createLockReference(Mockito.any(), Mockito.any())).thenReturn("lockreference2"); + result = MusicCore.createLockReference("key3", "owner3"); + assertEquals("lockreference2", result); + } + + @Test + public void testCreateLockReferenceAtomic2() throws MusicLockingException { + String result = null; + Mockito.when(musicCore.createLockReferenceAtomic(Mockito.any(), Mockito.any())).thenReturn("lockreference3"); + result = MusicCore.createLockReferenceAtomic("key4", LockType.READ); + assertEquals("lockreference3", result); + } + + @Test + public void testCreateLockReference2() throws MusicLockingException { + String result = null; + Mockito.when(musicCore.createLockReference(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn("lockreference4"); + result = MusicCore.createLockReference("key4", LockType.READ, "owner4"); + assertEquals("lockreference4", result); + } + + @Test + public void testCreateTable() throws MusicServiceException { + ResultType resultType = Mockito.mock(ResultType.class); + ResultType result = null; + Mockito.when(musicCore.createTable(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(resultType); + result = MusicCore.createTable("keyspace1", "table1", new PreparedQueryObject(), "consistency"); + assertEquals(resultType, result); + } + + @Test + public void testQuorumGet() { + ResultSet rs = Mockito.mock(ResultSet.class); + Mockito.when(musicCore.quorumGet(Mockito.any())).thenReturn(rs); + assertEquals(rs, MusicCore.quorumGet(new PreparedQueryObject())); + } + + @Test + public void testWhoseTurnIsIt() { + Mockito.when(musicCore.whoseTurnIsIt(Mockito.any())).thenReturn("turn"); + assertEquals("turn", MusicCore.whoseTurnIsIt("key5")); + } + + @Test + public void testGetCurrentLockHolders() { + List<String> result = Mockito.mock(List.class); + Mockito.when(musicCore.getCurrentLockHolders(Mockito.any())).thenReturn(result); + assertEquals(result, MusicCore.getCurrentLockHolders("key6")); + } + + @Test + public void testPromoteLock() throws MusicLockingException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + Mockito.when(musicCore.promoteLock(Mockito.any())).thenReturn(returnType); + result = MusicCore.promoteLock("lockid2"); + assertEquals(returnType, result); + } + + @Test + public void testEventualPut() { + ReturnType returnType = Mockito.mock(ReturnType.class); + Mockito.when(musicCore.eventualPut(Mockito.any())).thenReturn(returnType); + assertEquals(returnType, MusicCore.eventualPut(new PreparedQueryObject())); + } + + @Test + public void testEventualPut_nb() { + ReturnType returnType = Mockito.mock(ReturnType.class); + Mockito.when(musicCore.eventualPut_nb(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(returnType); + assertEquals(returnType, + MusicCore.eventualPut_nb(new PreparedQueryObject(), "keyspace2", "table2", "primarykey1")); + } + + @Test + public void testCriticalPut() { + ReturnType returnType = Mockito.mock(ReturnType.class); + Mockito.when(musicCore.criticalPut(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any())).thenReturn(returnType); + assertEquals(returnType, MusicCore.criticalPut("keyspace3", "table3", "primarykey2", new PreparedQueryObject(), + "lockreference2", new Condition(new HashMap(), new PreparedQueryObject()))); + } + + @Test + public void testNonKeyRelatedPut() throws MusicServiceException, MusicQueryException { + ResultType resultType = Mockito.mock(ResultType.class); + ResultType result = null; + Mockito.when(musicCore.nonKeyRelatedPut(Mockito.any(), Mockito.any())).thenReturn(resultType); + result = MusicCore.nonKeyRelatedPut(new PreparedQueryObject(), "consistency2"); + assertEquals(resultType, result); + } + + @Test + public void testGet() throws MusicServiceException { + ResultSet rs = Mockito.mock(ResultSet.class); + ResultSet result = null; + Mockito.when(musicCore.get(Mockito.any())).thenReturn(rs); + result = MusicCore.get(new PreparedQueryObject()); + assertEquals(rs, result); + } + + @Test + public void testCriticalGet() throws MusicServiceException { + ResultSet rs = Mockito.mock(ResultSet.class); + ResultSet result = null; + Mockito.when(musicCore.criticalGet(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(rs); + result = MusicCore.criticalGet("keyspace4", "table4", "primarykey3", new PreparedQueryObject(), + "lockreference3"); + assertEquals(rs, result); + } + + @Test + public void testAtomicPut() throws MusicLockingException, MusicQueryException, MusicServiceException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + Mockito.when(musicCore.atomicPut(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(returnType); + result = MusicCore.atomicPut("keyspace5", "table5", "primarykey4", new PreparedQueryObject(), + new Condition(new HashMap(), new PreparedQueryObject())); + assertEquals(returnType, result); + } + + @Test + public void testAtomicGet() throws MusicServiceException, MusicLockingException, MusicQueryException { + ResultSet rs = Mockito.mock(ResultSet.class); + ResultSet result = null; + Mockito.when(musicCore.atomicGet(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(rs); + result = MusicCore.atomicGet("keyspace5", "table5", "primarykey4", new PreparedQueryObject()); + assertEquals(rs, result); + } + + @Test + public void testGetLockQueue() throws MusicServiceException, MusicQueryException, MusicLockingException { + List<String> result = Mockito.mock(List.class); + List<String> rst = null; + Mockito.when(musicCore.getLockQueue(Mockito.any())).thenReturn(result); + rst = MusicCore.getLockQueue("key5"); + assertEquals(result, rst); + } + + @Test + public void testGetLockQueueSize() throws MusicServiceException, MusicQueryException, MusicLockingException { + long result = 0L; + Mockito.when(musicCore.getLockQueueSize(Mockito.any())).thenReturn(100L); + result = MusicCore.getLockQueueSize("key6"); + assertEquals(100L, result); + } + + @Test + public void testatomicPutWithDeleteLock() throws MusicLockingException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + Mockito.when(musicCore.atomicPutWithDeleteLock(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any())).thenReturn(returnType); + result = MusicCore.atomicPutWithDeleteLock("keyspace5", "table5", "primarykey4", new PreparedQueryObject(), + new Condition(new HashMap(), new PreparedQueryObject())); + assertEquals(returnType, result); + } + + @Test + public void testAtomicGetWithDeleteLock() throws MusicServiceException, MusicLockingException { + ResultSet rs = Mockito.mock(ResultSet.class); + ResultSet result = null; + Mockito.when(musicCore.atomicGetWithDeleteLock(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(rs); + result = MusicCore.atomicGetWithDeleteLock("keyspace5", "table5", "primarykey4", new PreparedQueryObject()); + assertEquals(rs, result); + } + + @Test + public void testValidateLock() { + Map<String, Object> map = Mockito.mock(Map.class); + Mockito.when(musicCore.validateLock(Mockito.any())).thenReturn(map); + assertEquals(map, MusicCore.validateLock("lockname")); + } + + @Test + public void testReleaseLock() throws MusicLockingException { + MusicLockState musicLockState = Mockito.mock(MusicLockState.class); + MusicLockState result = null; + Mockito.when(musicCore.releaseLock(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(musicLockState); + result = MusicCore.releaseLock("lockid", true); + assertEquals(musicLockState, result); + } + + @Test + public void testReleaseAllLocksForOwner() throws MusicLockingException, MusicServiceException, MusicQueryException { + List<String> result = Mockito.mock(List.class); + List<String> rst = null; + Mockito.when(musicCore.releaseAllLocksForOwner(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(result); + rst = MusicCore.releaseAllLocksForOwner("owner2", "keyspace6", "table6"); + assertEquals(result, rst); + } + + @Test + public void testCreateKeyspace() throws MusicServiceException, MusicQueryException { + ResultType resultType = Mockito.mock(ResultType.class); + ResultType result = null; + Mockito.when(musicCore.createKeyspace(Mockito.any(), Mockito.any())).thenReturn(resultType); + result = MusicCore.createKeyspace(new JsonKeySpace(), "consistency3"); + assertEquals(resultType, result); + } + + @Test + public void testDropKeyspace() throws MusicServiceException, MusicQueryException { + ResultType resultType = Mockito.mock(ResultType.class); + ResultType result = null; + Mockito.when(musicCore.dropKeyspace(Mockito.any(), Mockito.any())).thenReturn(resultType); + result = MusicCore.dropKeyspace(new JsonKeySpace(), "consistency4"); + assertEquals(resultType, result); + } + + @Test + public void testCreateTable2() throws MusicServiceException, MusicQueryException { + ResultType resultType = Mockito.mock(ResultType.class); + ResultType result = null; + Mockito.when(musicCore.createTable(Mockito.any(), Mockito.any())).thenReturn(resultType); + result = MusicCore.createTable(new JsonTable(), "consistency5"); + assertEquals(resultType, result); + } + + @Test + public void testDropTable() throws MusicServiceException, MusicQueryException { + ResultType resultType = Mockito.mock(ResultType.class); + ResultType result = null; + Mockito.when(musicCore.dropTable(Mockito.any(), Mockito.any())).thenReturn(resultType); + result = MusicCore.dropTable(new JsonTable(), "consistency5"); + assertEquals(resultType, result); + } + + @Test + public void testCreateIndex() throws MusicServiceException, MusicQueryException { + ResultType resultType = Mockito.mock(ResultType.class); + ResultType result = null; + Mockito.when(musicCore.createIndex(Mockito.any(), Mockito.any())).thenReturn(resultType); + result = MusicCore.createIndex(new JsonIndex("indexName", "keyspace7", "table7", "field"), "consistency6"); + assertEquals(resultType, result); + } + + @Test + public void testSelect() throws MusicServiceException, MusicQueryException { + ResultSet rs = Mockito.mock(ResultSet.class); + ResultSet result = null; + Mockito.when(musicCore.select(Mockito.any(), Mockito.any())).thenReturn(rs); + MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class); + result = MusicCore.select(new JsonSelect(), map); + assertEquals(rs, result); + } + + @Test + public void testSelectCritical() throws MusicLockingException, MusicQueryException, MusicServiceException { + ResultSet rs = Mockito.mock(ResultSet.class); + ResultSet result = null; + Mockito.when(musicCore.selectCritical(Mockito.any(), Mockito.any())).thenReturn(rs); + MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class); + result = MusicCore.selectCritical(new JsonInsert(), map); + assertEquals(rs, result); + } + + @Test + public void testInsertIntoTable() throws MusicLockingException, MusicQueryException, MusicServiceException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + Mockito.when(musicCore.insertIntoTable(Mockito.any())).thenReturn(returnType); + result = MusicCore.insertIntoTable(new JsonInsert()); + assertEquals(returnType, result); + } + + @Test + public void testUpdateTable() throws MusicLockingException, MusicQueryException, MusicServiceException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + Mockito.when(musicCore.updateTable(Mockito.any(), Mockito.any())).thenReturn(returnType); + MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class); + result = MusicCore.updateTable(new JsonUpdate(), map); + assertEquals(returnType, result); + } + + @Test + public void testDeleteFromTable() throws MusicLockingException, MusicQueryException, MusicServiceException { + ReturnType returnType = Mockito.mock(ReturnType.class); + ReturnType result = null; + MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class); + Mockito.when(musicCore.deleteFromTable(Mockito.any(), Mockito.any())).thenReturn(returnType); + result = MusicCore.deleteFromTable(new JsonDelete(), map); + assertEquals(returnType, result); + } +} diff --git a/music-core/src/test/java/org/onap/music/main/ResultTypeTest.java b/music-core/src/test/java/org/onap/music/main/ResultTypeTest.java new file mode 100644 index 00000000..d6ccc1f1 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/main/ResultTypeTest.java @@ -0,0 +1,42 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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.music.main; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class ResultTypeTest { + + @Test + public void testResultType() { + assertEquals("SUCCESS",ResultType.SUCCESS.name()); + assertEquals("FAILURE",ResultType.FAILURE.name()); + } + + @Test + public void testGetResult() { + assertEquals("Success",ResultType.SUCCESS.getResult()); + assertEquals("Failure",ResultType.FAILURE.getResult()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java b/music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java new file mode 100644 index 00000000..fbb5f84d --- /dev/null +++ b/music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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.music.main; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Map; + +import org.junit.Test; + +public class ReturnTypeTest { + + @Test + public void testReturnType() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + assertEquals(result.getMessage(),"message"); + assertEquals(result.getResult(),ResultType.SUCCESS); + } + + @Test + public void testTimingInfo() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + result.setTimingInfo("123"); + assertEquals(result.getTimingInfo(),"123"); + } + + @Test + public void testGetResult() { + ReturnType result = new ReturnType(ResultType.FAILURE,"message"); + assertEquals(result.getResult(),ResultType.FAILURE); + } + + @Test + public void testGetMessage() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + result.setMessage("NewMessage"); + assertEquals(result.getMessage(),"NewMessage"); + } + + @Test + public void testToJson() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + String myJson = result.toJson(); + assertTrue(myJson.contains("message")); + } + + @Test + public void testToString() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + String test = result.toString(); + assertTrue(test.contains("message")); + } + + @Test + public void testToMap() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + Map<String, Object> myMap = result.toMap(); + assertTrue(myMap.containsKey("message")); + } + +} diff --git a/music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java b/music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java new file mode 100644 index 00000000..33debfaa --- /dev/null +++ b/music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java @@ -0,0 +1,485 @@ +/******************************************************************************* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2018 AT&T Intellectual Property + * =================================================================== + * 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.music.service.impl; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.MusicDataStoreHandle; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.cassandra.CassaLockStore; +import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject; +import org.onap.music.lockingservice.cassandra.LockType; +import org.onap.music.main.MusicUtil; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; + +@RunWith(MockitoJUnitRunner.class) +public class MusicCassaCoreTest { + + @Mock + private CassaLockStore mLockHandle; + + @Mock + private MusicDataStore dsHandle; + + @Mock + private Session session; + + MusicCassaCore core; + + @Before + public void before() { + core = MusicCassaCore.getInstance(); + MusicCassaCore.setmLockHandle(mLockHandle); + MusicDataStoreHandle.setMDstoreHandle(dsHandle); + Mockito.when(dsHandle.getSession()).thenReturn(session); + } + + @Test + public void testGetmLockHandle() { + assertEquals(mLockHandle, MusicCassaCore.getmLockHandle()); + } + + @Test + public void testSetmLockHandle() { + CassaLockStore m2 = Mockito.mock(CassaLockStore.class); + MusicCassaCore.setmLockHandle(m2); + assertEquals(m2, MusicCassaCore.getmLockHandle()); + //revert back to original handle + MusicCassaCore.setmLockHandle(mLockHandle); + } + + @Test + public void testGetInstance() { + assertEquals(core, MusicCassaCore.getInstance()); + } + + @Test + public void testGetLockingServiceHandle() { + assertEquals(mLockHandle, MusicCassaCore.getmLockHandle()); + } + + @Test + public void testCreateLockReferenceAtomicString() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, null)) + .thenReturn("lockReturned"); + + String lockRef = core.createLockReferenceAtomic(fullyQualifiedKey); + + Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, null); + assertEquals("lockReturned", lockRef); + } + + @Test + public void testCreateLockReferenceStringString() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + String owner = "owner1"; + Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, owner)) + .thenReturn("lockReturned"); + + String lockRef = core.createLockReference(fullyQualifiedKey, owner); + + Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, owner); + assertEquals("lockReturned", lockRef); + } + + @Test + public void testCreateLockReferenceAtomicStringLockType() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, null)) + .thenReturn("lockReturned"); + + String lockRef = core.createLockReferenceAtomic(fullyQualifiedKey, LockType.READ); + + Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, null); + assertEquals("lockReturned", lockRef); + } + + @Test + public void testCreateLockReferenceStringLockTypeString() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + String owner = "owner1"; + Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, owner)) + .thenReturn("lockReturned"); + + String lockRef = core.createLockReference(fullyQualifiedKey, LockType.READ, owner); + + Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, owner); + assertEquals("lockReturned", lockRef); + } + + @Test + public void testPromoteLock() throws Exception { + String lockId = "$keyspace.table.lockName$1"; + Mockito.when(mLockHandle.promoteLock("keyspace", "table", "lockName", "1")) + .thenReturn(new ReturnType(ResultType.SUCCESS, "Lock Promoted")); + + ReturnType rt = core.promoteLock(lockId); + assertEquals(ResultType.SUCCESS, rt.getResult()); + assertEquals("Lock Promoted", rt.getMessage()); + } + + @Test + public void testAcquireLockWithLease() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + String lockId = "$keyspace.table.lockName$1"; + long leasePeriod = 1000; + String currTime = String.valueOf(System.currentTimeMillis()); + Mockito.when(mLockHandle.peekLockQueue("keyspace", "table", "lockName")) + .thenReturn(mLockHandle.new LockObject(true, lockId, currTime, currTime, LockType.WRITE, null)); + Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1")) + .thenReturn(mLockHandle.new LockObject(false, lockId, null, null, LockType.WRITE, null)); + + ReturnType rt = core.acquireLockWithLease(fullyQualifiedKey, lockId, leasePeriod); + assertEquals(ResultType.FAILURE, rt.getResult()); + } + + @Test + public void testAcquireLock() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + String lockId = "$keyspace.table.lockName$1"; + Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1")) + .thenReturn(mLockHandle.new LockObject(false, lockId, null, null, LockType.WRITE, null)); + + ReturnType rt = core.acquireLock(fullyQualifiedKey, lockId); + + assertEquals(ResultType.FAILURE, rt.getResult()); + Mockito.verify(mLockHandle).getLockInfo("keyspace", "table", "lockName", "1"); + /*TODO: if we successfully acquire the lock we hit an error by trying to read MusicDatastoreHandle */ + } + + @Test + public void testWhoseTurnIsIt() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + Mockito.when(mLockHandle.peekLockQueue("keyspace", "table", "lockName")) + .thenReturn(mLockHandle.new LockObject(true, "1", "", "", LockType.WRITE, null)); + + String topOfQ = core.whoseTurnIsIt(fullyQualifiedKey); + System.out.println(topOfQ); + + assertEquals("$"+fullyQualifiedKey+"$1", topOfQ); + } + + @Test + public void testGetCurrentLockHolders() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + List<String> currentHolders = new ArrayList<>(); + currentHolders.add("$"+fullyQualifiedKey+"$1"); + currentHolders.add("$"+fullyQualifiedKey+"$2"); + Mockito.when(mLockHandle.getCurrentLockHolders("keyspace", "table", "lockName")) + .thenReturn(currentHolders); + + List<String> holders = core.getCurrentLockHolders(fullyQualifiedKey); + + assertTrue(currentHolders.containsAll(holders) && holders.containsAll(currentHolders)); + } + + @Test + public void testGetLockNameFromId() { + String lockId = "$keyspace.table.lockName$1"; + assertEquals("keyspace.table.lockName", core.getLockNameFromId(lockId)); + } + + @Test + public void testDestroyLockRefString() throws Exception { + String lockId = "$keyspace.table.lockName$1"; + + core.destroyLockRef(lockId); + Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount()); + } + + @Test + public void testDestroyLockRefStringString() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + String lockReference = "1"; + + core.destroyLockRef(fullyQualifiedKey, lockReference); + Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount()); + } + + @Test + public void testReleaseLock() throws Exception { + String lockId = "$keyspace.table.lockName$1"; + + core.releaseLock(lockId, true); + + Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount()); + } + + @Test + public void testVoluntaryReleaseLock() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + String lockReference = "1"; + + core.voluntaryReleaseLock(fullyQualifiedKey, lockReference); + + Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount()); + } + + @Test + public void testReleaseAllLocksForOwner() throws Exception { + List<String> ownersLocks = new ArrayList<>(); + ownersLocks.add("lockName$1"); + ownersLocks.add("lockName$2"); + Mockito.when(mLockHandle.getAllLocksForOwner("ownerId", "keyspace", "table")) + .thenReturn(ownersLocks); + + List<String> locksReleased = core.releaseAllLocksForOwner("ownerId", "keyspace", "table"); + + Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount()); + Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "2", MusicUtil.getRetryCount()); + assertTrue(ownersLocks.containsAll(locksReleased) && locksReleased.containsAll(ownersLocks)); + } + + + @Test + public void testValidateLock() { + String lockId = "$keyspace.table.lockName$1"; + + assertFalse(core.validateLock(lockId).containsKey("Error")); + } + + @Test + public void testGetLockQueue() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + List<String> myList = new ArrayList<>(); + Mockito.when(mLockHandle.getLockQueue("keyspace", "table", "lockName")) + .thenReturn(myList); + List<String> theirList = core.getLockQueue(fullyQualifiedKey); + + assertEquals(myList, theirList); + } + + @Test + public void testGetLockQueueSize() throws Exception { + String fullyQualifiedKey = "keyspace.table.lockName"; + Mockito.when(mLockHandle.getLockQueueSize("keyspace", "table", "lockName")) + .thenReturn((long) 23); + long theirSize = core.getLockQueueSize(fullyQualifiedKey); + + assertEquals(23, theirSize); + } + + @Test + public void testCreateTable() throws MusicServiceException, MusicQueryException { + String keyspaceName = "keyspace"; + String tableName = "table"; + JsonTable table = new JsonTable(); + table.setTableName(tableName); + table.setKeyspaceName(keyspaceName); + Map<String, String> fields = new HashMap<>(); + fields.put("employee", "text"); + fields.put("salary", "int"); + table.setFields(fields); + table.setPrimaryKey("employee"); + + Mockito.when(mLockHandle.createLockQueue(Mockito.matches(keyspaceName), Mockito.matches(tableName))) + .thenReturn(true); + Mockito.when(dsHandle.executePut(Mockito.any(PreparedQueryObject.class), Mockito.matches("eventual"))).thenReturn(true); + ResultType rs = core.createTable(table , "eventual"); + + assertEquals(ResultType.SUCCESS, rs); + } + + @Test + public void testDropTable() throws MusicServiceException, MusicQueryException { + String keyspaceName = "keyspace"; + String tableName = "table"; + JsonTable table = new JsonTable(); + table.setTableName(tableName); + table.setKeyspaceName(keyspaceName); + + ArgumentCaptor<PreparedQueryObject> queryCaptor = ArgumentCaptor.forClass(PreparedQueryObject.class); + Mockito.when(dsHandle.executePut(queryCaptor.capture(), Mockito.matches("eventual"))).thenReturn(true); + + ResultType rs = core.dropTable(table, "eventual"); + assertEquals(ResultType.SUCCESS, rs); + assertEquals("DROP TABLE keyspace.table;", queryCaptor.getValue().getQuery()); + } + + @Test + public void testQuorumGet() throws MusicServiceException, MusicQueryException { + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES;"); + ResultSet rs = Mockito.mock(ResultSet.class); + Mockito.when(dsHandle.executeQuorumConsistencyGet(Mockito.same(query))).thenReturn(rs); + ResultSet returnedRs = core.quorumGet(query); + + assertEquals(rs, returnedRs); + } + + @Test + public void testForciblyReleaseLock() throws MusicServiceException, MusicQueryException, MusicLockingException { + String fullyQualifiedKey = "keyspace.table.lockName"; + ArgumentCaptor<PreparedQueryObject> unsyncedQuery = ArgumentCaptor.forClass(PreparedQueryObject.class); + Mockito.doReturn(true).when(dsHandle).executePut(unsyncedQuery.capture(), Mockito.matches("critical")); + core.forciblyReleaseLock(fullyQualifiedKey, "123"); + + assertEquals("insert into keyspace.unsyncedKeys_table (key) values (?);",unsyncedQuery.getValue().getQuery()); + } + + @Test + public void testEventualPut() throws MusicServiceException, MusicQueryException { + PreparedQueryObject query = new PreparedQueryObject("INSERT INTO EMPLOYEES VALUES ('John', 1);"); + Mockito.when(dsHandle.executePut(Mockito.same(query), Mockito.matches("eventual"))).thenReturn(true); + + assertEquals(ResultType.SUCCESS, core.eventualPut(query).getResult()); + } + + @Test + public void testEventualPutNB() throws MusicServiceException, MusicQueryException { + String keyspace = "keyspace"; + String table = "EMPLOYEES"; + String primaryKey = "NAME"; + PreparedQueryObject query = new PreparedQueryObject("INSERT INTO EMPLOYEES VALUES ('John', 1);"); + + ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class); + ResultSet rs = Mockito.mock(ResultSet.class); + Row row = Mockito.mock(Row.class); + Mockito.when(dsHandle.executeQuorumConsistencyGet(queryCapture.capture())).thenReturn(rs); + Mockito.when(rs.one()).thenReturn(row); + + Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true); + + ReturnType rt = core.eventualPut_nb(query, keyspace, table, primaryKey); + + assertEquals("SELECT guard FROM keyspace.lockq_EMPLOYEES WHERE key = ? ;", + queryCapture.getAllValues().get(0).getQuery()); + assertEquals("INSERT INTO EMPLOYEES VALUES ('John', 1);", queryCapture.getAllValues().get(1).getQuery()); + + assertEquals(ResultType.SUCCESS, rt.getResult()); + } + + @Test + public void testCriticalPut() throws MusicServiceException, MusicQueryException { + String keyspace = "keyspace"; + String table = "table"; + String primaryKey = "lockName"; + PreparedQueryObject query = new PreparedQueryObject("INSERT INTO TABLE VALUES ('John', 1);"); + String lockId = "$keyspace.table.lockName$1"; + + Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1")) + .thenReturn(mLockHandle.new LockObject(true, lockId, null, null, LockType.WRITE, null)); + + ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class); + Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("critical"))).thenReturn(true); + ReturnType rt = core.criticalPut(keyspace, table, primaryKey, query, lockId, null); + + assertEquals(true, queryCapture.getValue().getQuery() + .startsWith("INSERT INTO TABLE VALUES ('John', 1) USING TIMESTAMP")); + assertEquals(ResultType.SUCCESS, rt.getResult()); + } + + @Test + public void testNonKeyRelatedPut() throws MusicServiceException, MusicQueryException { + PreparedQueryObject query = new PreparedQueryObject("INSERT INTO TABLE VALUES ('John', 1);"); + String consistency = "eventual"; + ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class); + Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches(consistency))).thenReturn(true); + + core.nonKeyRelatedPut(query, consistency); + + assertEquals(query.getQuery(), queryCapture.getValue().getQuery()); + } + + @Test + public void testGet() throws MusicServiceException, MusicQueryException { + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES;"); + ResultSet rs = Mockito.mock(ResultSet.class); + Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.same(query))).thenReturn(rs); + assertEquals(rs, core.get(query)); + } + + @Test + public void testCriticalGet() throws MusicServiceException, MusicQueryException { + String keyspace = "keyspace"; + String table = "table"; + String primaryKey = "lockName"; + PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES WHERE LOCKNAME='lockName';"); + String lockId = "$keyspace.table.lockName$1"; + + Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1")) + .thenReturn(mLockHandle.new LockObject(true, lockId, null, null, LockType.WRITE, null)); + + ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class); + ResultSet rs = Mockito.mock(ResultSet.class); + Mockito.when(dsHandle.executeQuorumConsistencyGet(queryCapture.capture())).thenReturn(rs); + assertEquals(rs, core.criticalGet(keyspace, table, primaryKey, query, lockId)); + } + + @Test + public void testCreateKeyspace() throws MusicServiceException, MusicQueryException { + String keyspace = "cycling"; + JsonKeySpace ks = new JsonKeySpace(); + ks.setKeyspaceName(keyspace); + ks.setDurabilityOfWrites("true"); + + Map<String, Object> replicationInfo = new HashMap<>(); + replicationInfo.put("class", "SimpleStrategy"); + replicationInfo.put("replication_factor", 1); + ks.setReplicationInfo(replicationInfo); + Map<String, String> consistencyInfo = new HashMap<>(); + consistencyInfo.put("consistency", "quorum"); + ks.setConsistencyInfo(consistencyInfo); + + ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class); + Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true); + + core.createKeyspace(ks , "eventual"); + + assertEquals("CREATE KEYSPACE cycling WITH replication = {'replication_factor':1,'class':'SimpleStrategy'} AND durable_writes = true;", + queryCapture.getValue().getQuery()); + } + + @Test + public void testDropKeyspace() throws MusicServiceException, MusicQueryException { + String keyspace = "cycling"; + JsonKeySpace ks = new JsonKeySpace(); + ks.setKeyspaceName(keyspace); + + ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class); + Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true); + + core.dropKeyspace(ks , "eventual"); + + assertEquals("DROP KEYSPACE cycling;", queryCapture.getValue().getQuery()); + } +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java new file mode 100644 index 00000000..7f6af4c5 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 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.music.unittests.jsonobjects; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import org.onap.music.datastore.jsonobjects.JSONObject; + +public class JSONObjectTest { + private JSONObject jsonObject; + + @Before + public void setUp() { + jsonObject = new JSONObject(); + } + + @Test + public void testGetSetData() { + jsonObject.setData("data"); + Assert.assertEquals("data", jsonObject.getData()); + } +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java new file mode 100644 index 00000000..b7dfa075 --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java @@ -0,0 +1,47 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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.music.unittests.jsonobjects; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.datastore.jsonobjects.JsonLeasedLock; + +public class JsonLeasedLockTest { + + JsonLeasedLock jl = null; + + @Before + public void init() { + jl = new JsonLeasedLock(); + } + + + @Test + public void testGetLeasePeriod() { + long lease = 20000; + jl.setLeasePeriod(lease); + assertEquals(lease,jl.getLeasePeriod()); + } + +} diff --git a/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java new file mode 100644 index 00000000..ceda3f3a --- /dev/null +++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2019 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.music.unittests.jsonobjects; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.onap.music.eelf.healthcheck.MusicHealthCheck; + +public class MusicHealthCheckTest { + + private MusicHealthCheck musicHealthCheck; + + @Before + public void setUp() + { + musicHealthCheck= new MusicHealthCheck(); + } + + @Test + public void testCassandraHost() + { + musicHealthCheck.setCassandrHost("9042"); + assertEquals("9042", musicHealthCheck.getCassandrHost()); + } + +} |