Skip to content

Commit

Permalink
[FAB-9678] Channel Client: Examples
Browse files Browse the repository at this point in the history
Change-Id: I9fd8f4f64213b9b75419d14102521d974ed99a9e
Signed-off-by: Sandra Vrtikapa <sandra.vrtikapa@securekey.com>
  • Loading branch information
sandrask committed Apr 25, 2018
1 parent 830bdea commit 29957ca
Show file tree
Hide file tree
Showing 9 changed files with 379 additions and 450 deletions.
29 changes: 20 additions & 9 deletions pkg/client/channel/chclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,18 +369,10 @@ func TestOrdererStatusError(t *testing.T) {
func TestTransactionValidationError(t *testing.T) {
validationCode := pb.TxValidationCode_BAD_RWSET
mockEventService := fcmocks.NewMockEventService()
mockEventService.TxValidationCode = validationCode
testPeer1 := fcmocks.NewMockPeer("Peer1", "http://peer1.com")
peers := []fab.Peer{testPeer1}

go func() {
select {
case txStatusReg := <-mockEventService.TxStatusRegCh:
txStatusReg.Eventch <- &fab.TxStatusEvent{TxID: txStatusReg.TxID, TxValidationCode: validationCode}
case <-time.After(time.Second * 5):
panic("Timed out waiting for execute Tx to register event callback")
}
}()

chClient := setupChannelClient(peers, t)
chClient.eventService = mockEventService
response, err := chClient.Execute(Request{ChaincodeID: "test", Fcn: "invoke",
Expand All @@ -392,6 +384,25 @@ func TestTransactionValidationError(t *testing.T) {
assert.EqualValues(t, validationCode, status.ToTransactionValidationCode(statusError.Code))
}

func TestTransactionTimeout(t *testing.T) {

mockEventService := fcmocks.NewMockEventService()
mockEventService.Timeout = true
testPeer1 := fcmocks.NewMockPeer("Peer1", "http://peer1.com")
peers := []fab.Peer{testPeer1}

chClient := setupChannelClient(peers, t)
chClient.eventService = mockEventService
response, err := chClient.Execute(Request{ChaincodeID: "test", Fcn: "invoke",
Args: [][]byte{[]byte("move"), []byte("a"), []byte("b"), []byte("1")}})
assert.Nil(t, response.Payload, "Expected nil result on failed execute operation")
assert.NotNil(t, err, "expected error")
statusError, ok := status.FromError(err)
assert.True(t, ok, "Expected status error got %+v", err)

assert.EqualValues(t, statusError.Code, status.Timeout)
}

func TestExecuteTxWithRetries(t *testing.T) {
testStatus := status.New(status.EndorserClientStatus, status.ConnectionFailed.ToInt32(), "test", nil)
testResp := []byte("test")
Expand Down
138 changes: 138 additions & 0 deletions pkg/client/channel/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package channel

import (
"fmt"

"github.com/hyperledger/fabric-sdk-go/pkg/client/channel/invoke"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context"
"github.com/hyperledger/fabric-sdk-go/pkg/fab/mocks"
)

func Example() {

c, err := New(mockChannelProvider("mychannel"))
if err != nil {
fmt.Println("failed to create client")
}

response, err := c.Query(Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("query"), []byte("data")}})
if err != nil {
fmt.Printf("failed to query chaincode: %v", err)
}

fmt.Println(string(response.Payload))

// Output: abc
}

func ExampleNew() {

ctx := mockChannelProvider("mychannel")

c, err := New(ctx)
if err != nil {
fmt.Println(err)
}

if c != nil {
fmt.Println("channel client created")
} else {
fmt.Println("channel client is nil")
}

// Output: channel client created

}

func ExampleClient_Query() {

c, err := New(mockChannelProvider("mychannel"))
if err != nil {
fmt.Println("failed to create client")
}

response, err := c.Query(Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("query"), []byte("b")}})
if err != nil {
fmt.Printf("failed to query chaincode: %v", err)
}

if len(response.Payload) > 0 {
fmt.Println("chaincode query success")
}

// Output: chaincode query success
}

func ExampleClient_Execute() {

c, err := New(mockChannelProvider("mychannel"))
if err != nil {
fmt.Println("failed to create client")
}

_, err = c.Execute(Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("move"), []byte("a"), []byte("b"), []byte("1")}})
if err != nil {
fmt.Println(err.Error())
}

fmt.Println("Chaincode transaction completed")

// Output: Chaincode transaction completed
}

func ExampleClient_RegisterChaincodeEvent() {

c, err := New(mockChannelProvider("mychannel"))
if err != nil {
fmt.Println("failed to create client")
}

registration, _, err := c.RegisterChaincodeEvent("examplecc", "event123")
if err != nil {
fmt.Println("failed to register chaincode event")
}
defer c.UnregisterChaincodeEvent(registration)

fmt.Println("chaincode event registered successfully")

// Output: chaincode event registered successfully

}

func ExampleClient_InvokeHandler() {

c, err := New(mockChannelProvider("mychannel"))
if err != nil {
fmt.Println("failed to create client")
}

response, err := c.InvokeHandler(&exampleHandler{}, Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("query"), []byte("data")}})
if err != nil {
fmt.Printf("failed to query chaincode: %v", err)
}

fmt.Println(string(response.Payload))

// Output: custom
}

type exampleHandler struct {
}

func (c *exampleHandler) Handle(requestContext *invoke.RequestContext, clientContext *invoke.ClientContext) {
requestContext.Response.Payload = []byte("custom")
}

func mockChannelProvider(channelID string) context.ChannelProvider {

channelProvider := func() (context.Channel, error) {
return mocks.NewMockChannel(channelID)
}

return channelProvider
}
2 changes: 1 addition & 1 deletion pkg/client/channel/invoke/signature.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func (f *SignatureValidationHandler) Handle(requestContext *RequestContext, clie
//Filter tx proposal responses
err := f.validate(requestContext.Response.Responses, clientContext)
if err != nil {
requestContext.Error = errors.WithMessage(err, "endorsement validation failed")
requestContext.Error = errors.WithMessage(err, "signature validation failed")
return
}

Expand Down
9 changes: 8 additions & 1 deletion pkg/client/channel/invoke/txnhandler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,19 @@ func TestExecuteTxHandlerErrors(t *testing.T) {
func TestEndorsementHandler(t *testing.T) {
request := Request{ChaincodeID: "test", Fcn: "invoke", Args: [][]byte{[]byte("move"), []byte("a"), []byte("b"), []byte("1")}}

requestContext := prepareRequestContext(request, Opts{Targets: []fab.Peer{fcmocks.NewMockPeer("p2", "")}}, t)
clientContext := setupChannelClientContext(nil, nil, nil, t)
requestContext := prepareRequestContext(request, Opts{Targets: nil}, t)

handler := NewEndorsementHandler()
handler.Handle(requestContext, clientContext)
assert.NotNil(t, requestContext.Error)

requestContext = prepareRequestContext(request, Opts{Targets: []fab.Peer{fcmocks.NewMockPeer("p2", "")}}, t)

handler = NewEndorsementHandler()
handler.Handle(requestContext, clientContext)
assert.Nil(t, requestContext.Error)

}

// Target filter
Expand Down
4 changes: 2 additions & 2 deletions pkg/client/resmgmt/resmgmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func New(ctxProvider context.ClientProvider, opts ...ClientOption) (*Client, err

ctx, err := ctxProvider()
if err != nil {
return nil, errors.WithMessage(err, "failed to create resmgmt client")
return nil, errors.WithMessage(err, "failed to create resmgmt client due to context error")
}

if ctx.Identifier().MSPID == "" {
Expand Down Expand Up @@ -688,7 +688,7 @@ func (rc *Client) sendCCProposal(reqCtx reqContext.Context, ccProposalType chain
// Verify signature(s)
err = rc.verifyTPSignature(channelService, txProposalResponse)
if err != nil {
return tp.TxnID, errors.WithMessage(err, "sending deploy transaction proposal failed")
return tp.TxnID, errors.WithMessage(err, "sending deploy transaction proposal failed to verify signature")
}

eventService, err := channelService.EventService()
Expand Down
Loading

0 comments on commit 29957ca

Please sign in to comment.