Skip to content

Commit

Permalink
[FAB-3927] Add tests for invoke,query,instantiate cmds
Browse files Browse the repository at this point in the history
Add tests for invoke, query and instantiate peer chaincode
commands.

Change-Id: If9aa1fe85e027ef9d5ec7101395fe11a1c7db33d
Signed-off-by: Anil Ambati <[email protected]>
  • Loading branch information
Anil Ambati authored and wlahti committed May 26, 2017
1 parent 010dcf6 commit fd03063
Show file tree
Hide file tree
Showing 11 changed files with 588 additions and 61 deletions.
17 changes: 10 additions & 7 deletions peer/chaincode/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ func chaincodeInvokeOrQuery(cmd *cobra.Command, args []string, invoke bool, cf *
return err
}

proposalResp, err := ChaincodeInvokeOrQuery(spec, chainID, invoke, cf.Signer, cf.EndorserClient, cf.BroadcastClient)
proposalResp, err := ChaincodeInvokeOrQuery(spec, chainID, invoke,
cf.Signer, cf.EndorserClient, cf.BroadcastClient)
if err != nil {
return err
}
Expand Down Expand Up @@ -137,7 +138,8 @@ func checkChaincodeCmdParams(cmd *cobra.Command) error {
return fmt.Errorf("Must supply value for %s name parameter.", chainFuncName)
}

if cmd.Name() == instantiate_cmdname || cmd.Name() == install_cmdname || cmd.Name() == upgrade_cmdname || cmd.Name() == package_cmdname {
if cmd.Name() == instantiate_cmdname || cmd.Name() == install_cmdname ||
cmd.Name() == upgrade_cmdname || cmd.Name() == package_cmdname {
if chaincodeVersion == common.UndefinedParamValue {
return fmt.Errorf("Chaincode version is not provided for %s", cmd.Name())
}
Expand Down Expand Up @@ -222,21 +224,21 @@ func InitCmdFactory(isEndorserRequired, isOrdererRequired bool) (*ChaincodeCmdFa
var err error
var endorserClient pb.EndorserClient
if isEndorserRequired {
endorserClient, err = common.GetEndorserClient()
endorserClient, err = common.GetEndorserClientFnc()
if err != nil {
return nil, fmt.Errorf("Error getting endorser client %s: %s", chainFuncName, err)
}
}

signer, err := common.GetDefaultSigner()
signer, err := common.GetDefaultSignerFnc()
if err != nil {
return nil, fmt.Errorf("Error getting default signer: %s", err)
}

var broadcastClient common.BroadcastClient
if isOrdererRequired {
if len(orderingEndpoint) == 0 {
orderingEndpoints, err := common.GetOrdererEndpointOfChain(chainID, signer, endorserClient)
orderingEndpoints, err := common.GetOrdererEndpointOfChainFnc(chainID, signer, endorserClient)
if err != nil {
return nil, fmt.Errorf("Error getting (%s) orderer endpoint: %s", chainID, err)
}
Expand All @@ -247,7 +249,7 @@ func InitCmdFactory(isEndorserRequired, isOrdererRequired bool) (*ChaincodeCmdFa
orderingEndpoint = orderingEndpoints[0]
}

broadcastClient, err = common.GetBroadcastClient(orderingEndpoint, tls, caFile)
broadcastClient, err = common.GetBroadcastClientFnc(orderingEndpoint, tls, caFile)

if err != nil {
return nil, fmt.Errorf("Error getting broadcast client: %s", err)
Expand All @@ -269,7 +271,8 @@ func InitCmdFactory(isEndorserRequired, isOrdererRequired bool) (*ChaincodeCmdFa
//
// NOTE - Query will likely go away as all interactions with the endorser are
// Proposal and ProposalResponses
func ChaincodeInvokeOrQuery(spec *pb.ChaincodeSpec, cID string, invoke bool, signer msp.SigningIdentity, endorserClient pb.EndorserClient, bc common.BroadcastClient) (*pb.ProposalResponse, error) {
func ChaincodeInvokeOrQuery(spec *pb.ChaincodeSpec, cID string, invoke bool,
signer msp.SigningIdentity, endorserClient pb.EndorserClient, bc common.BroadcastClient) (*pb.ProposalResponse, error) {
// Build the ChaincodeInvocationSpec message
invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}
if customIDGenAlg != common.UndefinedParamValue {
Expand Down
82 changes: 82 additions & 0 deletions peer/chaincode/instantiate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
Copyright IBM Corp. 2017 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package chaincode

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestInstantiateCmd(t *testing.T) {
InitMSP()

mockCF, err := getMockChaincodeCmdFactory()
assert.NoError(t, err, "Error getting mock chaincode command factory")

// basic function tests
var tests = []struct {
args []string
errorExpected bool
errMsg string
}{
{
args: []string{"-n", "example02", "-p", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02",
"-v", "anotherversion", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
errorExpected: false,
errMsg: "Run chaincode instantiate cmd error",
},
{
args: []string{},
errorExpected: true,
errMsg: "Expected error executing instantiate command without required options",
},
{
args: []string{"-n", "example02", "-p", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02",
"-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
errorExpected: true,
errMsg: "Expected error executing instantiate command without the -v option",
},
{
args: []string{"-p", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02",
"-v", "anotherversion", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
errorExpected: true,
errMsg: "Expected error executing instantiate command without the -n option",
},
{
args: []string{"-n", "example02", "-p", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02",
"-v", "anotherversion"},
errorExpected: true,
errMsg: "Expected error executing instantiate command without the -c option",
},
}
for _, test := range tests {
cmd := instantiateCmd(mockCF)
AddFlags(cmd)
cmd.SetArgs(test.args)
err = cmd.Execute()
checkError(t, err, test.errorExpected, test.errMsg)
}
}

func checkError(t *testing.T, err error, expectedError bool, msg string) {
if expectedError {
assert.Error(t, err, msg)
} else {
assert.NoError(t, err, msg)
}
}
171 changes: 171 additions & 0 deletions peer/chaincode/invoke_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/*
Copyright IBM Corp. 2017 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package chaincode

import (
"errors"
"testing"

"github.com/hyperledger/fabric/msp"
"github.com/hyperledger/fabric/peer/common"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/stretchr/testify/assert"
)

func TestInvokeCmd(t *testing.T) {
InitMSP()
mockCF, err := getMockChaincodeCmdFactory()
assert.NoError(t, err, "Error getting mock chaincode command factory")

cmd := invokeCmd(mockCF)
AddFlags(cmd)
args := []string{"-n", "example02", "-p", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02",
"-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}"}
cmd.SetArgs(args)
err = cmd.Execute()
assert.NoError(t, err, "Run chaincode invoke cmd error")

// Error case 1: no orderer endpoints
t.Logf("Start error case 1: no orderer endpoints")
getEndorserClient := common.GetEndorserClientFnc
getOrdererEndpointOfChain := common.GetOrdererEndpointOfChainFnc
getBroadcastClient := common.GetBroadcastClientFnc
getDefaultSigner := common.GetDefaultSignerFnc
defer func() {
common.GetEndorserClientFnc = getEndorserClient
common.GetOrdererEndpointOfChainFnc = getOrdererEndpointOfChain
common.GetBroadcastClientFnc = getBroadcastClient
common.GetDefaultSignerFnc = getDefaultSigner
}()
common.GetEndorserClientFnc = func() (pb.EndorserClient, error) {
return mockCF.EndorserClient, nil
}
common.GetOrdererEndpointOfChainFnc = func(chainID string, signer msp.SigningIdentity, endorserClient pb.EndorserClient) ([]string, error) {
return []string{}, nil
}
cmd = invokeCmd(nil)
AddFlags(cmd)
args = []string{"-n", "example02", "-p", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02",
"-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}"}
cmd.SetArgs(args)
err = cmd.Execute()
assert.Error(t, err)

// Error case 2: getEndorserClient returns error
t.Logf("Start error case 2: getEndorserClient returns error")
common.GetEndorserClientFnc = func() (pb.EndorserClient, error) {
return nil, errors.New("error")
}
err = cmd.Execute()
assert.Error(t, err)

// Error case 3: getDefaultSignerFnc returns error
t.Logf("Start error case 3: getDefaultSignerFnc returns error")
common.GetEndorserClientFnc = func() (pb.EndorserClient, error) {
return mockCF.EndorserClient, nil
}
common.GetDefaultSignerFnc = func() (msp.SigningIdentity, error) {
return nil, errors.New("error")
}
err = cmd.Execute()
assert.Error(t, err)
common.GetDefaultSignerFnc = common.GetDefaultSigner

// Error case 4: getOrdererEndpointOfChainFnc returns error
t.Logf("Start error case 4: getOrdererEndpointOfChainFnc returns error")
common.GetEndorserClientFnc = func() (pb.EndorserClient, error) {
return mockCF.EndorserClient, nil
}
common.GetOrdererEndpointOfChainFnc = func(chainID string, signer msp.SigningIdentity, endorserClient pb.EndorserClient) ([]string, error) {
return nil, errors.New("error")
}
err = cmd.Execute()
assert.Error(t, err)

// Error case 5: getBroadcastClient returns error
t.Logf("Start error case 5: getBroadcastClient returns error")
common.GetOrdererEndpointOfChainFnc = func(chainID string, signer msp.SigningIdentity, endorserClient pb.EndorserClient) ([]string, error) {
return []string{"localhost:9999"}, nil
}
common.GetBroadcastClientFnc = func(orderingEndpoint string, tlsEnabled bool, caFile string) (common.BroadcastClient, error) {
return nil, errors.New("error")
}
err = cmd.Execute()
assert.Error(t, err)

// Success case
t.Logf("Start success case")
common.GetBroadcastClientFnc = func(orderingEndpoint string, tlsEnabled bool, caFile string) (common.BroadcastClient, error) {
return mockCF.BroadcastClient, nil
}
err = cmd.Execute()
assert.NoError(t, err)
}

func TestInvokeCmdEndorseFail(t *testing.T) {
InitMSP()
mockCF, err := getMockChaincodeCmdFactoryWithErr()
assert.NoError(t, err, "Error getting mock chaincode command factory")

cmd := invokeCmd(mockCF)
AddFlags(cmd)
args := []string{"-n", "example02", "-p", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02",
"-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}"}
cmd.SetArgs(args)
err = cmd.Execute()
assert.Error(t, err, "Expected error executing invoke command")
}

// Returns mock chaincode command factory
func getMockChaincodeCmdFactory() (*ChaincodeCmdFactory, error) {
signer, err := common.GetDefaultSigner()
if err != nil {
return nil, err
}
mockResponse := &pb.ProposalResponse{
Response: &pb.Response{Status: 200},
Endorsement: &pb.Endorsement{},
}
mockEndorserClient := common.GetMockEndorserClient(mockResponse, nil)
mockBroadcastClient := common.GetMockBroadcastClient(nil)
mockCF := &ChaincodeCmdFactory{
EndorserClient: mockEndorserClient,
Signer: signer,
BroadcastClient: mockBroadcastClient,
}
return mockCF, nil
}

// Returns mock chaincode command factory that is constructed with an endorser
// client that returns an error for proposal request
func getMockChaincodeCmdFactoryWithErr() (*ChaincodeCmdFactory, error) {
signer, err := common.GetDefaultSigner()
if err != nil {
return nil, err
}

errMsg := "invoke error"
mockEndorerClient := common.GetMockEndorserClient(nil, errors.New(errMsg))
mockBroadcastClient := common.GetMockBroadcastClient(nil)

mockCF := &ChaincodeCmdFactory{
EndorserClient: mockEndorerClient,
Signer: signer,
BroadcastClient: mockBroadcastClient,
}
return mockCF, nil
}
2 changes: 1 addition & 1 deletion peer/chaincode/package_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func TestCDSPackage(t *testing.T) {
ccpackfile := pdir + "/ccpack.file"
err := createSignedCDSPackage([]string{"-n", "somecc", "-p", "some/go/package", "-v", "0", ccpackfile}, false)
if err != nil {
t.Fatalf("Run chaincode upgrade cmd error:%v", err)
t.Fatalf("Run chaincode package cmd error:%v", err)
}

b, err := ioutil.ReadFile(ccpackfile)
Expand Down
Loading

0 comments on commit fd03063

Please sign in to comment.