Skip to content

Commit

Permalink
[FAB-8985] client,common,fabsdk/... metalinter
Browse files Browse the repository at this point in the history
This change resolves the metalinter warnings except for:
* cyclomatic complexity
* err shadows declartion

Change-Id: Ia4d64a5add3809c2de04862f623f1e71a961d84e
Signed-off-by: Troy Ronda <[email protected]>
  • Loading branch information
troyronda committed Mar 20, 2018
1 parent 5d5b7e2 commit e3276ec
Show file tree
Hide file tree
Showing 35 changed files with 130 additions and 229 deletions.
30 changes: 23 additions & 7 deletions pkg/client/channel/chclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,20 +73,33 @@ func New(channelProvider context.ChannelProvider, opts ...ClientOption) (*Client
}

for _, param := range opts {
param(&channelClient)
err := param(&channelClient)
if err != nil {
return nil, errors.WithMessage(err, "option failed")
}
}

return &channelClient, nil
}

// Query chaincode using request and optional options provided
func (cc *Client) Query(request Request, options ...RequestOption) (Response, error) {
return cc.InvokeHandler(invoke.NewQueryHandler(), request, cc.addDefaultTimeout(cc.context, core.Query, options...)...)
optsWithTimeout, err := cc.addDefaultTimeout(cc.context, core.Query, options...)
if err != nil {
return Response{}, errors.WithMessage(err, "option failed")
}

return cc.InvokeHandler(invoke.NewQueryHandler(), request, optsWithTimeout...)
}

// Execute prepares and executes transaction using request and optional options provided
func (cc *Client) Execute(request Request, options ...RequestOption) (Response, error) {
return cc.InvokeHandler(invoke.NewExecuteHandler(), request, cc.addDefaultTimeout(cc.context, core.Execute, options...)...)
optsWithTimeout, err := cc.addDefaultTimeout(cc.context, core.Execute, options...)
if err != nil {
return Response{}, errors.WithMessage(err, "option failed")
}

return cc.InvokeHandler(invoke.NewExecuteHandler(), request, optsWithTimeout...)
}

//InvokeHandler invokes handler using request and options provided
Expand Down Expand Up @@ -226,17 +239,20 @@ func (cc *Client) prepareOptsFromOptions(ctx context.Client, options ...RequestO
}

//addDefaultTimeout adds given default timeout if it is missing in options
func (cc *Client) addDefaultTimeout(ctx context.Client, timeOutType core.TimeoutType, options ...RequestOption) []RequestOption {
func (cc *Client) addDefaultTimeout(ctx context.Client, timeOutType core.TimeoutType, options ...RequestOption) ([]RequestOption, error) {
txnOpts := requestOptions{}
for _, option := range options {
option(ctx, &txnOpts)
err := option(ctx, &txnOpts)
if err != nil {
return nil, errors.WithMessage(err, "option failed")
}
}

if txnOpts.Timeouts[timeOutType] == 0 {
//InvokeHandler relies on Execute timeout
return append(options, WithTimeout(core.Execute, cc.context.Config().TimeoutOrDefault(timeOutType)))
return append(options, WithTimeout(core.Execute, cc.context.Config().TimeoutOrDefault(timeOutType))), nil
}
return options
return options, nil
}

// RegisterChaincodeEvent registers chain code event
Expand Down
2 changes: 1 addition & 1 deletion pkg/client/channel/chclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ func TestTransactionValidationError(t *testing.T) {
case txStatusReg := <-mockEventService.TxStatusRegCh:
txStatusReg.Eventch <- &fab.TxStatusEvent{TxID: txStatusReg.TxID, TxValidationCode: validationCode}
case <-time.After(time.Second * 5):
t.Fatal("Timed out waiting for execute Tx to register event callback")
panic("Timed out waiting for execute Tx to register event callback")
}
}()

Expand Down
7 changes: 2 additions & 5 deletions pkg/client/channel/invoke/txnhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@ import (
"github.com/pkg/errors"

selectopts "github.com/hyperledger/fabric-sdk-go/pkg/client/common/selection/options"
"github.com/hyperledger/fabric-sdk-go/pkg/common/logging"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
"github.com/hyperledger/fabric-sdk-go/pkg/fab/peer"
"github.com/hyperledger/fabric-sdk-go/pkg/fab/txn"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/common"
pb "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/peer"
)

var logger = logging.NewLogger("fabsdk/client")

//EndorsementHandler for handling endorse transactions
type EndorsementHandler struct {
next Handler
Expand Down Expand Up @@ -118,7 +115,7 @@ func (f *EndorsementValidationHandler) validate(txProposalResponse []*fab.Transa
continue
}

if bytes.Compare(a1, r.ProposalResponse.GetResponse().Payload) != 0 {
if !bytes.Equal(a1, r.ProposalResponse.GetResponse().Payload) {
return status.New(status.EndorserClientStatus, status.EndorsementMismatch.ToInt32(),
"ProposalResponsePayloads do not match", nil)
}
Expand Down Expand Up @@ -239,7 +236,7 @@ func createAndSendTransaction(sender fab.Sender, proposal *fab.TransactionPropos
return transactionResponse, nil
}

func createAndSendTransactionProposal(transactor fab.Transactor, chrequest *Request, targets []fab.ProposalProcessor) ([]*fab.TransactionProposalResponse, *fab.TransactionProposal, error) {
func createAndSendTransactionProposal(transactor fab.ProposalSender, chrequest *Request, targets []fab.ProposalProcessor) ([]*fab.TransactionProposalResponse, *fab.TransactionProposal, error) {
request := fab.ChaincodeInvokeRequest{
ChaincodeID: chrequest.ChaincodeID,
Fcn: chrequest.Fcn,
Expand Down
5 changes: 1 addition & 4 deletions pkg/client/channel/invoke/txnhandler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,8 @@ import (

const (
testTimeOut = 20 * time.Second
discoveryServiceError = "Discovery service error"
selectionServiceError = "Selection service error"
endorsementMisMatchError = "ProposalResponsePayloads do not match"

filterTxError = "Filter Tx error"
)

func TestQueryHandlerSuccess(t *testing.T) {
Expand Down Expand Up @@ -77,7 +74,7 @@ func TestExecuteTxHandlerSuccess(t *testing.T) {
case txStatusReg := <-mockEventService.TxStatusRegCh:
txStatusReg.Eventch <- &fab.TxStatusEvent{TxID: txStatusReg.TxID, TxValidationCode: pb.TxValidationCode_VALID}
case <-time.After(requestContext.Opts.Timeouts[core.Execute]):
t.Fatal("Execute handler : time out not expected")
panic("Execute handler : time out not expected")
}
}()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ func TestStaticDiscovery(t *testing.T) {
t.Fatalf("Failed to setup discovery provider: %s", err)
}

discoveryService, err := discoveryProvider.CreateDiscoveryService("invalidChannel")
_, err = discoveryProvider.CreateDiscoveryService("invalidChannel")
if err == nil {
t.Fatalf("Should have failed to setup discovery service for non-configured channel")
}

discoveryService, err = discoveryProvider.CreateDiscoveryService("mychannel")
discoveryService, err := discoveryProvider.CreateDiscoveryService("mychannel")
if err != nil {
t.Fatalf("Failed to setup discovery service: %s", err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,10 @@ import (
"strings"
"testing"

"net"

"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
mocks "github.com/hyperledger/fabric-sdk-go/pkg/fab/mocks"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
pb "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/peer"
"google.golang.org/grpc"
)

func startEndorserServer(t *testing.T, grpcServer *grpc.Server, testAddress string) (*mocks.MockEndorserServer, string) {
lis, err := net.Listen("tcp", testAddress)
addr := lis.Addr().String()

endorserServer := &mocks.MockEndorserServer{}
pb.RegisterEndorserServer(grpcServer, endorserServer)
if err != nil {
t.Logf("Error starting test server %s", err)
t.FailNow()
}
t.Logf("Starting test server on %s\n", addr)
go grpcServer.Serve(lis)
return endorserServer, addr
}

func TestCCPolicyProvider(t *testing.T) {
// Create SDK setup for channel client with dynamic selection
sdk, err := fabsdk.New(config.FromFile("../../../../../test/fixtures/config/config_test.yaml"))
Expand All @@ -50,37 +30,37 @@ func TestCCPolicyProvider(t *testing.T) {
}

// Nil sdk
ccPolicyProvider, err := newCCPolicyProvider(nil, "mychannel", "User1", "Org1")
_, err = newCCPolicyProvider(nil, "mychannel", "User1", "Org1")
if err == nil {
t.Fatalf("Should have failed for nil sdk")
}

// Invalid channelID
ccPolicyProvider, err = newCCPolicyProvider(context, "", "User1", "Org1")
_, err = newCCPolicyProvider(context, "", "User1", "Org1")
if err == nil {
t.Fatalf("Should have failed for empty channel")
}

// Empty user name
ccPolicyProvider, err = newCCPolicyProvider(context, "mychannel", "", "Prg1")
_, err = newCCPolicyProvider(context, "mychannel", "", "Prg1")
if err == nil {
t.Fatalf("Should have failed for empty user name")
}

// Empty org name
ccPolicyProvider, err = newCCPolicyProvider(context, "mychannel", "User1", "")
_, err = newCCPolicyProvider(context, "mychannel", "User1", "")
if err == nil {
t.Fatalf("Should have failed for nil sdk")
}

// Invalid channel
ccPolicyProvider, err = newCCPolicyProvider(context, "non-existent", "User1", "Org1")
_, err = newCCPolicyProvider(context, "non-existent", "User1", "Org1")
if err == nil {
t.Fatalf("Should have failed for invalid channel name")
}

// All good
ccPolicyProvider, err = newCCPolicyProvider(context, "mychannel", "User1", "Org1")
ccPolicyProvider, err := newCCPolicyProvider(context, "mychannel", "User1", "Org1")
if err != nil {
t.Fatalf("Failed to setup cc policy provider: %s", err)
}
Expand Down
30 changes: 0 additions & 30 deletions pkg/client/common/selection/dynamicselection/dynamicselection.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/hyperledger/fabric-sdk-go/pkg/util/concurrent/lazycache"
"github.com/hyperledger/fabric-sdk-go/pkg/util/concurrent/lazyref"

"github.com/hyperledger/fabric-sdk-go/pkg/common/logging"
copts "github.com/hyperledger/fabric-sdk-go/pkg/common/options"
contextAPI "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core"
Expand Down Expand Up @@ -86,7 +85,6 @@ type selectionService struct {
pgLBP pgresolver.LoadBalancePolicy
ccPolicyProvider CCPolicyProvider
discoveryService fab.DiscoveryService
cacheTimeout time.Duration
}

// Initialize allow for initializing providers
Expand Down Expand Up @@ -258,31 +256,3 @@ func (s *selectionService) getPolicyGroupForCC(channelID string, ccID string) (p
}
return pgresolver.CompileSignaturePolicy(sigPolicyEnv)
}

func (s *selectionService) getAvailablePeers(mspID string) []fab.Peer {
channelPeers, err := s.discoveryService.GetPeers()
if err != nil {
logger.Errorf("Error retrieving peers from discovery service: %s", err)
return nil
}

var peers []fab.Peer
for _, peer := range channelPeers {
if string(peer.MSPID()) == mspID {
peers = append(peers, peer)
}
}

if logging.IsEnabledFor(loggerModule, logging.DEBUG) {
str := ""
for i, peer := range peers {
str += peer.URL()
if i+1 < len(peers) {
str += ","
}
}
logger.Debugf("Available peers:\n%s\n", str)
}

return peers
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,22 @@ import (
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-sdk-go/pkg/client/common/selection/dynamicselection/pgresolver"
"github.com/hyperledger/fabric-sdk-go/pkg/common/logging"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/fab/mocks"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk/factory/defsvc"
mspmocks "github.com/hyperledger/fabric-sdk-go/pkg/msp/test/mockmsp"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/core/common/ccprovider"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/common"
)

var testConfig *config.Config

const (
org1 = "Org1MSP"
org2 = "Org2MSP"
org3 = "Org3MSP"
org4 = "Org4MSP"
org5 = "Org5MSP"
org6 = "Org6MSP"
org7 = "Org7MSP"
org8 = "Org8MSP"
org9 = "Org9MSP"
org10 = "Org10MSP"
org1 = "Org1MSP"
org2 = "Org2MSP"
org3 = "Org3MSP"
org4 = "Org4MSP"
org5 = "Org5MSP"
)

const (
Expand All @@ -49,7 +40,6 @@ const (
const (
cc1 = "cc1"
cc2 = "cc2"
cc3 = "cc3"
)

const (
Expand Down Expand Up @@ -491,12 +481,6 @@ func (lbp *customLBP) Choose(peerGroups []pgresolver.PeerGroup) pgresolver.PeerG
return peerGroups[0]
}

func setupMockContext(username, orgName string) context.Providers {
user := mspmocks.NewMockSigningIdentity(username, orgName)
ctx := mocks.NewMockContext(user)
return ctx
}

type mockDiscoveryService struct {
peers []fab.Peer
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,11 @@ import (
)

const (
org1 = "Org1MSP"
org2 = "Org2MSP"
org3 = "Org3MSP"
org4 = "Org4MSP"
org5 = "Org5MSP"
org6 = "Org6MSP"
org7 = "Org7MSP"
org8 = "Org8MSP"
org9 = "Org9MSP"
org10 = "Org10MSP"
org1 = "Org1MSP"
org2 = "Org2MSP"
org3 = "Org3MSP"
org4 = "Org4MSP"
org5 = "Org5MSP"
)

var p1 = peer("peer1", "peer1:9999", org1)
Expand All @@ -43,8 +38,6 @@ var p12 = peer("peer12", "peer12:9999", org5)

var allPeers = []fab.Peer{p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12}

var configImp = mocks.NewMockConfig()

const (
o1 = iota
o2
Expand Down Expand Up @@ -347,10 +340,6 @@ func peer(name, url, mspID string) fab.Peer {
return mp
}

func peers(peers ...fab.Peer) []fab.Peer {
return peers
}

func verify(t *testing.T, pgResolver PeerGroupResolver, peers []fab.Peer, expectedPeerGroups []PeerGroup, expectedErr error) {
peerGroup, err := pgResolver.Resolve(peers)
if err != nil {
Expand Down
Loading

0 comments on commit e3276ec

Please sign in to comment.