testing

package
v0.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 29, 2019 License: MIT Imports: 24 Imported by: 4

README

Test Hyperledger Fabric golang chaincode: check blockchain state, events and permissions

Testing stage is a critical requirement for software quality assurance, doesn't matter is this
web application or a smart contract. Tests must be fast enough to run on every commit to repository. CCKit, programming toolkit for developing and testing hyperledger fabric golang chaincodes, enhances the development experience with extended version of MockStub for chaincode testing.

Chaincode testing techniques

Chaincode (smart contract) testing

A smart contract defines the different states of a business object and governs the processes that move the object between these different states. Smart contracts are important because they allow architects and smart contract developers to define the key business processes and data that are shared across the different organizations collaborating in a blockchain network.

Tests must ensure that chaincode works as expected:

  • particular input payload leads to particular business object state change
  • particular input payload leads to validation or other errors
  • particular object state allow subset of state transitions

Any software testing (chaincode or web application for example) may either be a manual or an automated process. Manual software testing is led by a team or individual who will manually operate a software product and ensure it behaves as expected. In case of chaincode tests you can manually invoke chaincode via peer cli tools.

Automated software testing is the practice of instrumenting input and output correctness checks for individual units of code. During automated testing, code are executed in a test environment with simulated input.

Steps in chaincode development process

The job of a smart contract developer is to take an existing business process and express it as a smart contract in a programming language. Steps of chaincode development:

  • Define chaincode model - schema for state entries, input payload and events
  • Define chaincode interface
  • Implement chaincode instantiate method
  • Implement chaincode methods with business logic
  • Create tests

Test driven development (TDD) or Behavioral Driven Development, possibly, single way to develop smart contracts.

Running chaincode

Deploying chaincode to blockchain network isn't the quickest thing in the world, there's a lot of time that can be saved with testing. Also, more importantly, since blockchain is immutable and supposed to be secure because the code is on the network, we rather not leave flaws in our code.

During chaincode development we can divide testing to multiple stage - fast stage, when testing only smart contract logic, and more complicated stage, when we do integration testing with live blockchain network, multiple peers, deployed on-chain code (smart contracts) and off-chain application, that uses SDK to connect with blockchain network peers.

Chaincode DEV mode

Deploying a Hyperledger Fabric blockchain network, chaincode installing and initializing is quite complicated to set up and a long procedure. Time to re-install / upgrade the code of a smart contract can be reduced by using chaincode dev mode. Normally chaincodes are started and maintained by peer. In “dev” mode, chaincode is built and started by the user. This mode is useful during chaincode development phase for rapid code/build/run/debug cycle turnaround. However, the process of updating the code will still be slow.

MockStub

The shim package contains a MockStub implementation that wraps calls to a chaincode, simulating its behavior in the HLF peer environment. MockStub does not need to start multiple docker containers with peer, world state database, chaincodes and allows to get test results almost immediately. MockStub essentially replaces the SDK and peer enviroment and allows to test chaincode without actually starting your network. It implements almost every function the actual stub does, but in memory.

mockstub

MockStub includes implementation for most of shim.ChaincodeStubInterface function, but in the current version of Hyperledger Fabric (1.4), the MockStub has not implemented some of the important methods such as GetCreator or method for work with private state range, for example. Since chaincode would use GetCreator method to get tx creator certificate for access control, it's critical to be able to stub this method in order to completely unit-test chaincode.

CCKit MockStub

CCKit testing package contains:

  • MockStub with implemented GetCreator, GetTransient methods and event subscription feature
  • Test identity creation helpers
  • Chaincode expect helpers

Testing in Go

Go has a built-in testing command called go test and a package testing which combine to give a minimal but complete testing experience. In our example we use Ginkgo - BDD-style Go testing framework, builds on Go’s testing package, and allows you to write expressive tests in an efficient and effective manner. It is best paired with the Gomega matcher library but is designed to be matcher-agnostic.

As with popular BDD frameworks in other languages, Ginkgo allows you to group tests in Describe and Context container blocks. Ginkgo provides the It and Specify blocks which can hold your assertions. It also comes with handy structural utilities such as BeforeSuite, AfterSuite etc that allow you to separate test configuration from test creation, and improve code reuse.

Ginkgo also comes with support for writing asynchronous tests. This makes testing code that use channels with chaincode events as easy as testing synchronous code.

Commercial Paper chaincode

Scenario

Official hyperledger fabric documentation contain detailed chaincode example - commercial paper smart contract that defines the valid states for commercial paper, and the transaction logic that transition a paper from one state to another. We will test commercial paper extended chaincode example based on CCKit with protobuf state, described in article.

We can represent the lifecycle of a commercial paper using a state transition diagram: commercial papers transition between issued, trading and redeemed states by means of the issue, buy and redeem transactions.

state

Requirements

To produce tests first we need to define requirements to tested application. Let’s start by listing our requirements for commercial paper chaincode:

  • It should allow the issuer to issue commercial paper
  • It should allow the participant to buy commercial paper
  • It should allow the owner to redeem commercial paper

Chaincode interface functions described in file chaincode.go, so we can see all possible operations with chaincode data.

    Query("list", queryCPapers).

    // Get method has 2 params - commercial paper primary key components
    Query("get", queryCPaper, defparam.Proto(&schema.CommercialPaperId{})).
    Query("getByExternalId", queryCPaperGetByExternalId, param.String("externalId")).

    // txn methods
    Invoke("issue", invokeCPaperIssue, defparam.Proto(&schema.IssueCommercialPaper{})).
    Invoke("buy", invokeCPaperBuy, defparam.Proto(&schema.BuyCommercialPaper{})).
    Invoke("redeem", invokeCPaperRedeem, defparam.Proto(&schema.RedeemCommercialPaper{})).
    Invoke("delete", invokeCPaperDelete, defparam.Proto(&schema.CommercialPaperId{}))

Getting started

Before you begin, be sure to get CCKit:

git clone git@github.com:s7techlab/cckit.git

This will fetch and install the CCKit package with examples. After that we need to install the dependencies using command:

go mod vendor

Creating test suite

Test package

To write a new test suite, create a file whose name ends _test.go that contains the TestXxx functions, in our case will be cpaper_extended/chaincode_test.go

Using separate package with tests cpaper_extended_test instead of cpaper_extended allows us to respect the encapsulation of the chaincode package: your tests will need to import chaincode and access it from the outside. You cannot fiddle around with the internals, instead you focus on the exposed chaincode interface.

Import matchers and helpers

To get started, we need to import the matcher functionality from the Ginkgo testing package so we can use different comparison mechanisms like comparing response objects or status codes.

We import the ginkgo and gomega packages with the . so that we can use functions from these packages without the package prefix. In short, this allows us to use Describe instead of ginkgo.Describe, and Equal instead of gomega.Equal.

Bootstrap

The call to RegisterFailHandler registers a handler, the Fail function from the ginkgo package, with Gomega. This creates the coupling between Ginkgo and Gomega.

Test suite bootstrap example:

package main

import (
	"fmt"
	"testing"
	"github.com/s7techlab/cckit/examples/insurance/app"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	testcc "github.com/s7techlab/cckit/testing"
	expectcc "github.com/s7techlab/cckit/testing/expect"
)

func TestCommercialPaper(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Commercial paper suite")
}

var _ = Describe(`Commercial paper`, func() {
	

}
Test structure

This particular test specification can be written using Ginkgo as follows:

var _ = Describe(`CommercialPaper`, func() {
	
		Describe("Commercial Paper lifecycle", func() {
			
			It("Allow issuer to issue new commercial paper", func() { ... }
			
			It("Allow issuer to get commercial paper by composite primary key", func() { ... }
			
		    It("Allow issuer to get commercial paper by unique key", func() { ... }
		    
		    It("Allow issuer to get a list of commercial papers", func() { ... }
		    
		    It("Allow buyer to buy commercial paper", func() { ... }
		    
		    It("Allow buyer to redeem commercial paper", func() { ... }
			
		    It("Allow issuer to delete commercial paper", func() { ... }
		}
}
Implementing tests

Now we go in depth to see how to create test functions specifically for chaincode development using MockStub functionalities.

Tests suite starts with creating a new instance of chaincode, or we can also instantiate a new chaincode instance before every test spec. This depends on how and what we want to test. In this example we instantiate a global commercial paper chaincode that can be used in multiple test specs.

Chaincode invocation results

All chaincode invocation (via SDK to blockchain peer or to MockStub) resulted as peer.Response structure:

type Response struct {
	// A status code that should follow the HTTP status codes.
	Status int32 
	// A message associated with the response code.
	Message string 
	// A payload that can be used to include metadata with this response.
	Payload              []byte   
}

During tests we can check Response attribute:

  • Status (error or success)
  • Message string ( contains error description)
  • Payload contents ( marshaled json or protobuf)
Testing helpers

Testing package contains multiple helpers / wrappers on ginkgo expect functions.

Most frequently used helpers are:

  • ResponseOk (response peer.Response) expects that peer response contains ok code (200)
  • ResponseError (response peer.Response) expects that peer response contains error code (500). Optionally you can pass expected error substring
  • PayloadIs(response peer.Response, target interface{})
Init function

When the chaincode is initialised, we want to test the execution status and make sure everything was successful. The equal method of the expect functionality comes in handy to compare the status.

Running test

To run the test suite you have to simply run the command in the repository where the test suite is located:

go test

Conclusion

Chaincode MockStub is really useful as it allows a developer to test his chaincode without starting the network every time. This reduces development time as he can use a test driven development (TDD) approach where he doesn’t need to start the network (this takes +- 40-80 seconds depending on the specs of the computer).

Documentation

Index

Constants

View Source
const EventChannelBufferSize = 100

Variables

View Source
var (
	// ErrChaincodeNotExists occurs when attempting to invoke a nonexostent external chaincode
	ErrChaincodeNotExists = errors.New(`chaincode not exists`)
	// ErrUnknownFromArgsType occurs when attempting to set unknown args in From func
	ErrUnknownFromArgsType = errors.New(`unknown args type to cckit.MockStub.From func`)
	// ErrKeyAlreadyExistsInTransientMap occurs when attempting to set existing key in transient map
	ErrKeyAlreadyExistsInTransientMap = errors.New(`key already exists in transient map`)
)

Functions

func MustConvertFromBytes added in v0.4.4

func MustConvertFromBytes(bb []byte, target interface{}) interface{}

func MustJSONMarshal added in v0.4.5

func MustJSONMarshal(val interface{}) []byte

func MustProtoMarshal added in v0.4.1

func MustProtoMarshal(pb proto.Message) []byte

MustProtoMarshal marshals proto.Message, panics if error

func MustProtoTimestamp added in v0.4.1

func MustProtoTimestamp(t time.Time) *timestamp.Timestamp

MustProtoTimestamp, creates proto.Timestamp, panics if error

func MustProtoUnmarshal added in v0.4.3

func MustProtoUnmarshal(bb []byte, pm proto.Message) proto.Message

MustProtoUnmarshal unmarshals proto.Message, panics if error

func TransformCreator

func TransformCreator(txCreator ...interface{}) (mspID string, certPEM []byte, err error)

TransformCreator transforms arbitrary tx creator (pmsp.SerializedIdentity etc) to mspID string, certPEM []byte,

Types

type ChannelMockStubs added in v0.4.4

type ChannelMockStubs map[string]*MockStub

type ChannelsMockStubs added in v0.4.4

type ChannelsMockStubs map[string]ChannelMockStubs

type CreatorTransformer

type CreatorTransformer func(...interface{}) (mspID string, certPEM []byte, err error)

type EventSubscription added in v0.4.4

type EventSubscription struct {
	// contains filtered or unexported fields
}

func (*EventSubscription) Close added in v0.4.4

func (es *EventSubscription) Close() error

func (*EventSubscription) Errors added in v0.4.4

func (es *EventSubscription) Errors() chan error

func (*EventSubscription) Events added in v0.4.4

func (es *EventSubscription) Events() chan *peer.ChaincodeEvent

type Identities added in v0.4.4

type Identities map[string]*Identity

func IdentitiesFromFiles added in v0.4.4

func IdentitiesFromFiles(mspID string, files map[string]string, getContent identity.GetContent) (Identities, error)

IdentitiesFromFiles returns map of CertIdentity, loaded from PEM files

func IdentitiesFromPem added in v0.4.4

func IdentitiesFromPem(mspID string, certPEMs map[string][]byte) (ids Identities, err error)

IdentitiesFromPem returns CertIdentity (MSP ID and X.509 cert) converted PEM content

func MustIdentitiesFromFiles added in v0.4.5

func MustIdentitiesFromFiles(mspID string, files map[string]string, getContent identity.GetContent) Identities

MustIdentitiesFromFiles

type Identity added in v0.4.4

type Identity struct {
	MspId       string
	Certificate *x509.Certificate
}

implements msp.SigningIdentity

func IdentityFromFile added in v0.5.2

func IdentityFromFile(mspID string, file string, getContent identity.GetContent) (*Identity, error)

IdentityFromFile returns Identity struct containing mspId and certificate

func IdentityFromPem added in v0.4.5

func IdentityFromPem(mspID string, certPEM []byte) (*Identity, error)

func MustIdentityFromPem added in v0.4.5

func MustIdentityFromPem(mspID string, certPEM []byte) *Identity

func NewIdentity added in v0.4.4

func NewIdentity(mspID string, cert *x509.Certificate) *Identity

func (*Identity) Anonymous added in v0.4.4

func (i *Identity) Anonymous() bool

func (*Identity) ExpiresAt added in v0.4.4

func (i *Identity) ExpiresAt() time.Time

ExpiresAt returns date of certificate expiration

func (*Identity) GetID added in v0.4.4

func (i *Identity) GetID() string

func (*Identity) GetIdentifier added in v0.4.4

func (i *Identity) GetIdentifier() *msp.IdentityIdentifier

func (*Identity) GetMSPIdentifier added in v0.4.4

func (i *Identity) GetMSPIdentifier() string

GetMSPIdentifier returns current MspID of identity

func (*Identity) GetOrganizationalUnits added in v0.4.4

func (i *Identity) GetOrganizationalUnits() []*msp.OUIdentifier

func (*Identity) GetPEM added in v0.4.4

func (i *Identity) GetPEM() []byte

GetPEM certificate encoded to PEM

func (*Identity) GetPublicVersion added in v0.4.4

func (i *Identity) GetPublicVersion() msp.Identity

func (*Identity) GetSubject added in v0.4.4

func (i *Identity) GetSubject() string

func (*Identity) SatisfiesPrincipal added in v0.4.4

func (i *Identity) SatisfiesPrincipal(principal *msppb.MSPPrincipal) error

func (*Identity) Serialize added in v0.4.4

func (i *Identity) Serialize() ([]byte, error)

func (*Identity) Sign added in v0.4.4

func (i *Identity) Sign(msg []byte) ([]byte, error)

func (*Identity) Validate added in v0.4.4

func (i *Identity) Validate() error

func (*Identity) Verify added in v0.4.4

func (i *Identity) Verify(msg []byte, sig []byte) error

type MockStub

type MockStub struct {
	shim.MockStub

	ClearCreatorAfterInvoke bool

	InvokablesFull map[string]*MockStub // invokable this version of MockStub

	ChaincodeEvent *peer.ChaincodeEvent // event in last tx

	PrivateKeys map[string]*list.List
	// contains filtered or unexported fields
}

MockStub replacement of shim.MockStub with creator mocking facilities

func NewMockStub

func NewMockStub(name string, cc shim.Chaincode) *MockStub

NewMockStub creates chaincode imitation

func (*MockStub) AddTransient added in v0.4.5

func (stub *MockStub) AddTransient(transient map[string][]byte) *MockStub

AddTransient adds key-value pairs to transient map

func (*MockStub) ClearEvents

func (stub *MockStub) ClearEvents()

ClearEvents clears chaincode events channel

func (*MockStub) DelPrivateData added in v0.5.0

func (stub *MockStub) DelPrivateData(collection string, key string) error

DelPrivateData mocked

func (*MockStub) EventSubscription

func (stub *MockStub) EventSubscription() chan *peer.ChaincodeEvent

func (*MockStub) From

func (stub *MockStub) From(txCreator ...interface{}) *MockStub

From mock tx creator

func (*MockStub) GetArgs

func (stub *MockStub) GetArgs() [][]byte

GetArgs mocked args

func (*MockStub) GetCreator

func (stub *MockStub) GetCreator() ([]byte, error)

GetCreator mocked

func (*MockStub) GetFunctionAndParameters

func (stub *MockStub) GetFunctionAndParameters() (function string, params []string)

GetFunctionAndParameters mocked

func (*MockStub) GetPrivateDataByPartialCompositeKey added in v0.5.0

func (stub *MockStub) GetPrivateDataByPartialCompositeKey(collection, objectType string, attributes []string) (shim.StateQueryIteratorInterface, error)

GetPrivateDataByPartialCompositeKey mocked

func (*MockStub) GetStringArgs

func (stub *MockStub) GetStringArgs() []string

GetStringArgs get mocked args as strings

func (*MockStub) GetTransient added in v0.3.0

func (stub *MockStub) GetTransient() (map[string][]byte, error)

func (*MockStub) Init

func (stub *MockStub) Init(iargs ...interface{}) peer.Response

Init func of chaincode - sugared version with autogenerated tx uuid

func (*MockStub) InitBytes added in v0.4.5

func (stub *MockStub) InitBytes(args ...[]byte) peer.Response

InitBytes init func with ...[]byte args

func (*MockStub) Invoke

func (stub *MockStub) Invoke(funcName string, iargs ...interface{}) peer.Response

Invoke sugared invoke function with autogenerated tx uuid

func (*MockStub) InvokeBytes added in v0.3.0

func (stub *MockStub) InvokeBytes(args ...[]byte) peer.Response

InvokeByte mock invoke with autogenerated tx uuid

func (*MockStub) InvokeChaincode

func (stub *MockStub) InvokeChaincode(chaincodeName string, args [][]byte, channel string) peer.Response

InvokeChaincode using another MockStub

func (*MockStub) MockCreator

func (stub *MockStub) MockCreator(mspID string, certPEM []byte)

MockCreator of tx

func (*MockStub) MockInit

func (stub *MockStub) MockInit(uuid string, args [][]byte) peer.Response

MockInit mocked init function

func (*MockStub) MockInvoke

func (stub *MockStub) MockInvoke(uuid string, args [][]byte) peer.Response

MockInvoke

func (*MockStub) MockPeerChaincode

func (stub *MockStub) MockPeerChaincode(invokableChaincodeName string, otherStub *MockStub)

MockPeerChaincode link to another MockStub

func (*MockStub) MockQuery added in v0.4.1

func (stub *MockStub) MockQuery(uuid string, args [][]byte) peer.Response

MockQuery

func (*MockStub) MockedPeerChaincodes added in v0.4.5

func (stub *MockStub) MockedPeerChaincodes() []string

MockedPeerChaincodes returns names of mocked chaincodes, available for invoke from current stub

func (*MockStub) PutPrivateData added in v0.5.0

func (stub *MockStub) PutPrivateData(collection string, key string, value []byte) error

PutPrivateData mocked

func (*MockStub) Query

func (stub *MockStub) Query(funcName string, iargs ...interface{}) peer.Response

func (*MockStub) QueryBytes added in v0.4.1

func (stub *MockStub) QueryBytes(args ...[]byte) peer.Response

QueryBytes mock query with autogenerated tx uuid

func (*MockStub) RegisterCreatorTransformer

func (stub *MockStub) RegisterCreatorTransformer(creatorTransformer CreatorTransformer) *MockStub

RegisterCreatorTransformer that transforms creator data to MSP_ID and X.509 certificate

func (*MockStub) SetArgs

func (stub *MockStub) SetArgs(args [][]byte)

SetArgs set mocked args

func (*MockStub) SetEvent

func (stub *MockStub) SetEvent(name string, payload []byte) error

SetEvent sets chaincode event

func (*MockStub) WithTransient added in v0.3.0

func (stub *MockStub) WithTransient(transient map[string][]byte) *MockStub

WithTransient sets transient map

type MockedPeer added in v0.4.5

type MockedPeer struct {
	// channel name -> chaincode name
	ChannelCC ChannelsMockStubs
	// contains filtered or unexported fields
}

func NewPeer added in v0.4.5

func NewPeer() *MockedPeer

NewInvoker implements Invoker interface from hlf-sdk-go

func (*MockedPeer) Chaincode added in v0.4.5

func (mi *MockedPeer) Chaincode(channel string, chaincode string) (*MockStub, error)

func (*MockedPeer) Invoke added in v0.4.5

func (mi *MockedPeer) Invoke(
	ctx context.Context, from msp.SigningIdentity, channel string, chaincode string,
	fn string, args [][]byte, transArgs api.TransArgs) (*peer.Response, api.ChaincodeTx, error)

func (*MockedPeer) Query added in v0.4.5

func (mi *MockedPeer) Query(
	ctx context.Context, from msp.SigningIdentity, channel string, chaincode string,
	fn string, args [][]byte, transArgs api.TransArgs) (*peer.Response, error)

func (*MockedPeer) Subscribe added in v0.4.5

func (mi *MockedPeer) Subscribe(
	ctx context.Context, from msp.SigningIdentity, channel, chaincode string) (api.EventCCSubscription, error)

func (*MockedPeer) WithChannel added in v0.4.5

func (mi *MockedPeer) WithChannel(channel string, mockStubs ...*MockStub) *MockedPeer

type PrivateMockStateRangeQueryIterator added in v0.5.0

type PrivateMockStateRangeQueryIterator struct {
	Closed     bool
	Stub       *MockStub
	StartKey   string
	EndKey     string
	Current    *list.Element
	Collection string
}

func NewPrivateMockStateRangeQueryIterator added in v0.5.0

func NewPrivateMockStateRangeQueryIterator(stub *MockStub, collection string, startKey string, endKey string) *PrivateMockStateRangeQueryIterator

func (*PrivateMockStateRangeQueryIterator) Close added in v0.5.0

Close closes the range query iterator. This should be called when done reading from the iterator to free up resources.

func (*PrivateMockStateRangeQueryIterator) HasNext added in v0.5.0

func (iter *PrivateMockStateRangeQueryIterator) HasNext() bool

HasNext returns true if the range query iterator contains additional keys and values.

func (*PrivateMockStateRangeQueryIterator) Next added in v0.5.0

Next returns the next key and value in the range query iterator.

func (*PrivateMockStateRangeQueryIterator) Print added in v0.5.0

func (iter *PrivateMockStateRangeQueryIterator) Print()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL