type Owner struct {
Id string `json:"id"`
Username string `json:"username"`
Company string `json:"company"`
}
//=====================================================================================================
// Create Owner - create a new owner and store it in the chaincode state
//=====================================================================================================
func create_owner(stub shim.ChaincodeStubInterface, args []string) peer.Response {
var err error
if len(args) < 3 {
return shim.Error("Incorrect number of arguments. Expecting at least 3")
}
var owner Owner
owner.Id = args[0]
owner.Username = args[1]
owner.Company = args[2]
// check if Owner already exists
_, err = get_owner(stub, owner.Id)
if err == nil {
return shim.Error("This Owner already exists - " + owner.Id)
}
// save the Owner
ownerAsBytes, _ := json.Marshal(owner) // convert to array of bytes
err = stub.PutState(owner.Id, ownerAsBytes) // store Owner by its Id
if err != nil {
fmt.Println("Could not save an Owner")
return shim.Error(err.Error())
}
return shim.Success(nil)
}
//=====================================================================================================
// Read Owner - get an Owner record as bytes from the ledger
//=====================================================================================================
func read_owner(stub shim.ChaincodeStubInterface, args []string) peer.Response {
var err error
key := args[0]
valAsbytes, err := stub.GetState(key)
if err != nil {
return shim.Error("Owner does not exist with Id '" + key + "'")
}
return shim.Success(valAsbytes)
}
type Asset struct {
ExternalId string `json:"externalId"` // Asset Id
Sernr string `json:"sernr"` // Serial Number
Matnr string `json:"matnr"` // Material Number
ObjDesc string `json:"objDesc"` // Description
OwnerId string `json:"ownerId"` // Owner Id
}
// ============================================================================================================================
// Change Owner for an Asset
// ============================================================================================================================
func set_owner(stub shim.ChaincodeStubInterface, args []string) peer.Response {
var err error
if len(args) != 2 {
return shim.Error("Incorrect number of arguments. Expecting 2")
}
var asset_id = args[0]
var new_owner_id = args[1]
// check if user already exists
owner, err := get_owner(stub, new_owner_id)
if err != nil || len(owner.Username) == 0 {
return shim.Error("This Owner does not exist - " + new_owner_id)
}
// get asset's current state
assetAsBytes, err := stub.GetState(asset_id)
if err != nil {
return shim.Error("Failed to read Asset")
}
var asset Asset
json.Unmarshal(assetAsBytes, &asset)
asset.OwnerId = new_owner_id
jsonAsBytes, _ := json.Marshal(asset)
err = stub.PutState(asset_id, jsonAsBytes)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {
return shim.Success(nil)
}
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
function, args := stub.GetFunctionAndParameters()
// Handle invoke functions
if function == "init" { // initialise the chaincode state
return t.Init(stub)
} else if function == "create_asset" { // create a new asset
return create_asset(stub, args)
} else if function == "read_asset" { // read an asset
return read_asset(stub, args)
} else if function == "create_owner" { // create an owner
return create_owner(stub, args)
} else if function == "read_owner" { // read an owner
return read_owner(stub, args)
} else if function == "set_owner" { // change owner of an asset
return set_owner(stub, args)
}
// error out
fmt.Println("Received unknown invoke function name - '" + function + "'")
return shim.Error("Received unknown invoke function name - '" + function + "'")
}
package main
import (
"testing"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
func TestInstancesCreation(test *testing.T) {
stub := InitChaincode(test)
assetExternalId := "ID01"
ownerId := "o1"
Invoke(test, stub, "create_owner", ownerId, "Username_1", "Company_1")
Invoke(test, stub, "create_asset", assetExternalId, "Sernr1234", "Matnr1234", "ObjDesc", ownerId)
}
func InitChaincode(test *testing.T) *shim.MockStub {
stub := shim.NewMockStub("testingStub", new(SimpleChaincode))
result := stub.MockInit("000", nil)
if result.Status != shim.OK {
test.FailNow()
}
return stub
}
func Invoke(test *testing.T, stub *shim.MockStub, function string, args ...string) {
cc_args := make([][]byte, 1+len(args))
cc_args[0] = []byte(function)
for i, arg := range args {
cc_args[i + 1] = []byte(arg)
}
result := stub.MockInvoke("000", cc_args)
fmt.Println("Call: ", function, "(", strings.Join(args,","), ")")
fmt.Println("RetCode: ", result.Status)
fmt.Println("RetMsg: ", result.Message)
fmt.Println("Payload: ", string(result.Payload))
if result.Status != shim.OK {
test.FailNow()
}
}
$ go get github.com/onsi/ginkgo/ginkgo
$ go get github.com/onsi/gomega/...
$ cd path/to/your_project
$ ginkgo bootstrap
package main
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestAsset(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Asset Transfer Suite")
}
$ go test -v
=== RUN TestAsset
Running Suite: Asset Suite
==========================
Random Seed: 1546738572
Will run 0 of 0 specs
Ran 0 of 0 Specs in 0.000 seconds
SUCCESS! -- 0 Passed | 0 Failed | 0 Pending | 0 Skipped
--- PASS: TestAsset (0.00s)
PASS
When running tests for the Asset
We would like to check that its create/read methods work fine
Once an Asset is successfully created
Another Asset instance is also retrieved successfully by the same Id
Once compared, the both Asset instances are identical
Describe("Running tests for the Asset", func() {
Context("Checking that create/read for Asset work fine", func() {
It("Should be created successfully", func() {})
It("Another Asset instance is retrieved successfully by the same Id", func() {})
Specify("Asset instances are identical", func() {})
})
})
It("Should be created successfully", func() {
mockOwner := [][]byte{
[]byte("o1"), // Id
[]byte("Username_1"), // Username
[]byte("Company_1") // Company
}
argsToCreate := append([][]byte{[]byte("create_owner")}, mockOwner...)
stub.MockInit("000", nil)
receivedStatus := stub.MockInvoke("000", argsToCreate).Status
status200 := int32(200)
Expect(receivedStatus).Should(Equal(status200))
})
It("Another Asset instance is retrieved successfully by the same Id", func() {
argsToRead := [][]byte{[]byte("read_owner"), []byte("o1")}
stub.MockInit("000", nil)
result := stub.MockInvoke("000", argsToRead)
status200 := int32(200)
Expect(result.Status).Should(Equal(status200))
})
Specify("Asset instances are identical", func() {
Expect(payload).To(Equal(mockOwner))
})
package main
import (
"github.com/hyperledger/fabric/core/chaincode/shim"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Tests for Assets", func() {
stub := shim.NewMockStub("testingStub", new(SimpleChaincode))
status200 := int32(200)
mockOwner := GetFirstOwnerForTesting()
mockOwnerAsBytes := ConvertBytesToOwnerAsBytes(mockOwner)
argsToCreate := append([][]byte{[]byte("create_owner")}, mockOwner...)
argsToRead := [][]byte{[]byte("read_owner"), mockOwner[0]}
payload := []byte{}
BeforeSuite(func() {
stub.MockInit("000", nil)
})
Describe("Checking the CRUD operations", func() {
Context("Checking that create/read work fine", func() {
It("An Owner should be created successfully first", func() {
receivedStatus := stub.MockInvoke("000", argsToCreateOwner).Status
Expect(receivedStatus).Should(Equal(status200))
})
It("First Asset instance should be saved successfully", func() {
receivedStatus := stub.MockInvoke("000", argsToCreate).Status
Expect(receivedStatus).Should(Equal(status200))
})
It("Another Asset instance is retrieved by the same Id", func() {
result := stub.MockInvoke("000", argsToRead)
payload = []byte(result.Payload)
Expect(result.Status).Should(Equal(status200))
})
Specify("Asset instances are identical", func() {
Expect(payload).To(Equal(mockOwnerAsBytes))
})
})
})
})
$ go test
Running Suite: Asset Suite
==========================
Random Seed: 1546775466
Will run 7 of 7 specs
+++
Ran 7 of 7 Specs in 0.000 seconds
SUCCESS! -- 7 Passed | 0 Failed | 0 Pending | 0 Skipped
PASS
ok
Describe("Running tests to check Assets tracking", func() {
Context("Checking that Asset is transferred correctly between Owners", func() {
It("First Owner should be created successfully", func() {
stub.DelState(string(mockOwner[0]))
receivedStatus := stub.MockInvoke("000", argsToCreateOwner).Status
Expect(receivedStatus).Should(Equal(status200))
})
It("Second Owner should be created successfully", func() {
receivedStatus := stub.MockInvoke("000", argsToCreateAnotherOwner).Status
Expect(receivedStatus).Should(Equal(status200))
})
It("Asset should be created successfully belonging to the first Owner", func() {
receivedStatus := stub.MockInvoke("000", argsToCreateAsset).Status
Expect(receivedStatus).Should(Equal(status200))
})
It("Asset should be passed to the second Owner", func() {
result := stub.MockInvoke("000", argsToPassAsset)
Expect(result.Status).Should(Equal(status200))
})
Specify("Check that Asset belongs to the second Owner", func() {
result := stub.MockInvoke("000", argsToReadAsset)
payload = []byte(result.Payload)
var asset Asset
json.Unmarshal(payload, &asset)
Expect(asset.OwnerId).Should(Equal(string(anotherMockOwner[0])))
})
})
})
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
12 | |
9 | |
7 | |
7 | |
7 | |
6 | |
6 | |
6 | |
6 | |
4 |