diff options
Diffstat (limited to 'src/test')
9 files changed, 1991 insertions, 0 deletions
diff --git a/src/test/java/LICENSE.txt b/src/test/java/LICENSE.txt new file mode 100644 index 00000000..cc6cdea5 --- /dev/null +++ b/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/src/test/java/org/onap/music/benchmarks/MicroBenchMarkRestClient.java b/src/test/java/org/onap/music/benchmarks/MicroBenchMarkRestClient.java new file mode 100644 index 00000000..2dcecfc2 --- /dev/null +++ b/src/test/java/org/onap/music/benchmarks/MicroBenchMarkRestClient.java @@ -0,0 +1,73 @@ +/* + * ============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.benchmarks; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import org.onap.music.main.MusicUtil; + + +@Path("/tests") +public class MicroBenchMarkRestClient { + static double version = 9.7; + + @GET + @Path("/run") + @Produces(MediaType.TEXT_PLAIN) + public String runTests() { + String testType = MusicUtil.getTestType(); + String candidateName = "shankar" + System.currentTimeMillis(); + MicroBenchMarks msHandle = new MicroBenchMarks(); + switch (testType) { + case "musicPut": + return msHandle.musicPutAndUpdate(candidateName); + + case "musicCriticalPut": + return msHandle.musicCriticalPutAndUpdate(candidateName); + + case "musicGet": + return msHandle.musicGet(); + + case "cassaPut": + return msHandle.cassaPutAndUpdate(candidateName); + + case "cassaQuorumPut": + return msHandle.cassaQuorumPutAndUpdate(candidateName); + + case "cassaGet": + return msHandle.cassaGet(); + + case "zkPut": + return msHandle.zkPutAndUpdate(candidateName); + + case "zkGet": + return msHandle.zkGet(); + + } + return "something wrong!"; + + } + +} + diff --git a/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java b/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java new file mode 100644 index 00000000..a9b40aec --- /dev/null +++ b/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java @@ -0,0 +1,440 @@ +/* + * ============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.benchmarks; + +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonTable; +import org.onap.music.main.MusicUtil; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.json.JSONConfiguration; + +public class MicroBenchMarks { + final String keyspaceName = "shankarks"; + final String musicurl = "http://" + MusicUtil.musicRestIp + ":8080/MUSIC/rest/formal"; + final String userForGets = "shankarUserForGets"; + + public MicroBenchMarks() { + bootStrap(); + } + + private void createVotingKeyspace() { + System.out.println(keyspaceName); + Map<String, Object> replicationInfo = new HashMap<String, Object>(); + replicationInfo.put("class", "SimpleStrategy"); + replicationInfo.put("replication_factor", 3); + String durabilityOfWrites = "false"; + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + JsonKeySpace jsonKp = new JsonKeySpace(); + jsonKp.setConsistencyInfo(consistencyInfo); + jsonKp.setDurabilityOfWrites(durabilityOfWrites); + jsonKp.setReplicationInfo(replicationInfo); + + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + WebResource webResource = client.resource(musicurl + "/keyspaces/" + keyspaceName); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .post(ClientResponse.class, jsonKp); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + } + + private void createVotingTable() { + Map<String, String> fields = new HashMap<String, String>(); + fields.put("name", "text"); + fields.put("count", "varint"); + fields.put("PRIMARY KEY", "(name)"); + + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonTable jtab = new JsonTable(); + jtab.setFields(fields); + jtab.setConsistencyInfo(consistencyInfo); + + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + WebResource webResource = client + .resource(musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount"); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .post(ClientResponse.class, jtab); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + } + + private void createEntryForCandidate(String candidateName) { + Map<String, Object> values = new HashMap<String, Object>(); + values.put("name", candidateName); + values.put("count", 0); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows"; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .post(ClientResponse.class, jIns); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + private String createLock(String lockName) { + Client client = Client.create(); + String msg = musicurl + "/locks/create/" + lockName; + WebResource webResource = client.resource(msg); + System.out.println(msg); + + WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); + + ClientResponse response = wb.post(ClientResponse.class); + + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + String output = response.getEntity(String.class); + + return output; + } + + private boolean acquireLock(String lockId) { + Client client = Client.create(); + String msg = musicurl + "/locks/acquire/" + lockId; + System.out.println(msg); + WebResource webResource = client.resource(msg); + + + WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); + + ClientResponse response = wb.get(ClientResponse.class); + + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + String output = response.getEntity(String.class); + Boolean status = Boolean.parseBoolean(output); + System.out.println("Server response .... \n"); + System.out.println(output); + return status; + } + + private void unlock(String lockId) { + Client client = Client.create(); + WebResource webResource = client.resource(musicurl + "/locks/release/" + lockId); + + ClientResponse response = webResource.delete(ClientResponse.class); + + + if (response.getStatus() != 204) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + } + + public String musicCriticalPutAndUpdate(String candidateName) { + /* + * create lock for the candidate. The music API dictates that the lock name must be of the + * form keyspacename.tableName.primaryKeyName + */ + createEntryForCandidate(candidateName); + System.out.println("trying to acquire lock!"); + + String lockName = keyspaceName + ".votecount." + candidateName; + String lockId = createLock(lockName); + while (acquireLock(lockId) != true); + + System.out.println("acquired lock!"); + // update candidate entry if you have the lock + Map<String, Object> values = new HashMap<String, Object>(); + values.put("count", 5); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "atomic"); + consistencyInfo.put("lockId", lockId); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" + + candidateName; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .put(ClientResponse.class, jIns); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + // release lock now that the operation is done + unlock(lockId); + return "musicCriticalPutAndUpdate:" + url; + + } + + public String musicPutAndUpdate(String candidateName) { + createEntryForCandidate(candidateName); + + Map<String, Object> values = new HashMap<String, Object>(); + values.put("count", 5); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" + + candidateName; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .put(ClientResponse.class, jIns); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + return "musicPutAndUpdate:" + url; + } + + public String musicGet() { + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" + + userForGets; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + Map<String, Object> output = response.getEntity(Map.class); + return "musicGet:" + url; + } + + public String cassaQuorumPutAndUpdate(String candidateName) { + // http://135.197.226.98:8080/MUSIC/rest/formal/purecassa/keyspaces/shankarks/tables/employees/rows?emp_name=shankaruser1 + Map<String, Object> values = new HashMap<String, Object>(); + values.put("count", 5); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "atomic"); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicurl + "/purecassa/keyspaces/" + keyspaceName + + "/tables/votecount/rows?name=" + candidateName; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .put(ClientResponse.class, jIns); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + return "cassaQuorumPutAndUpdate:" + url; + + } + + public String cassaPutAndUpdate(String candidateName) { + // http://135.197.226.98:8080/MUSIC/rest/formal/purecassa/keyspaces/shankarks/tables/employees/rows?emp_name=shankaruser1 + long start = System.currentTimeMillis(); + createEntryForCandidate(candidateName); + + Map<String, Object> values = new HashMap<String, Object>(); + values.put("count", 5); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicurl + "/purecassa/keyspaces/" + keyspaceName + + "/tables/votecount/rows?name=" + candidateName; + WebResource webResource = client.resource(url); + long end = System.currentTimeMillis(); + String time = (end - start) + ""; + + start = System.currentTimeMillis(); + ClientResponse response = webResource.accept("application/json").type("application/json") + .put(ClientResponse.class, jIns); + end = System.currentTimeMillis(); + String time2 = (end - start) + ""; + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + return "cassaPutAndUpdate:" + url; + } + + public String cassaGet() { + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + String url = musicurl + "/keyspaces/" + keyspaceName + "/tables/votecount/rows?name=" + + userForGets; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + Map<String, Object> output = response.getEntity(Map.class); + return "cassaGet:" + url; + } + + private void zkCreate(String candidateName) { + // http://135.197.226.98:8080/MUSIC/rest/formal/purezk/shankarzknode + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + WebResource webResource = client.resource(musicurl + "/purezk/" + candidateName); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .post(ClientResponse.class); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + public String zkPutAndUpdate(String candidateName) { + // http://135.197.226.99:8080/MUSIC/rest/formal/purezk/shankarzknode + + // CREATE IT FIRST + zkCreate(candidateName); + + Map<String, Object> values = new HashMap<String, Object>(); + values.put("count", 5); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "atomic"); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicurl + "/purezk/" + candidateName; + System.out.println("in zk put:" + url); + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .put(ClientResponse.class, jIns); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + return "zkPutAndUpdate:" + url; + } + + public String zkGet() { + Client client = Client.create(); + String url = musicurl + "/purezk/" + userForGets; + System.out.println("in zk get:" + url); + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class); + + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + String output = response.getEntity(String.class); + return "zkGet:" + url; + } + + + public void bootStrap() { + // createVotingKeyspace(); + // createVotingTable(); + // createEntryForCandidate(userForGets); + // zkPutAndUpdate(userForGets); + } + + +} diff --git a/src/test/java/org/onap/music/e2eTests/MusicConnector.java b/src/test/java/org/onap/music/e2eTests/MusicConnector.java new file mode 100644 index 00000000..bb3d1f1b --- /dev/null +++ b/src/test/java/org/onap/music/e2eTests/MusicConnector.java @@ -0,0 +1,80 @@ +/* + * ============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.e2eTests; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Random; + +public class MusicConnector { + + // change this to point to relevant cluster + public String[] musicNodes; + + public MusicConnector(String[] musicNodes) { + this.musicNodes = musicNodes; + } + + private String getMusicNodeIp() { + Random r = new Random(); + int index = r.nextInt(musicNodes.length); + return musicNodes[index]; + } + + /* + * public static String toggle(String serverAddress){ if(serverAddress.equals(agaveMusicNode)){ + * System.out.println("Agave is down...connect to Big Site"); serverAddress = bigSiteMusicNode; + * }else if(serverAddress.equals(bigSiteMusicNode)){ + * System.out.println("Big Site is down...connect to Agave"); serverAddress = agaveMusicNode; } + * return serverAddress; } + */ + + public String getMusicNodeURL() { + String musicurl = "http://" + getMusicNodeIp() + ":8080/MUSIC/rest"; + System.out.println(musicurl); + return musicurl; + } + + public boolean isHostUp(String serverAddress) { + Boolean isUp = false; + try { + InetAddress inet = InetAddress.getByName(serverAddress); + isUp = inet.isReachable(1000); + } catch (UnknownHostException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return isUp; + } + + /* + * private static String getMusicNodeIp(){ + * + * //return "54.224.168.13"; return bigSiteMusicNode; String serverAddress; serverAddress = + * agaveMusicNode; while(isHostUp(serverAddress) != true) serverAddress = toggle(serverAddress); + * return serverAddress; } + */ +} diff --git a/src/test/java/org/onap/music/e2eTests/TestMusicE2E.java b/src/test/java/org/onap/music/e2eTests/TestMusicE2E.java new file mode 100644 index 00000000..25021e82 --- /dev/null +++ b/src/test/java/org/onap/music/e2eTests/TestMusicE2E.java @@ -0,0 +1,478 @@ +/* + * ============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.e2eTests; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import org.onap.music.datastore.jsonobjects.JsonDelete; +import org.onap.music.datastore.jsonobjects.JsonInsert; +import org.onap.music.datastore.jsonobjects.JsonKeySpace; +import org.onap.music.datastore.jsonobjects.JsonTable; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.json.JSONConfiguration; + +public class TestMusicE2E { + String keyspaceName; + ArrayList<String> lockNames; + MusicConnector musicHandle; + + public TestMusicE2E(String[] musicIps) { + lockNames = new ArrayList<String>(); + musicHandle = new MusicConnector(musicIps); + bootStrap(); + } + + public void createVotingKeyspace() { + keyspaceName = "VotingAppForMusic" + System.currentTimeMillis(); + Map<String, Object> replicationInfo = new HashMap<String, Object>(); + replicationInfo.put("class", "SimpleStrategy"); + replicationInfo.put("replication_factor", 1); + String durabilityOfWrites = "false"; + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + JsonKeySpace jsonKp = new JsonKeySpace(); + jsonKp.setConsistencyInfo(consistencyInfo); + jsonKp.setDurabilityOfWrites(durabilityOfWrites); + jsonKp.setReplicationInfo(replicationInfo); + + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + WebResource webResource = client + .resource(musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .post(ClientResponse.class, jsonKp); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + } + + public void createVotingTable() { + Map<String, String> fields = new HashMap<String, String>(); + fields.put("name", "text"); + fields.put("count", "varint"); + fields.put("PRIMARY KEY", "(name)"); + + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonTable jtab = new JsonTable(); + jtab.setFields(fields); + jtab.setConsistencyInfo(consistencyInfo); + + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName + + "/tables/votecount"; + System.out.println("create url:" + url); + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .post(ClientResponse.class, jtab); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + } + + private void checkMusicVersion() { + Client client = Client.create(); + System.out.println(musicHandle.getMusicNodeURL() + "/version"); + + + // System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + WebResource webResource = client.resource(musicHandle.getMusicNodeURL() + "/version"); + + + ClientResponse response = webResource.accept("text/plain").header("Connection", "close") + .get(ClientResponse.class); + + if (response.getStatus() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + String output = response.getEntity(String.class); + + // System.out.println("Output from Server .... \n"); + System.out.println(output); + + } + + private void createEntryForCandidate(String candidateName) { + Map<String, Object> values = new HashMap<String, Object>(); + values.put("name", candidateName); + values.put("count", 0); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName + + "/tables/votecount/rows"; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .post(ClientResponse.class, jIns); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:" + + url + " candidate name:" + candidateName); + + + } + + private String createLock(String lockName) { + Client client = Client.create(); + String msg = musicHandle.getMusicNodeURL() + "/locks/create/" + lockName; + WebResource webResource = client.resource(msg); + System.out.println(msg); + WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); + + ClientResponse response = wb.post(ClientResponse.class); + + if (response.getStatus() != 200) { + throw new RuntimeException( + "Failed : HTTP error code : " + response.getStatus() + "url:" + msg); + } + + String output = response.getEntity(String.class); + + // System.out.println("Server response .... \n"); + // System.out.println(output); + return output; + } + + private boolean acquireLock(String lockId) { + Client client = Client.create(); + String msg = musicHandle.getMusicNodeURL() + "/locks/acquire/" + lockId; + System.out.println(msg); + WebResource webResource = client.resource(msg); + + + WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); + + ClientResponse response = wb.get(ClientResponse.class); + + if (response.getStatus() != 200) { + throw new RuntimeException( + "Failed : HTTP error code : " + response.getStatus() + "url:" + msg); + } + + String output = response.getEntity(String.class); + Boolean status = Boolean.parseBoolean(output); + System.out.println("Server response .... \n"); + System.out.println(output); + return status; + } + + private void unlock(String lockId) { + Client client = Client.create(); + WebResource webResource = + client.resource(musicHandle.getMusicNodeURL() + "/locks/release/" + lockId); + + ClientResponse response = webResource.delete(ClientResponse.class); + + + if (response.getStatus() != 204) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + } + + private void updateVoteCountAtomically(String candidateName, int count) { + /* + * create lock for the candidate. The music API dictates that the lock name must be of the + * form keyspacename.tableName.primaryKeyName + */ + System.out.println("trying to acquire lock!"); + + String lockName = keyspaceName + ".votecount." + candidateName; + lockNames.add(lockName); + String lockId = createLock(lockName); + while (acquireLock(lockId) != true); + + System.out.println("acquired lock!"); + // update candidate entry if you have the lock + Map<String, Object> values = new HashMap<String, Object>(); + values.put("count", count); + + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "critical"); + consistencyInfo.put("lockId", lockId); + + JsonInsert jIns = new JsonInsert(); + jIns.setValues(values); + jIns.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName + + "/tables/votecount/rows?name=" + candidateName; + System.out.println(url); + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .put(ClientResponse.class, jIns); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException( + "Failed : HTTP error code : " + response.getStatus() + "url:" + url); + + // release lock now that the operation is done + unlock(lockId); + + } + + private void deleteCandidateEntryEventually(String candidateName) { + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonDelete jDel = new JsonDelete(); + jDel.setConsistencyInfo(consistencyInfo); + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName + + "/tables/votecount/rows?name=" + candidateName; + System.out.println(url); + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").type("application/json") + .delete(ClientResponse.class, jDel); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException( + "Failed : HTTP error code : " + response.getStatus() + "url:" + url); + + } + + public Map<String, Object> readVoteCountForCandidate(String candidateName) { + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName + + "/tables/votecount/rows?name=" + candidateName; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + Map<String, Object> output = response.getEntity(Map.class); + return output; + } + + public Map<String, Object> readAllVotes() { + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + String url = musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName + + "/tables/votecount/rows"; + WebResource webResource = client.resource(url); + + ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + + Map<String, Object> output = response.getEntity(Map.class); + return output; + } + + + /* + * Unable to use this because of the error: Exception in thread "main" + * com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: HTTP method + * DELETE doesn't support output. Seems to be a error in the rest java combination according to + * the interwebs + */ + private void dropKeySpace() { + Map<String, String> consistencyInfo = new HashMap<String, String>(); + consistencyInfo.put("type", "eventual"); + + JsonKeySpace jsonKp = new JsonKeySpace(); + jsonKp.setConsistencyInfo(consistencyInfo); + + ClientConfig clientConfig = new DefaultClientConfig(); + + clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + + Client client = Client.create(clientConfig); + + WebResource webResource = client + .resource(musicHandle.getMusicNodeURL() + "/keyspaces/" + keyspaceName); + + ClientResponse response = + webResource.type("application/json").delete(ClientResponse.class, jsonKp); + + if (response.getStatus() < 200 || response.getStatus() > 299) + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + private void deleteLock(String lockName) { + Client client = Client.create(); + WebResource webResource = client + .resource(musicHandle.getMusicNodeURL() + "/locks/delete/" + lockName); + + ClientResponse response = webResource.delete(ClientResponse.class); + + + if (response.getStatus() != 204) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + } + + private void resetMusic() { + Client client = Client.create(); + WebResource webResource = client.resource(musicHandle.getMusicNodeURL() + "/reset"); + + ClientResponse response = webResource.delete(ClientResponse.class); + + + if (response.getStatus() != 204) { + throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); + } + + } + + public void deleteAllLocks() { + for (String lockName : lockNames) { + deleteLock(lockName); + } + } + + + public void bootStrap() { + checkMusicVersion(); + createVotingKeyspace(); + + + createVotingTable(); + + + // the next few lines just create an entry in the voting table for all these candidates with + // vote count as 0 + createEntryForCandidate("Popeye"); + + createEntryForCandidate("Judy"); + + createEntryForCandidate("Flash"); + + createEntryForCandidate("Mickey"); + + } + + public void overAllTests() { + // update the count atomically + updateVoteCountAtomically("Popeye", 5); + + updateVoteCountAtomically("Judy", 7); + + updateVoteCountAtomically("Mickey", 8); + + updateVoteCountAtomically("Flash", 2); + + + // read votecount + System.out.println(readAllVotes()); + + System.out.println(readVoteCountForCandidate("Popeye")); + + System.out.println(readVoteCountForCandidate("Flash")); + + deleteCandidateEntryEventually("Mickey"); + + System.out.println(readAllVotes()); + + dropKeySpace(); + + deleteAllLocks(); + } + + public void flipTest() { + checkMusicVersion(); + } + + public static String executeBashScript(String pathToScript, String arg1, String arg2) { + try { + ProcessBuilder pb = new ProcessBuilder(pathToScript, arg1, arg2); + final Process process = pb.start(); + InputStream is = process.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + return br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public static void main(String[] args) { + long start = System.currentTimeMillis(); + for (int i = 0; i < 2; ++i) { + TestMusicE2E vHandle = new TestMusicE2E(args); + vHandle.overAllTests(); + + System.out.println("====================================="); + System.out.println("Test no." + i + " completed:"); + } + long diff = System.currentTimeMillis() - start; + System.out.println(diff); + } + + +} diff --git a/src/test/java/org/onap/music/unittests/CassandraCQL.java b/src/test/java/org/onap/music/unittests/CassandraCQL.java new file mode 100644 index 00000000..0d2a606d --- /dev/null +++ b/src/test/java/org/onap/music/unittests/CassandraCQL.java @@ -0,0 +1,252 @@ +/* + * ============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; +/** + * @author srupane + * + */ + +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.PreparedQueryObject; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.exceptions.NoHostAvailableException; + +public class CassandraCQL { + + public static final String createKeySpace = + "CREATE KEYSPACE IF NOT EXISTS testCassa WITH replication = {'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;"; + + public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testCassa"; + + public static final String createTableEmployees = + "CREATE TABLE IF NOT EXISTS testCassa.employees " + + "(vector_ts text,emp_id uuid,emp_name text,emp_salary varint,address Map<text,text>,PRIMARY KEY (emp_name)) " + + "WITH comment='Financial Info of employees' " + + "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} " + + "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};"; + + public static final String insertIntoTablePrepared1 = + "INSERT INTO testCassa.employees (vector_ts,emp_id,emp_name,emp_salary) VALUES (?,?,?,?); "; + + public static final String insertIntoTablePrepared2 = + "INSERT INTO testCassa.employees (vector_ts,emp_id,emp_name,emp_salary,address) VALUES (?,?,?,?,?);"; + + public static final String selectALL = "SELECT * FROM testCassa.employees;"; + + public static final String selectSpecific = + "SELECT * FROM testCassa.employees WHERE emp_name= ?;"; + + public static final String updatePreparedQuery = + "UPDATE testCassa.employees SET vector_ts=?,address= ? WHERE emp_name= ?;"; + + public static final String deleteFromTable = " "; + + public static final String deleteFromTablePrepared = " "; + + // Set Values for Prepared Query + + public static List<Object> setPreparedInsertValues1() { + + List<Object> preppreparedInsertValues1 = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + UUID emp_id = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6"); + BigInteger emp_salary = BigInteger.valueOf(23443); + String emp_name = "Mr Test one"; + preppreparedInsertValues1.add(vectorTs); + preppreparedInsertValues1.add(emp_id); + preppreparedInsertValues1.add(emp_name); + preppreparedInsertValues1.add(emp_salary); + return preppreparedInsertValues1; + } + + public static List<Object> setPreparedInsertValues2() { + + List<Object> preparedInsertValues2 = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + UUID emp_id = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6"); + BigInteger emp_salary = BigInteger.valueOf(45655); + String emp_name = "Mr Test two"; + Map<String, String> address = new HashMap<>(); + preparedInsertValues2.add(vectorTs); + preparedInsertValues2.add(emp_id); + preparedInsertValues2.add(emp_name); + preparedInsertValues2.add(emp_salary); + address.put("Street", "1 att way"); + address.put("City", "Bedmister"); + preparedInsertValues2.add(address); + return preparedInsertValues2; + } + + public static List<Object> setPreparedUpdateValues() { + + List<Object> preparedUpdateValues = new ArrayList<>(); + String vectorTs = + String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis()); + Map<String, String> address = new HashMap<>(); + preparedUpdateValues.add(vectorTs); + String emp_name = "Mr Test one"; + address.put("Street", "101 Att Way"); + address.put("City", "Bedmister"); + preparedUpdateValues.add(address); + preparedUpdateValues.add(emp_name); + return preparedUpdateValues; + } + + // Generate Different Prepared Query Objects + /** + * Query Object for Get + * + * @return + */ + public static PreparedQueryObject setPreparedGetQuery() { + + PreparedQueryObject queryObject = new PreparedQueryObject(); + String emp_name1 = "Mr Test one"; + queryObject.appendQueryString(selectSpecific); + queryObject.addValue(emp_name1); + return queryObject; + } + + /** + * Query Object 1 for Insert + * + * @return + */ + public static PreparedQueryObject setPreparedInsertQueryObject1() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(insertIntoTablePrepared1); + List<Object> values = setPreparedInsertValues1(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + /** + * Query Object 2 for Insert + * + * @return + */ + public static PreparedQueryObject setPreparedInsertQueryObject2() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(insertIntoTablePrepared2); + List<Object> values = setPreparedInsertValues2(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + /** + * Query Object for Update + * + * @return + */ + public static PreparedQueryObject setPreparedUpdateQueryObject() { + + PreparedQueryObject queryobject = new PreparedQueryObject(); + queryobject.appendQueryString(updatePreparedQuery); + List<Object> values = setPreparedUpdateValues(); + if (!values.isEmpty() || values != null) { + for (Object o : values) { + queryobject.addValue(o); + } + } + return queryobject; + + } + + private static ArrayList<String> getAllPossibleLocalIps() { + ArrayList<String> allPossibleIps = new ArrayList<String>(); + try { + Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); + while (en.hasMoreElements()) { + NetworkInterface ni = (NetworkInterface) en.nextElement(); + Enumeration<InetAddress> ee = ni.getInetAddresses(); + while (ee.hasMoreElements()) { + InetAddress ia = (InetAddress) ee.nextElement(); + allPossibleIps.add(ia.getHostAddress()); + } + } + } catch (SocketException e) { + System.out.println(e.getMessage()); + } + return allPossibleIps; + } + + public static MusicDataStore connectToEmbeddedCassandra() { + Iterator<String> it = getAllPossibleLocalIps().iterator(); + String address = "localhost"; + + Cluster cluster = null; + Session session = null; + while (it.hasNext()) { + try { + + try { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(60000); + } catch (ConfigurationException | TTransportException | IOException e) { + + System.out.println(e.getMessage()); + } + + cluster = new Cluster.Builder().addContactPoint(address).withPort(9142).build(); + session = cluster.connect(); + + break; + } catch (NoHostAvailableException e) { + address = it.next(); + System.out.println(e.getMessage()); + + } + } + return new MusicDataStore(cluster, session); + + } + +} diff --git a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java new file mode 100644 index 00000000..520a5fe4 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java @@ -0,0 +1,146 @@ +/* + * ============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; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.mockito.Mock; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; + +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.PreparedQueryObject; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class MusicDataStoreTest { + + static MusicDataStore dataStore; + static PreparedQueryObject testObject; + + @BeforeClass + public static void init() { + dataStore = CassandraCQL.connectToEmbeddedCassandra(); + + } + + @AfterClass + public static void close() throws MusicServiceException, MusicQueryException { + + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.dropKeyspace); + dataStore.executePut(testObject, "eventual"); + dataStore.close(); + + } + + @Test + public void Test1_SetUp() throws MusicServiceException, MusicQueryException { + boolean result = false; + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createKeySpace); + result = dataStore.executePut(testObject, "eventual");; + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.createTableEmployees); + result = dataStore.executePut(testObject, "eventual"); + assertEquals(true, result); + + } + + @Test + public void Test2_ExecutePut_eventual_insert() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedInsertQueryObject1(); + boolean result = dataStore.executePut(testObject, "eventual"); + assertEquals(true, result); + } + + @Test + public void Test3_ExecutePut_critical_insert() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedInsertQueryObject2(); + boolean result = dataStore.executePut(testObject, "Critical"); + assertEquals(true, result); + } + + @Test + public void Test4_ExecutePut_eventual_update() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedUpdateQueryObject(); + boolean result = false; + result = dataStore.executePut(testObject, "eventual"); + assertEquals(true, result); + } + + @Test + public void Test5_ExecuteEventualGet() throws MusicServiceException, MusicQueryException { + testObject = new PreparedQueryObject(); + testObject.appendQueryString(CassandraCQL.selectALL); + boolean result = false; + int count = 0; + ResultSet output = null; + output = dataStore.executeEventualGet(testObject); + System.out.println(output); + ; + for (Row row : output) { + count++; + System.out.println(row.toString()); + } + if (count == 2) { + result = true; + } + assertEquals(true, result); + } + + @Test + public void Test6_ExecuteCriticalGet() throws MusicServiceException, MusicQueryException { + testObject = CassandraCQL.setPreparedGetQuery(); + boolean result = false; + int count = 0; + ResultSet output = null; + output = dataStore.executeCriticalGet(testObject); + System.out.println(output); + ; + for (Row row : output) { + count++; + System.out.println(row.toString()); + } + if (count == 1) { + result = true; + } + assertEquals(true, result); + } + + @Test(expected = NullPointerException.class) + public void Test7_exception() { + PreparedQueryObject queryObject = null; + try { + dataStore.executePut(queryObject, "critical"); + } catch (MusicQueryException | MusicServiceException e) { + System.out.println(e.getMessage()); + } + + } +} diff --git a/src/test/java/org/onap/music/unittests/TestLockStore.java b/src/test/java/org/onap/music/unittests/TestLockStore.java new file mode 100644 index 00000000..4dbc7b4f --- /dev/null +++ b/src/test/java/org/onap/music/unittests/TestLockStore.java @@ -0,0 +1,53 @@ +/* + * ============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; + +import org.apache.log4j.Logger; +import org.onap.music.lockingservice.MusicLockingService; + +public class TestLockStore { + final static Logger logger = Logger.getLogger(TestLockStore.class); + + public static void main(String[] args) throws Exception { + String lockName = "/achristmkllas"; + MusicLockingService ml = new MusicLockingService(); + ml.deleteLock(lockName); + + + logger.info("lockname:" + lockName); + + String lockId1 = ml.createLockId(lockName); + logger.info("lockId1 " + lockId1); + logger.info(ml.isMyTurn(lockId1)); + + String lockId2 = ml.createLockId(lockName); + logger.info("lockId2 " + lockId2); + logger.info("check " + ml.isMyTurn("$bank$x-94608776321630264-0000000000")); + logger.info(ml.isMyTurn(lockId2)); + + // zkClient.unlock(lockId1); + // logger.info(ml.lock(lockId2)); + // zkClient.unlock(lockId2); + } + + +} diff --git a/src/test/java/org/onap/music/unittests/TestMusicCore.java b/src/test/java/org/onap/music/unittests/TestMusicCore.java new file mode 100644 index 00000000..17f911ce --- /dev/null +++ b/src/test/java/org/onap/music/unittests/TestMusicCore.java @@ -0,0 +1,445 @@ +/* + * ============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; + +import static org.junit.Assert.*; +import static org.onap.music.main.MusicCore.mDstoreHandle; +import static org.onap.music.main.MusicCore.mLockHandle; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.lockingservice.MusicLockState; +import org.onap.music.lockingservice.MusicLockingService; +import org.onap.music.lockingservice.MusicLockState.LockStatus; +import org.onap.music.main.MusicCore; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.music.main.MusicCore.Condition; +import org.onap.music.datastore.MusicDataStore; +import org.onap.music.datastore.PreparedQueryObject; +import com.datastax.driver.core.ResultSet; + +@RunWith(MockitoJUnitRunner.class) +public class TestMusicCore { + + @Mock + private Condition condition; + + @Mock + private ResultSet rs; + + @Mock + private PreparedQueryObject preparedQueryObject; + + @Before + public void setUp() { + mLockHandle = Mockito.mock(MusicLockingService.class); + + } + + @Test + public void testCreateLockReferenceforvalidlock() { + Mockito.when(mLockHandle.createLockId("/" + "test")).thenReturn("lock"); + String lockId = MusicCore.createLockReference("test"); + assertEquals("lock", lockId); + Mockito.verify(mLockHandle).createLockId("/" + "test"); + } + + @Test + public void testIsTableOrKeySpaceLock() { + Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1"); + assertTrue(result); + } + + @Test + public void testIsTableOrKeySpaceLockwithPrimarykey() { + Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1.pk1"); + assertFalse(result); + } + + @Test + public void testGetMusicLockState() { + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); + Mockito.when(mLockHandle.getLockState("ks1.tb1.pk1")).thenReturn(musicLockState); + MusicLockState mls = MusicCore.getMusicLockState("ks1.tb1.pk1"); + assertEquals(musicLockState, mls); + Mockito.verify(mLockHandle).getLockState("ks1.tb1.pk1"); + } + + @Test + public void testAcquireLockifisMyTurnTrue() { + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + Boolean lock = MusicCore.acquireLock("ks1.tn1", "id1"); + assertTrue(lock); + Mockito.verify(mLockHandle).isMyTurn("id1"); + } + + @Test + public void testAcquireLockifisMyTurnFalse() { + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); + Boolean lock = MusicCore.acquireLock("ks1.ts1", "id1"); + assertFalse(lock); + Mockito.verify(mLockHandle).isMyTurn("id1"); + } + + @Test + public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockTrue() { + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + Boolean lock = MusicCore.acquireLock("ks1.tn1", "id1"); + assertTrue(lock); + Mockito.verify(mLockHandle).isMyTurn("id1"); + } + + @Test + public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandHaveLock() { + MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Boolean lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); + assertTrue(lock); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); + } + + @Test + public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandDontHaveLock() { + MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id2"); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Boolean lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1"); + assertTrue(lock); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); + } + + @Test + public void testAcquireLockWithLeasewithLockStatusLOCKED() { + MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); + ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); + assertEquals(expectedResult.getResult(), actualResult.getResult()); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); + } + + @Test + public void testAcquireLockWithLeasewithLockStatusUNLOCKED() { + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); + ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); + assertEquals(expectedResult.getResult(), actualResult.getResult()); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); + + } + + @Test + public void testAcquireLockWithLeaseIfNotMyTurn() { + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); + ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); + ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000); + assertEquals(expectedResult.getResult(), actualResult.getResult()); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1"); + } + + /* + * @Test public void testQuorumGet() { mDstoreHandle = Mockito.mock(MusicDataStore.class); rs = + * Mockito.mock(ResultSet.class); + * Mockito.when(mDstoreHandle.executeCriticalGet("qu1")).thenReturn(rs); ResultSet rs1 = + * MusicCore.quorumGet("qu1"); assertNotNull(rs1); + * Mockito.verify(mDstoreHandle).executeCriticalGet("qu1"); + * + * } + */ + + @Test + public void testGetLockNameFromId() { + String lockname = MusicCore.getLockNameFromId("lockName$id"); + assertEquals("lockName", lockname); + } + + @Test + public void testDestroyLockRef() { + Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); + MusicCore.destroyLockRef("id1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); + } + + @Test + public void testreleaseLockwithvoluntaryReleaseTrue() { + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); + Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); + MusicLockState musicLockState1 = MusicCore.releaseLock("id1", true); + assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus()); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); + } + + @Test + public void testreleaseLockwithvoluntaryReleaseFalse() { + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); + Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1"); + MusicLockState musicLockState1 = MusicCore.releaseLock("id1", false); + assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus()); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1"); + } + + @Test + public void testDeleteLock() { + Mockito.doNothing().when(mLockHandle).deleteLock("/" + "id1"); + MusicCore.deleteLock("id1"); + Mockito.verify(mLockHandle).deleteLock("/" + "id1"); + } + + /* + * @Test public void testNonKeyRelatedPut() throws Exception { mDstoreHandle = + * Mockito.mock(MusicDataStore.class); Mockito.when(mDstoreHandle.executePut("qu1", + * "consistency")).thenReturn(true); Boolean result = MusicCore.nonKeyRelatedPut("qu1", + * "consistency"); assertTrue(result); Mockito.verify(mDstoreHandle).executePut("qu1", + * "consistency"); } + */ + + @Test + public void testEventualPutPreparedQuery() throws MusicServiceException, MusicQueryException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); + Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(true); + ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject); + assertEquals(expectedResult.getResult(), actualResult.getResult()); + Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual"); + } + + @Test + public void testEventualPutPreparedQuerywithResultFalse() + throws MusicServiceException, MusicQueryException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); + Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(false); + ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject); + assertEquals(expectedResult.getResult(), actualResult.getResult()); + Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual"); + } + + @Test + public void testCriticalPutPreparedQuerywithValidLockId() + throws MusicServiceException, MusicQueryException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); + Mockito.when(condition.testCondition()).thenReturn(true); + ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true); + ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, + "id1", condition); + assertEquals(expectedResult.getResult(), returnType.getResult()); + Mockito.verify(condition).testCondition(); + Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); + Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical"); + } + + @Test + public void testCriticalPutPreparedQuerywithInvalidLockId() { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); + ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, + "id1", condition); + assertEquals(expectedResult.getResult(), returnType.getResult()); + Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); + } + + @Test + public void testCriticalPutPreparedQuerywithvalidLockIdandTestConditionFalse() { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); + Mockito.when(condition.testCondition()).thenReturn(false); + ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject, + "id1", condition); + assertEquals(expectedResult.getResult(), returnType.getResult()); + Mockito.verify(condition).testCondition(); + Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1"); + } + + @Test + public void testNonKeyRelatedPutPreparedQuery() throws Exception { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "consistency")).thenReturn(true); + Boolean result = MusicCore.nonKeyRelatedPut(preparedQueryObject, "consistency"); + assertTrue(result); + Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "consistency"); + } + + @Test + public void testAtomicPutPreparedQuery() throws MusicServiceException, MusicQueryException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); + MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); + ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes"); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + Mockito.when(condition.testCondition()).thenReturn(true); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true); + ReturnType returnType = + MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition); + assertEquals(expectedResult.getResult(), returnType.getResult()); + Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(condition).testCondition(); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()) + .getLockState("ks1" + "." + "tn1" + "." + "pk1"); + Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical"); + } + + @Test + public void testAtomicPutPreparedQuerywithAcquireLockWithLeaseFalse() { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); + MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); + ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure"); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + ReturnType returnType = + MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition); + assertEquals(expectedResult.getResult(), returnType.getResult()); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()) + .getLockState("ks1" + "." + "tn1" + "." + "pk1"); + Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); + } + + @Test + public void testAtomicGetPreparedQuery() throws MusicServiceException, MusicQueryException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + rs = Mockito.mock(ResultSet.class); + Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); + MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs); + ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject); + assertNotNull(rs1); + Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()) + .getLockState("ks1" + "." + "tn1" + "." + "pk1"); + Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject); + } + + @Test + public void testAtomicGetPreparedQuerywithAcquireLockWithLeaseFalse() + throws MusicServiceException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + rs = Mockito.mock(ResultSet.class); + Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1"); + MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1"); + Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState); + Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject); + assertNull(rs1); + Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1"); + Mockito.verify(mLockHandle).isMyTurn("id1"); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()) + .getLockState("ks1" + "." + "tn1" + "." + "pk1"); + + } + + @Test + public void testGetPreparedQuery() throws MusicServiceException, MusicQueryException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + rs = Mockito.mock(ResultSet.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + Mockito.when(mDstoreHandle.executeEventualGet(preparedQueryObject)).thenReturn(rs); + ResultSet rs1 = MusicCore.get(preparedQueryObject); + assertNotNull(rs1); + Mockito.verify(mDstoreHandle).executeEventualGet(preparedQueryObject); + + } + + @Test + public void testcriticalGetPreparedQuery() throws MusicServiceException, MusicQueryException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1"); + rs = Mockito.mock(ResultSet.class); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs); + ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1"); + assertNotNull(rs1); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()) + .getLockState("ks1" + "." + "tn1" + "." + "pk1"); + Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject); + } + + @Test + public void testcriticalGetPreparedQuerywithInvalidLockId() throws MusicServiceException { + mDstoreHandle = Mockito.mock(MusicDataStore.class); + preparedQueryObject = Mockito.mock(PreparedQueryObject.class); + MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2"); + Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1")) + .thenReturn(musicLockState); + ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1"); + assertNull(rs1); + Mockito.verify(mLockHandle, Mockito.atLeastOnce()) + .getLockState("ks1" + "." + "tn1" + "." + "pk1"); + } + +} |