Skip to content

Commit

Permalink
FAB-4596 Improve code coverage
Browse files Browse the repository at this point in the history
Improve code coverage for the fabric-sdk-java code base

Change-Id: If9e62ee86315b70acfd0bbd8ab845b1775c71386
Signed-off-by: rickr <cr22rc@gmail.com>
  • Loading branch information
cr22rc committed Jun 15, 2017
1 parent 18b2e13 commit dc6c72c
Show file tree
Hide file tree
Showing 3 changed files with 221 additions and 44 deletions.
33 changes: 22 additions & 11 deletions src/main/java/org/hyperledger/fabric/sdk/Channel.java
Original file line number Diff line number Diff line change
Expand Up @@ -1710,6 +1710,10 @@ Set<String> queryChannels(Peer peer) throws InvalidArgumentException, ProposalEx
}

ProposalResponse proposalResponse = proposalResponses.iterator().next();
if (proposalResponse.getStatus() != ChaincodeResponse.Status.SUCCESS) {
throw new ProposalException(format("Failed exception message is %s, status is %d", proposalResponse.getMessage(), proposalResponse.getStatus().getStatus()));

}

FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse();
if (null == fabricResponse) {
Expand Down Expand Up @@ -1977,44 +1981,51 @@ private Pair(Peer peer, Future<FabricProposalResponse.ProposalResponse> future)
for (Peer peer : peers) {
logger.debug(format("Channel %s send proposal to peer %s at url %s",
name, peer.getName(), peer.getUrl()));
peerFuturePairs.add(new Pair(peer, peer.sendProposalAsync(signedProposal)));
Future<FabricProposalResponse.ProposalResponse> proposalResponseListenableFuture;
try {
proposalResponseListenableFuture = peer.sendProposalAsync(signedProposal);
} catch (Exception e) {
proposalResponseListenableFuture = new CompletableFuture<>();
((CompletableFuture) proposalResponseListenableFuture).completeExceptionally(e);

}
peerFuturePairs.add(new Pair(peer, proposalResponseListenableFuture));

}

Collection<ProposalResponse> proposalResponses = new ArrayList<>();
for (Pair peerFuturePair : peerFuturePairs) {

FabricProposalResponse.ProposalResponse fabricResponse = null;
String message;
int status;
int status = 500;
final String peerName = peerFuturePair.peer.getName();
try {
fabricResponse = peerFuturePair.future.get(transactionContext.getProposalWaitTime(), TimeUnit.MILLISECONDS);
message = fabricResponse.getResponse().getMessage();
status = fabricResponse.getResponse().getStatus();
logger.debug(format("Channel %s got back from peer %s status: %d, message: %s",
name, peerFuturePair.peer.getName(), status, message));
name, peerName, status, message));
} catch (InterruptedException e) {
message = "Sending proposal to " + peerFuturePair.peer.getName() + " failed because of interruption";
status = 500;
message = "Sending proposal to " + peerName + " failed because of interruption";
logger.error(message, e);
} catch (TimeoutException e) {
message = format("Sending proposal to " + peerFuturePair.peer.getName() + " failed because of timeout(%d milliseconds) expiration",
message = format("Sending proposal to " + peerName + " failed because of timeout(%d milliseconds) expiration",
transactionContext.getProposalWaitTime());
status = 500;
logger.error(message, e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof Error) {
String emsg = "Sending proposal to " + peerFuturePair.peer.getName() + " failed because of " + cause.getMessage();
String emsg = "Sending proposal to " + peerName + " failed because of " + cause.getMessage();
logger.error(emsg, new Exception(cause)); //wrapped in exception to get full stack trace.
throw (Error) cause;
} else {
if (cause instanceof StatusRuntimeException) {
message = format("Sending proposal to " + peerFuturePair.peer.getName() + " failed because of gRPC failure=%s",
message = format("Sending proposal to " + peerName + " failed because of: gRPC failure=%s",
((StatusRuntimeException) cause).getStatus());
} else {
message = format("Sending proposal to " + peerFuturePair.peer.getName() + " failed because of %s", cause.getMessage());
message = format("Sending proposal to " + peerName + " failed because of: %s", cause.getMessage());
}
status = 500;
logger.error(message, new Exception(cause)); //wrapped in exception to get full stack trace.
}
}
Expand Down
146 changes: 144 additions & 2 deletions src/test/java/org/hyperledger/fabric/sdk/ChannelTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,40 @@

package org.hyperledger.fabric.sdk;

//Allow throwing undeclared checked execeptions in mock code.
//CHECKSTYLE.OFF: IllegalImport

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.orderer.Ab;
import org.hyperledger.fabric.protos.peer.FabricProposal;
import org.hyperledger.fabric.protos.peer.FabricProposalResponse;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.PeerException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import sun.misc.Unsafe;

import static org.hyperledger.fabric.sdk.testutils.TestUtils.setField;

//CHECKSTYLE.ON: IllegalImport




public class ChannelTest {
private static HFClient hfclient = null;
private static Channel shutdownChannel = null;
Expand Down Expand Up @@ -258,7 +275,6 @@ protected void parseConfigBlock() {

@Test
public void testChannelShutdown() {
Channel testChannel = null;

try {

Expand All @@ -267,7 +283,7 @@ public void testChannelShutdown() {
} catch (Exception e) {

Assert.assertTrue(e.getClass() == InvalidArgumentException.class);
Assert.assertTrue(testChannel.isInitialized());
Assert.assertTrue(shutdownChannel.isInitialized());
}

}
Expand Down Expand Up @@ -605,4 +621,130 @@ public void testChannelQueryTransactionByIDNull() throws Exception {

}

@Test
public void testQueryInstalledChaincodesThrowInterrupted() throws Exception {

thrown.expect(ProposalException.class);
thrown.expectMessage("You interrupting me?");

final Channel channel = createRunningChannel(null);
Peer peer = channel.getPeers().iterator().next();

setField(peer, "endorserClent", new MockEndorserClient(new InterruptedException("You interrupting me?")));

hfclient.queryChannels(peer);

}

@Test
public void testQueryInstalledChaincodesThrowPeerException() throws Exception {

thrown.expect(ProposalException.class);
thrown.expectMessage("rick did this:)");

final Channel channel = createRunningChannel(null);
Peer peer = channel.getPeers().iterator().next();

setField(peer, "endorserClent", new MockEndorserClient(new PeerException("rick did this:)")));

hfclient.queryChannels(peer);

}

@Test
public void testQueryInstalledChaincodesThrowTimeoutException() throws Exception {

thrown.expect(ProposalException.class);
thrown.expectMessage("What time is it?");

final Channel channel = createRunningChannel(null);
Peer peer = channel.getPeers().iterator().next();

setField(peer, "endorserClent", new MockEndorserClient(new PeerException("What time is it?")));

hfclient.queryChannels(peer);

}

@Test
public void testQueryInstalledChaincodesERROR() throws Exception {

thrown.expect(Error.class);
thrown.expectMessage("Error bad bad bad");

final Channel channel = createRunningChannel(null);
Peer peer = channel.getPeers().iterator().next();

final SettableFuture<FabricProposalResponse.ProposalResponse> settableFuture = SettableFuture.create();
settableFuture.setException(new Error("Error bad bad bad"));
setField(peer, "endorserClent", new MockEndorserClient(settableFuture));

hfclient.queryChannels(peer);

}

@Test
public void testQueryInstalledChaincodesStatusRuntimeException() throws Exception {

thrown.expect(ProposalException.class);
thrown.expectMessage("ABORTED");

final Channel channel = createRunningChannel(null);
Peer peer = channel.getPeers().iterator().next();

final SettableFuture<FabricProposalResponse.ProposalResponse> settableFuture = SettableFuture.create();
settableFuture.setException(new StatusRuntimeException(Status.ABORTED));
setField(peer, "endorserClent", new MockEndorserClient(settableFuture));

hfclient.queryChannels(peer);

}

class MockEndorserClient extends EndorserClient {
final Throwable throwThis;
private final ListenableFuture<FabricProposalResponse.ProposalResponse> returnedFuture;

MockEndorserClient(Throwable throwThis) {
super(new Endpoint("grpc://loclhost:99", null).getChannelBuilder());
if (throwThis == null) {
throw new IllegalArgumentException("Can't throw a null!");
}
this.throwThis = throwThis;
this.returnedFuture = null;
}

MockEndorserClient(ListenableFuture<FabricProposalResponse.ProposalResponse> returnedFuture) {
super(new Endpoint("grpc://loclhost:99", null).getChannelBuilder());
this.throwThis = null;
this.returnedFuture = returnedFuture;
}

@Override
public ListenableFuture<FabricProposalResponse.ProposalResponse> sendProposalAsync(FabricProposal.SignedProposal proposal) throws PeerException {
if (throwThis != null) {
getUnsafe().throwException(throwThis);
}
return returnedFuture;

}

@Override
public boolean isChannelActive() {

return true;

}

private Unsafe getUnsafe() { //lets us throw undeclared exceptions.
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
return (Unsafe) field.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}


}
86 changes: 55 additions & 31 deletions src/test/java/org/hyperledger/fabric/sdk/TestHFClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@
package org.hyperledger.fabric.sdk;

import java.io.File;
import java.security.PrivateKey;

import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdkintegration.SampleStore;
import org.hyperledger.fabric.sdkintegration.SampleUser;

import static java.lang.String.format;

public class TestHFClient {

final File tempFile;
Expand All @@ -43,41 +44,46 @@ public static HFClient newInstance() throws Exception {
}
final SampleStore sampleStore = new SampleStore(sampleStoreFile);

SampleUser someTestUSER = sampleStore.getMember("someTestUSER", "someTestORG");
//src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/

//SampleUser someTestUSER = sampleStore.getMember("someTestUSER", "someTestORG");
SampleUser someTestUSER = sampleStore.getMember("someTestUSER", "someTestORG", "mspid",
findFileSk("src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore"),
new File("src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem"));
someTestUSER.setMspId("testMSPID?");

HFClient hfclient = HFClient.createNewInstance();
hfclient.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

someTestUSER.setEnrollment(new Enrollment() {
@Override
public PrivateKey getKey() {
return new PrivateKey() {
private static final long serialVersionUID = -7506317638561401152L;

@Override
public String getAlgorithm() {
return "algorithm?";
}

@Override
public String getFormat() {
return "format?";
}

@Override
public byte[] getEncoded() {
return new byte[0];
}
};
}

@Override
public String getCert() {
return "fakecert?";
}

});
// someTestUSER.setEnrollment(new Enrollment() {
// @Override
// public PrivateKey getKey() {
// return new PrivateKey() {
// private static final long serialVersionUID = -7506317638561401152L;
//
// @Override
// public String getAlgorithm() {
// return "algorithm?";
// }
//
// @Override
// public String getFormat() {
// return "format?";
// }
//
// @Override
// public byte[] getEncoded() {
// return new byte[0];
// }
// };
// }
//
// @Override
// public String getCert() {
// return "fakecert?";
// }
//
// });
hfclient.setUserContext(someTestUSER);


Expand All @@ -87,6 +93,24 @@ public String getCert() {

}

static File findFileSk(String directorys) {

File directory = new File(directorys);

File[] matches = directory.listFiles((dir, name) -> name.endsWith("_sk"));

if (null == matches) {
throw new RuntimeException(format("Matches returned null does %s directory exist?", directory.getAbsoluteFile().getName()));
}

if (matches.length != 1) {
throw new RuntimeException(format("Expected in %s only 1 sk file but found %d", directory.getAbsoluteFile().getName(), matches.length));
}

return matches[0];

}

@Override
protected void finalize() throws Throwable {
super.finalize();
Expand Down

0 comments on commit dc6c72c

Please sign in to comment.