From 03d4190d5b33b6f56fcaff39c8826a04ffdbb714 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Mon, 13 Sep 2021 18:15:17 -0400 Subject: [PATCH 1/6] Use mockery for ContractStore mocks Signed-off-by: Andrew Richardson --- Makefile | 14 + go.sum | 1 + internal/contractgateway/rest2eth_test.go | 554 ++++++++++++------ .../contractgateway/smartcontractgw_test.go | 44 +- mocks/contractregistrymocks/contract_store.go | 183 ++++++ 5 files changed, 599 insertions(+), 197 deletions(-) create mode 100644 mocks/contractregistrymocks/contract_store.go diff --git a/Makefile b/Makefile index 62771fe6..6b49110f 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,9 @@ BINARY_UNIX=$(BINARY_NAME)-tux BINARY_MAC=$(BINARY_NAME)-mac BINARY_WIN=$(BINARY_NAME)-win +GOBIN := $(shell $(VGO) env GOPATH)/bin +MOCKERY := $(GOBIN)/mockery + .DELETE_ON_ERROR: GOFILES := $(shell find . -name '*.go' -print) @@ -45,3 +48,14 @@ build-mac: GOOS=darwin GOARCH=amd64 $(VGO) build -o $(BINARY_MAC) -v build-win: GOOS=windows GOARCH=amd64 $(VGO) build -o $(BINARY_WIN) -v + +${MOCKERY}: + $(VGO) install github.com/vektra/mockery/cmd/mockery@latest + +define makemock +mocks: mocks-$(strip $(1))-$(strip $(2)) +mocks-$(strip $(1))-$(strip $(2)): ${MOCKERY} + ${MOCKERY} --case underscore --dir $(1) --name $(2) --outpkg $(3) --output mocks/$(strip $(3)) +endef + +$(eval $(call makemock, internal/contractregistry, ContractStore, contractregistrymocks)) \ No newline at end of file diff --git a/go.sum b/go.sum index 67237f3e..1ae51fe5 100644 --- a/go.sum +++ b/go.sum @@ -871,6 +871,7 @@ github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3 github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v0.0.0-20170130113145-4d4bfba8f1d1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.1.4/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/internal/contractgateway/rest2eth_test.go b/internal/contractgateway/rest2eth_test.go index 3fc816be..5b156adb 100644 --- a/internal/contractgateway/rest2eth_test.go +++ b/internal/contractgateway/rest2eth_test.go @@ -32,6 +32,7 @@ import ( "github.com/hyperledger-labs/firefly-ethconnect/internal/ethbind" "github.com/hyperledger-labs/firefly-ethconnect/internal/events" "github.com/hyperledger-labs/firefly-ethconnect/internal/messages" + "github.com/hyperledger-labs/firefly-ethconnect/mocks/contractregistrymocks" "github.com/julienschmidt/httprouter" ethbinding "github.com/kaleido-io/ethbinding/pkg" log "github.com/sirupsen/logrus" @@ -75,34 +76,6 @@ func (m *mockREST2EthDispatcher) DispatchDeployContractSync(ctx context.Context, } } -type mockContractResolver struct { - loadABIError error - deployMsg *messages.DeployContract - abiInfo *contractregistry.ABIInfo - contractInfo *contractregistry.ContractInfo - registeredContractAddr string - resolveContractErr error - nameAvailableError error - capturedAddr string -} - -func (m *mockContractResolver) GetContractByAddress(addrHex string) (*contractregistry.ContractInfo, error) { - m.capturedAddr = addrHex - return m.contractInfo, m.loadABIError -} - -func (m *mockContractResolver) ResolveContractAddress(registeredName string) (string, error) { - return m.registeredContractAddr, m.resolveContractErr -} - -func (m *mockContractResolver) GetABIByID(addrHex string) (*messages.DeployContract, *contractregistry.ABIInfo, error) { - return m.deployMsg, m.abiInfo, m.loadABIError -} - -func (m *mockContractResolver) CheckNameAvailable(name string, isRemote bool) error { - return m.nameAvailableError -} - type mockGateway struct { postDeployError error } @@ -216,14 +189,10 @@ func newTestDeployMsg(t *testing.T, addr string) *contractregistry.DeployContrac } } -func newTestREST2Eth(t *testing.T, dispatcher *mockREST2EthDispatcher) (*rest2eth, *mockRPC, *httprouter.Router) { +func newTestREST2Eth(dispatcher *mockREST2EthDispatcher) (*rest2eth, *mockRPC, *httprouter.Router) { mockRPC := &mockRPC{} - deployMsg := newTestDeployMsg(t, "") gateway := &mockGateway{} - contractResolver := &mockContractResolver{ - contractInfo: &contractregistry.ContractInfo{}, - deployMsg: &deployMsg.DeployContract, - } + contractResolver := &contractregistrymocks.ContractStore{} mockProcessor := &mockProcessor{} r := newREST2eth(gateway, contractResolver, mockRPC, nil, nil, mockProcessor, dispatcher, dispatcher) router := &httprouter.Router{} @@ -232,53 +201,13 @@ func newTestREST2Eth(t *testing.T, dispatcher *mockREST2EthDispatcher) (*rest2et return r, mockRPC, router } -func newTestREST2EthCustomGateway(t *testing.T, dispatcher *mockREST2EthDispatcher, gateway *mockGateway) (*rest2eth, *mockRPC, *httprouter.Router) { - mockRPC := &mockRPC{} - deployMsg := newTestDeployMsg(t, "") - contractResolver := &mockContractResolver{ - contractInfo: &contractregistry.ContractInfo{}, - deployMsg: &deployMsg.DeployContract, - } - mockProcessor := &mockProcessor{} - r := newREST2eth(gateway, contractResolver, mockRPC, nil, nil, mockProcessor, dispatcher, dispatcher) - router := &httprouter.Router{} - r.addRoutes(router) - - return r, mockRPC, router -} - -func newTestREST2EthCustomContractResolver(dispatcher *mockREST2EthDispatcher, contractResolver *mockContractResolver) (*rest2eth, *mockRPC, *httprouter.Router) { - mockRPC := &mockRPC{} - gateway := &mockGateway{} - mockProcessor := &mockProcessor{} - r := newREST2eth(gateway, contractResolver, mockRPC, nil, nil, mockProcessor, dispatcher, dispatcher) - router := &httprouter.Router{} - r.addRoutes(router) - - return r, mockRPC, router -} - -func newTestREST2EthAndMsg(t *testing.T, dispatcher *mockREST2EthDispatcher, from, to string, bodyMap map[string]interface{}) (*rest2eth, *mockRPC, *httprouter.Router, *httptest.ResponseRecorder, *http.Request) { - body, _ := json.Marshal(&bodyMap) - req := httptest.NewRequest("POST", "/contracts/"+to+"/set", bytes.NewReader(body)) - req.Header.Add("x-firefly-from", from) - res := httptest.NewRecorder() - - r, mockRPC, router := newTestREST2Eth(t, dispatcher) - - return r, mockRPC, router, res, req -} - -func newTestREST2EthAndMsgPostDeployError(t *testing.T, dispatcher *mockREST2EthDispatcher, from, to string, bodyMap map[string]interface{}) (*rest2eth, *mockRPC, *httprouter.Router, *httptest.ResponseRecorder, *http.Request) { - gateway := &mockGateway{ - postDeployError: fmt.Errorf("pop"), - } +func newTestREST2EthAndMsg(dispatcher *mockREST2EthDispatcher, from, to string, bodyMap map[string]interface{}) (*rest2eth, *mockRPC, *httprouter.Router, *httptest.ResponseRecorder, *http.Request) { body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) res := httptest.NewRecorder() - r, mockRPC, router := newTestREST2EthCustomGateway(t, dispatcher, gateway) + r, mockRPC, router := newTestREST2Eth(dispatcher) return r, mockRPC, router, res, req } @@ -299,7 +228,12 @@ func TestSendTransactionAsyncSuccess(t *testing.T) { Request: "request1", }, } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req.Header.Set("X-Firefly-PrivateFrom", "0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90") req.Header.Set("X-Firefly-PrivateFor", "0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745,0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C") router.ServeHTTP(res, req) @@ -317,6 +251,8 @@ func TestSendTransactionAsyncSuccess(t *testing.T) { assert.Equal("0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90", dispatcher.asyncDispatchMsg["privateFrom"]) assert.Equal("0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745", dispatcher.asyncDispatchMsg["privateFor"].([]interface{})[0]) assert.Equal("0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", dispatcher.asyncDispatchMsg["privateFor"].([]interface{})[1]) + + mcr.AssertExpectations(t) } func TestDeployContractAsyncSuccess(t *testing.T) { @@ -334,7 +270,11 @@ func TestDeployContractAsyncSuccess(t *testing.T) { Request: "request1", }, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1?fly-privateFrom=0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90&fly-privateFor=0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745&fly-privateFor=0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -352,6 +292,8 @@ func TestDeployContractAsyncSuccess(t *testing.T) { assert.Equal("0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90", dispatcher.asyncDispatchMsg["privateFrom"]) assert.Equal("0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745", dispatcher.asyncDispatchMsg["privateFor"].([]interface{})[0]) assert.Equal("0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", dispatcher.asyncDispatchMsg["privateFor"].([]interface{})[1]) + + mcr.AssertExpectations(t) } func TestDeployContractAsyncHDWallet(t *testing.T) { @@ -369,7 +311,11 @@ func TestDeployContractAsyncHDWallet(t *testing.T) { Request: "request1", }, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -384,6 +330,8 @@ func TestDeployContractAsyncHDWallet(t *testing.T) { assert.Equal(true, dispatcher.asyncDispatchAck) assert.Equal(strings.ToLower(from), dispatcher.asyncDispatchMsg["from"]) + + mcr.AssertExpectations(t) } func TestDeployContractAsyncDuplicate(t *testing.T) { @@ -401,9 +349,12 @@ func TestDeployContractAsyncDuplicate(t *testing.T) { Request: "request1", }, } - r, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) - contractResolver := r.cr.(*mockContractResolver) - contractResolver.nameAvailableError = fmt.Errorf("spent already") + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "abi1").Return(&messages.DeployContract{}, nil, nil) + mcr.On("CheckNameAvailable", "random", false).Return(fmt.Errorf("spent already")) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1?fly-privateFrom=0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90&fly-privateFor=0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745&fly-privateFor=0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -414,6 +365,8 @@ func TestDeployContractAsyncDuplicate(t *testing.T) { var resBody map[string]interface{} json.NewDecoder(res.Body).Decode(&resBody) assert.Equal("spent already", resBody["error"]) + + mcr.AssertExpectations(t) } func TestSendTransactionSyncSuccess(t *testing.T) { @@ -438,7 +391,12 @@ func TestSendTransactionSyncSuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -449,6 +407,8 @@ func TestSendTransactionSyncSuccess(t *testing.T) { assert.Equal(200, res.Result().StatusCode) assert.Equal(from, dispatcher.sendTransactionMsg.From) assert.Equal(to, dispatcher.sendTransactionMsg.To) + + mcr.AssertExpectations(t) } func TestSendTransactionSyncFailure(t *testing.T) { @@ -473,7 +433,12 @@ func TestSendTransactionSyncFailure(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -484,6 +449,8 @@ func TestSendTransactionSyncFailure(t *testing.T) { assert.Equal(500, res.Result().StatusCode) assert.Equal(from, dispatcher.sendTransactionMsg.From) assert.Equal(to, dispatcher.sendTransactionMsg.To) + + mcr.AssertExpectations(t) } func TestSendTransactionSyncPostDeployErr(t *testing.T) { @@ -510,10 +477,19 @@ func TestSendTransactionSyncPostDeployErr(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } - _, _, router, res, _ := newTestREST2EthAndMsgPostDeployError(t, dispatcher, from, to, bodyMap) + + r, _, router := newTestREST2Eth(dispatcher) + r.gw = &mockGateway{ + postDeployError: fmt.Errorf("pop"), + } + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) + res := httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(json.Number("1234"), dispatcher.sendTransactionMsg.Value) @@ -522,6 +498,8 @@ func TestSendTransactionSyncPostDeployErr(t *testing.T) { assert.Equal(from, dispatcher.sendTransactionMsg.From) assert.Equal(to, dispatcher.sendTransactionMsg.To) assert.Equal(contractAddr, *dispatcher.sendTransactionSyncReceipt.ContractAddress) + + mcr.AssertExpectations(t) } func TestSendTransactionSyncViaABISuccess(t *testing.T) { @@ -547,7 +525,11 @@ func TestSendTransactionSyncViaABISuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", abi).Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/"+abi+"/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -558,6 +540,8 @@ func TestSendTransactionSyncViaABISuccess(t *testing.T) { assert.Equal(200, res.Result().StatusCode) assert.Equal(from, dispatcher.sendTransactionMsg.From) assert.Equal(to, dispatcher.sendTransactionMsg.To) + + mcr.AssertExpectations(t) } func TestDeployContractSyncSuccess(t *testing.T) { @@ -581,7 +565,11 @@ func TestDeployContractSyncSuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ deployContractSyncReceipt: receipt, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1?fly-sync", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -589,9 +577,11 @@ func TestDeployContractSyncSuccess(t *testing.T) { assert.Equal(200, res.Result().StatusCode) assert.Equal(from, dispatcher.deployContractMsg.From) + + mcr.AssertExpectations(t) } -func TestDeployContractSyncRemoteRegitryInstance(t *testing.T) { +func TestDeployContractSyncRemoteRegistryInstance(t *testing.T) { assert := assert.New(t) dir := tempdir() defer cleanup(dir) @@ -616,7 +606,7 @@ func TestDeployContractSyncRemoteRegitryInstance(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) r.rr = &mockRR{ deployMsg: newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), } @@ -636,7 +626,7 @@ func TestDeployContractSyncRemoteRegitryInstance500(t *testing.T) { defer cleanup(dir) bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(t, &mockREST2EthDispatcher{}, "", "", bodyMap) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) r.rr = &mockRR{ err: fmt.Errorf("pop"), } @@ -653,7 +643,7 @@ func TestDeployContractSyncRemoteRegitryInstance404(t *testing.T) { defer cleanup(dir) bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(t, &mockREST2EthDispatcher{}, "", "", bodyMap) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) r.rr = &mockRR{} body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/instances/myinstance/set?fly-sync", bytes.NewReader(body)) @@ -668,7 +658,7 @@ func TestDeployContractSyncRemoteRegitryGateway500(t *testing.T) { defer cleanup(dir) bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(t, &mockREST2EthDispatcher{}, "", "", bodyMap) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) r.rr = &mockRR{ err: fmt.Errorf("pop"), } @@ -685,7 +675,7 @@ func TestDeployContractSyncRemoteRegitryGateway404(t *testing.T) { defer cleanup(dir) bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(t, &mockREST2EthDispatcher{}, "", "", bodyMap) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) r.rr = &mockRR{} body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/g/mygw?fly-sync", bytes.NewReader(body)) @@ -716,7 +706,7 @@ func TestDeployContractSyncRemoteRegistryGateway(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) r.rr = &mockRR{ deployMsg: newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), } @@ -743,7 +733,12 @@ func TestSendTransactionSyncFail(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncError: fmt.Errorf("pop"), } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req.Header.Set("x-firefly-sync", "true") router.ServeHTTP(res, req) @@ -752,6 +747,8 @@ func TestSendTransactionSyncFail(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionAsyncFail(t *testing.T) { @@ -767,7 +764,12 @@ func TestSendTransactionAsyncFail(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ asyncDispatchError: fmt.Errorf("pop"), } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -775,6 +777,8 @@ func TestSendTransactionAsyncFail(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } func TestDeployContractAsyncFail(t *testing.T) { @@ -789,7 +793,11 @@ func TestDeployContractAsyncFail(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ asyncDispatchError: fmt.Errorf("pop"), } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -800,6 +808,8 @@ func TestDeployContractAsyncFail(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionAsyncBadMethod(t *testing.T) { @@ -815,7 +825,12 @@ func TestSendTransactionAsyncBadMethod(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ asyncDispatchError: fmt.Errorf("pop"), } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -823,7 +838,10 @@ func TestSendTransactionAsyncBadMethod(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } + func TestSendTransactionBadContract(t *testing.T) { assert := assert.New(t) dir := tempdir() @@ -837,7 +855,13 @@ func TestSendTransactionBadContract(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ asyncDispatchError: fmt.Errorf("pop"), } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("ResolveContractAddress", "badness").Return("my-contract", nil) + mcr.On("GetContractByAddress", "my-contract").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -845,6 +869,8 @@ func TestSendTransactionBadContract(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionUnknownRegisteredName(t *testing.T) { @@ -858,9 +884,11 @@ func TestSendTransactionUnknownRegisteredName(t *testing.T) { to := "random" from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{} - r, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) - contractResolver := r.cr.(*mockContractResolver) - contractResolver.resolveContractErr = fmt.Errorf("unregistered") + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("ResolveContractAddress", "random").Return("", fmt.Errorf("unregistered")) + router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) @@ -868,6 +896,8 @@ func TestSendTransactionUnknownRegisteredName(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("unregistered", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionMissingContract(t *testing.T) { @@ -883,7 +913,12 @@ func TestSendTransactionMissingContract(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ asyncDispatchError: fmt.Errorf("pop"), } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + router.ServeHTTP(res, req) assert.Equal(400, res.Result().StatusCode) @@ -891,6 +926,8 @@ func TestSendTransactionMissingContract(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Please specify a valid address in the 'fly-from' query string parameter or x-firefly-from HTTP header", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionBadMethodABI(t *testing.T) { @@ -903,9 +940,13 @@ func TestSendTransactionBadMethodABI(t *testing.T) { Request: "request1", }, } - contractResolver := &mockContractResolver{ - contractInfo: &contractregistry.ContractInfo{}, - deployMsg: &messages.DeployContract{ + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8"). + Return(&contractregistry.ContractInfo{ABI: "abi-id"}, nil) + mcr.On("GetABIByID", "abi-id"). + Return(&messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "badmethod", Type: "function", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -913,9 +954,8 @@ func TestSendTransactionBadMethodABI(t *testing.T) { }, }, }, - }, - } - _, _, router := newTestREST2EthCustomContractResolver(dispatcher, contractResolver) + }, &contractregistry.ABIInfo{}, nil) + req := httptest.NewRequest("GET", "/contracts/0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8/badmethod", bytes.NewReader([]byte{})) req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() @@ -925,6 +965,8 @@ func TestSendTransactionBadMethodABI(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Invalid method 'badmethod' in ABI: unsupported arg type: badness", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionBadEventABI(t *testing.T) { @@ -937,9 +979,13 @@ func TestSendTransactionBadEventABI(t *testing.T) { Request: "request1", }, } - contractResolver := &mockContractResolver{ - contractInfo: &contractregistry.ContractInfo{}, - deployMsg: &messages.DeployContract{ + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8"). + Return(&contractregistry.ContractInfo{ABI: "abi-id"}, nil) + mcr.On("GetABIByID", "abi-id"). + Return(&messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "badevent", Type: "event", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -947,9 +993,8 @@ func TestSendTransactionBadEventABI(t *testing.T) { }, }, }, - }, - } - _, _, router := newTestREST2EthCustomContractResolver(dispatcher, contractResolver) + }, &contractregistry.ABIInfo{}, nil) + req := httptest.NewRequest("POST", "/contracts/0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8/badevent/subscribe", bytes.NewReader([]byte{})) req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() @@ -959,6 +1004,8 @@ func TestSendTransactionBadEventABI(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Invalid event 'badevent' in ABI: unsupported arg type: badness", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionBadConstructorABI(t *testing.T) { @@ -971,9 +1018,11 @@ func TestSendTransactionBadConstructorABI(t *testing.T) { Request: "request1", }, } - contractResolver := &mockContractResolver{ - contractInfo: &contractregistry.ContractInfo{}, - deployMsg: &messages.DeployContract{ + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "testabi"). + Return(&messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "badevent", Type: "constructor", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -981,9 +1030,8 @@ func TestSendTransactionBadConstructorABI(t *testing.T) { }, }, }, - }, - } - _, _, router := newTestREST2EthCustomContractResolver(dispatcher, contractResolver) + }, &contractregistry.ABIInfo{}, nil) + req := httptest.NewRequest("POST", "/abis/testabi", bytes.NewReader([]byte{})) req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() @@ -993,6 +1041,8 @@ func TestSendTransactionBadConstructorABI(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Invalid method 'constructor' in ABI: unsupported arg type: badness", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionDefaultConstructorABI(t *testing.T) { @@ -1005,18 +1055,21 @@ func TestSendTransactionDefaultConstructorABI(t *testing.T) { Request: "request1", }, } - contractResolver := &mockContractResolver{ - contractInfo: &contractregistry.ContractInfo{}, - deployMsg: &messages.DeployContract{ + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "testabi"). + Return(&messages.DeployContract{ ABI: ethbinding.ABIMarshaling{}, // completely empty ABI is ok - }, - } - _, _, router := newTestREST2EthCustomContractResolver(dispatcher, contractResolver) + }, &contractregistry.ABIInfo{}, nil) + req := httptest.NewRequest("POST", "/abis/testabi", bytes.NewReader([]byte{})) req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") res := httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) + + mcr.AssertExpectations(t) } func TestSendTransactionUnnamedParamsABI(t *testing.T) { @@ -1029,9 +1082,11 @@ func TestSendTransactionUnnamedParamsABI(t *testing.T) { Request: "request1", }, } - contractResolver := &mockContractResolver{ - contractInfo: &contractregistry.ContractInfo{}, - deployMsg: &messages.DeployContract{ + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "testabi"). + Return(&messages.DeployContract{ ABI: ethbinding.ABIMarshaling{ { Name: "unnamedparamsmethod", Type: "function", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -1040,9 +1095,8 @@ func TestSendTransactionUnnamedParamsABI(t *testing.T) { }, }, }, - }, - } - _, _, router := newTestREST2EthCustomContractResolver(dispatcher, contractResolver) + }, &contractregistry.ABIInfo{}, nil) + req := httptest.NewRequest("POST", "/abis/testabi/0x29fb3f4f7cc82a1456903a506e88cdd63b1d74e8/unnamedparamsmethod", bytes.NewReader([]byte{})) req.Header.Add("x-firefly-from", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") q := req.URL.Query() @@ -1052,6 +1106,8 @@ func TestSendTransactionUnnamedParamsABI(t *testing.T) { res := httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) + + mcr.AssertExpectations(t) } func TestSendTransactionBadFrom(t *testing.T) { @@ -1067,7 +1123,12 @@ func TestSendTransactionBadFrom(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ asyncDispatchError: fmt.Errorf("pop"), } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) @@ -1075,6 +1136,8 @@ func TestSendTransactionBadFrom(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("From Address must be a 40 character hex string (0x prefix is optional)", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionInvalidContract(t *testing.T) { @@ -1092,9 +1155,11 @@ func TestSendTransactionInvalidContract(t *testing.T) { Request: "request1", }, } - r, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) - contractResolver := r.cr.(*mockContractResolver) - contractResolver.loadABIError = fmt.Errorf("pop") + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(nil, fmt.Errorf("pop")) + router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) @@ -1102,6 +1167,8 @@ func TestSendTransactionInvalidContract(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } func TestDeployContractInvalidABI(t *testing.T) { @@ -1119,12 +1186,15 @@ func TestDeployContractInvalidABI(t *testing.T) { Request: "request1", }, } - r, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, "", bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1?fly-sync", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) - contractResolver := r.cr.(*mockContractResolver) - contractResolver.loadABIError = fmt.Errorf("pop") + + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "abi1").Return(nil, nil, fmt.Errorf("pop")) + router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) @@ -1132,7 +1202,10 @@ func TestDeployContractInvalidABI(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } + func TestSendTransactionInvalidMethod(t *testing.T) { assert := assert.New(t) dir := tempdir() @@ -1149,7 +1222,12 @@ func TestSendTransactionInvalidMethod(t *testing.T) { Request: "request1", }, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req := httptest.NewRequest("POST", "/contracts/"+to+"/shazaam", bytes.NewReader([]byte("{}"))) req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) @@ -1159,6 +1237,8 @@ func TestSendTransactionInvalidMethod(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Method or Event 'shazaam' is not declared in the ABI of contract '567a417717cb6c59ddc1035705f02c0fd1ab1872'", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionParamInQuery(t *testing.T) { @@ -1175,12 +1255,19 @@ func TestSendTransactionParamInQuery(t *testing.T) { Request: "request1", }, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&fly-ethvalue=12345", bytes.NewReader([]byte("{}"))) req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) assert.Equal(202, res.Result().StatusCode) + + mcr.AssertExpectations(t) } func TestSendTransactionRegisteredName(t *testing.T) { @@ -1197,16 +1284,22 @@ func TestSendTransactionRegisteredName(t *testing.T) { Request: "request1", }, } - r, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) - contractResolver := r.cr.(*mockContractResolver) - contractResolver.registeredContractAddr = "c6c572a18d31ff36d661d680c0060307e038dc47" + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("ResolveContractAddress", "transponster").Return("c6c572a18d31ff36d661d680c0060307e038dc47", nil) + mcr.On("GetContractByAddress", "c6c572a18d31ff36d661d680c0060307e038dc47").Return(&contractregistry.ContractInfo{ABI: "abi-id"}, nil) + mcr.On("GetABIByID", "abi-id").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&fly-ethvalue=12345", bytes.NewReader([]byte("{}"))) req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) - assert.Equal("c6c572a18d31ff36d661d680c0060307e038dc47", contractResolver.capturedAddr) assert.Equal(202, res.Result().StatusCode) + + mcr.AssertExpectations(t) } + func TestSendTransactionMissingParam(t *testing.T) { assert := assert.New(t) dir := tempdir() @@ -1221,7 +1314,12 @@ func TestSendTransactionMissingParam(t *testing.T) { Request: "request1", }, } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + router.ServeHTTP(res, req) assert.Equal(400, res.Result().StatusCode) @@ -1229,6 +1327,8 @@ func TestSendTransactionMissingParam(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Parameter 'i' of method 'set' was not specified in body or query parameters", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionBadBody(t *testing.T) { @@ -1245,7 +1345,12 @@ func TestSendTransactionBadBody(t *testing.T) { Request: "request1", }, } - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req := httptest.NewRequest("POST", "/contracts/"+to+"/set?x=999", bytes.NewReader([]byte(":not json or yaml"))) req.Header.Set("x-firefly-from", from) router.ServeHTTP(res, req) @@ -1255,6 +1360,8 @@ func TestSendTransactionBadBody(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Regexp("Unable to parse as YAML or JSON", reply.Message) + + mcr.AssertExpectations(t) } func TestCallMethodSuccess(t *testing.T) { @@ -1265,7 +1372,12 @@ func TestCallMethodSuccess(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} - _, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req := httptest.NewRequest("GET", "/contracts/"+to+"/get", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) @@ -1280,6 +1392,8 @@ func TestCallMethodSuccess(t *testing.T) { assert.Nil(reply["error"]) assert.Equal("123456", reply["i"]) assert.Equal("testing", reply["s"]) + + mcr.AssertExpectations(t) } func TestCallMethodHDWalletSuccess(t *testing.T) { @@ -1291,7 +1405,12 @@ func TestCallMethodHDWalletSuccess(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} from := "HD-u01234abcd-u01234abcd-12345" - r, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + r.processor.(*mockProcessor).resolvedFrom = "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" req := httptest.NewRequest("GET", "/contracts/"+to+"/get?fly-from="+from, bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" @@ -1307,6 +1426,8 @@ func TestCallMethodHDWalletSuccess(t *testing.T) { assert.Nil(reply["error"]) assert.Equal("123456", reply["i"]) assert.Equal("testing", reply["s"]) + + mcr.AssertExpectations(t) } func TestCallMethodHDWalletFail(t *testing.T) { @@ -1318,7 +1439,12 @@ func TestCallMethodHDWalletFail(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} from := "HD-u01234abcd-u01234abcd-12345" - r, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + r.processor.(*mockProcessor).resolvedFrom = "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" r.processor.(*mockProcessor).err = fmt.Errorf("pop") req := httptest.NewRequest("GET", "/contracts/"+to+"/get?fly-from="+from, bytes.NewReader([]byte{})) @@ -1329,6 +1455,8 @@ func TestCallMethodHDWalletFail(t *testing.T) { var reply map[string]interface{} json.NewDecoder(res.Result().Body).Decode(&reply) assert.Equal("pop", reply["error"]) + + mcr.AssertExpectations(t) } func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { @@ -1339,7 +1467,12 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} - _, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req := httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=12345", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) @@ -1355,9 +1488,16 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { assert.Equal("123456", reply["i"]) assert.Equal("testing", reply["s"]) + mcr.AssertExpectations(t) + to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} - _, mockRPC, router, res, _ = newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr = r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=0xab1234", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) @@ -1365,15 +1505,24 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { assert.Equal("eth_call", mockRPC.capturedMethod) assert.Equal("0xab1234", mockRPC.capturedArgs[1]) + mcr.AssertExpectations(t) + to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} - _, mockRPC, router, res, _ = newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr = r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=pending", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) assert.Equal("eth_call", mockRPC.capturedMethod) assert.Equal("pending", mockRPC.capturedArgs[1]) + + mcr.AssertExpectations(t) } func TestCallMethodFail(t *testing.T) { @@ -1383,7 +1532,12 @@ func TestCallMethodFail(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} - _, mockRPC, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + mockRPC.result = "" mockRPC.mockError = fmt.Errorf("pop") req := httptest.NewRequest("GET", "/contracts/"+to+"/get", bytes.NewReader([]byte{})) @@ -1395,13 +1549,22 @@ func TestCallMethodFail(t *testing.T) { assert.NoError(err) assert.Regexp("Call failed: pop", reply.Message) + mcr.AssertExpectations(t) + to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} - _, mockRPC, router, res, _ = newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, mockRPC, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr = r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=ab1234", bytes.NewReader([]byte{})) mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) + + mcr.AssertExpectations(t) } func TestCallMethodViaABIBadAddress(t *testing.T) { @@ -1411,7 +1574,11 @@ func TestCallMethodViaABIBadAddress(t *testing.T) { to := "badness" dispatcher := &mockREST2EthDispatcher{} - _, _, router, res, _ := newTestREST2EthAndMsg(t, dispatcher, "", to, map[string]interface{}{}) + + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req := httptest.NewRequest("GET", "/abis/ABI1/badaddress/get", bytes.NewReader([]byte{})) router.ServeHTTP(res, req) @@ -1420,6 +1587,8 @@ func TestCallMethodViaABIBadAddress(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("To Address must be a 40 character hex string (0x prefix is optional)", reply.Message) + + mcr.AssertExpectations(t) } func TestSubscribeNoAddressNoSubMgr(t *testing.T) { @@ -1428,7 +1597,11 @@ func TestSubscribeNoAddressNoSubMgr(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - _, _, router := newTestREST2Eth(t, dispatcher) + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + bodyBytes, _ := json.Marshal(&map[string]string{ "stream": "stream1", }) @@ -1441,6 +1614,8 @@ func TestSubscribeNoAddressNoSubMgr(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Event support is not configured on this gateway", reply.Message) + + mcr.AssertExpectations(t) } func TestSubscribeNoAddressUnknownEvent(t *testing.T) { @@ -1449,7 +1624,11 @@ func TestSubscribeNoAddressUnknownEvent(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - _, _, router := newTestREST2Eth(t, dispatcher) + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + bodyBytes, _ := json.Marshal(&map[string]string{ "stream": "stream1", }) @@ -1462,6 +1641,8 @@ func TestSubscribeNoAddressUnknownEvent(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Event 'subscribe' is not declared in the ABI", reply.Message) + + mcr.AssertExpectations(t) } func TestSubscribeUnauthorized(t *testing.T) { @@ -1472,7 +1653,10 @@ func TestSubscribeUnauthorized(t *testing.T) { auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) dispatcher := &mockREST2EthDispatcher{} - _, _, router := newTestREST2Eth(t, dispatcher) + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + bodyBytes, _ := json.Marshal(&map[string]string{ "stream": "stream1", }) @@ -1487,6 +1671,7 @@ func TestSubscribeUnauthorized(t *testing.T) { assert.Equal("Unauthorized", reply.Message) auth.RegisterSecurityModule(nil) + mcr.AssertExpectations(t) } func TestSubscribeNoAddressMissingStream(t *testing.T) { @@ -1495,7 +1680,10 @@ func TestSubscribeNoAddressMissingStream(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(t, dispatcher) + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + r.subMgr = &mockSubMgr{} bodyBytes, _ := json.Marshal(&map[string]string{}) req := httptest.NewRequest("POST", "/abis/ABI1/Changed/subscribe", bytes.NewReader(bodyBytes)) @@ -1507,6 +1695,8 @@ func TestSubscribeNoAddressMissingStream(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("Must supply a 'stream' parameter in the body or query", reply.Message) + + mcr.AssertExpectations(t) } func TestSubscribeNoAddressSuccess(t *testing.T) { @@ -1515,7 +1705,10 @@ func TestSubscribeNoAddressSuccess(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(t, dispatcher) + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + sm := &mockSubMgr{ sub: &events.SubscriptionInfo{ID: "sub1", Name: "stream-without-address"}, } @@ -1534,6 +1727,8 @@ func TestSubscribeNoAddressSuccess(t *testing.T) { assert.Equal("sub1", reply.ID) assert.Equal("stream-without-address", reply.Name) assert.Nil(sm.capturedAddr) + + mcr.AssertExpectations(t) } func TestSubscribeWithAddressSuccess(t *testing.T) { @@ -1542,7 +1737,11 @@ func TestSubscribeWithAddressSuccess(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(t, dispatcher) + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + sm := &mockSubMgr{ sub: &events.SubscriptionInfo{ID: "sub1"}, } @@ -1560,6 +1759,8 @@ func TestSubscribeWithAddressSuccess(t *testing.T) { assert.NoError(err) assert.Equal("sub1", reply.ID) assert.Equal("0x66C5fE653e7A9EBB628a6D40f0452d1e358BaEE8", sm.capturedAddr.Hex()) + + mcr.AssertExpectations(t) } func TestSubscribeWithAddressBadAddress(t *testing.T) { @@ -1568,9 +1769,11 @@ func TestSubscribeWithAddressBadAddress(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(t, dispatcher) - contractResolver := r.cr.(*mockContractResolver) - contractResolver.resolveContractErr = fmt.Errorf("unregistered") + + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("ResolveContractAddress", "badness").Return("", fmt.Errorf("unregistered")) + r.subMgr = &mockSubMgr{ sub: &events.SubscriptionInfo{ID: "sub1"}, } @@ -1586,6 +1789,8 @@ func TestSubscribeWithAddressBadAddress(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("unregistered", reply.Message) + + mcr.AssertExpectations(t) } func TestSubscribeWithAddressSubmgrFailure(t *testing.T) { @@ -1594,7 +1799,11 @@ func TestSubscribeWithAddressSubmgrFailure(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(t, dispatcher) + r, _, router := newTestREST2Eth(dispatcher) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + r.subMgr = &mockSubMgr{ err: fmt.Errorf("pop"), } @@ -1610,6 +1819,8 @@ func TestSubscribeWithAddressSubmgrFailure(t *testing.T) { err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) assert.Equal("pop", reply.Message) + + mcr.AssertExpectations(t) } func TestSendTransactionWithIDAsyncSuccess(t *testing.T) { @@ -1628,7 +1839,12 @@ func TestSendTransactionWithIDAsyncSuccess(t *testing.T) { Request: "request1", }, } - _, _, router, res, req := newTestREST2EthAndMsg(t, dispatcher, from, to, bodyMap) + + r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + mcr := r.cr.(*contractregistrymocks.ContractStore) + mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + req.Header.Set("X-Firefly-PrivateFrom", "0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90") req.Header.Set("X-Firefly-PrivateFor", "0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745,0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C") req.Header.Set("X-Firefly-ID", "my-id") @@ -1648,4 +1864,6 @@ func TestSendTransactionWithIDAsyncSuccess(t *testing.T) { assert.Equal("0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745", dispatcher.asyncDispatchMsg["privateFor"].([]interface{})[0]) assert.Equal("0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", dispatcher.asyncDispatchMsg["privateFor"].([]interface{})[1]) assert.Equal("my-id", dispatcher.asyncDispatchMsg["headers"].(map[string]interface{})["id"]) + + mcr.AssertExpectations(t) } diff --git a/internal/contractgateway/smartcontractgw_test.go b/internal/contractgateway/smartcontractgw_test.go index d0078ca7..2331f490 100644 --- a/internal/contractgateway/smartcontractgw_test.go +++ b/internal/contractgateway/smartcontractgw_test.go @@ -37,6 +37,7 @@ import ( "github.com/hyperledger-labs/firefly-ethconnect/internal/events" "github.com/hyperledger-labs/firefly-ethconnect/internal/messages" "github.com/hyperledger-labs/firefly-ethconnect/internal/tx" + "github.com/hyperledger-labs/firefly-ethconnect/mocks/contractregistrymocks" "github.com/julienschmidt/httprouter" ethbinding "github.com/kaleido-io/ethbinding/pkg" log "github.com/sirupsen/logrus" @@ -56,25 +57,6 @@ func (m *mockWebSocketServer) SendReply(message interface{}) { m.testChan <- message } -type mockContractStore struct { - mockContractResolver -} - -func (cs *mockContractStore) Init() { -} -func (cs *mockContractStore) AddContract(addrHexNo0x, abiID, pathName, registerAs string) (*contractregistry.ContractInfo, error) { - return nil, nil -} -func (cs *mockContractStore) AddABI(id string, deployMsg *messages.DeployContract, createdTime time.Time) *contractregistry.ABIInfo { - return nil -} -func (cs *mockContractStore) ListContracts() []messages.TimeSortable { - return []messages.TimeSortable{} -} -func (cs *mockContractStore) ListABIs() []messages.TimeSortable { - return []messages.TimeSortable{} -} - type SolcJson struct { ABI string `json:"abi"` Bin string `json:"bin"` @@ -834,14 +816,13 @@ func TestGetContractOrABIFail(t *testing.T) { }, nil, nil, nil, nil, ) - cs := &mockContractStore{} + mcs := &contractregistrymocks.ContractStore{} scgw := s.(*smartContractGW) - scgw.cs = cs - - cs.mockContractResolver.loadABIError = fmt.Errorf("pop") - cs.mockContractResolver.resolveContractErr = fmt.Errorf("pop") + scgw.cs = mcs // Contract that does not exist in the index + mcs.On("GetContractByAddress", "nonexistent").Return(nil, fmt.Errorf("pop")).Once() + mcs.On("ResolveContractAddress", "nonexistent").Return("", fmt.Errorf("pop")).Once() req := httptest.NewRequest("GET", "/contracts/nonexistent?openapi", bytes.NewReader([]byte{})) res := httptest.NewRecorder() router := &httprouter.Router{} @@ -850,12 +831,15 @@ func TestGetContractOrABIFail(t *testing.T) { assert.Equal(404, res.Result().StatusCode) // ABI that does not exist in the index + mcs.On("GetABIByID", "23456789abcdef0123456789abcdef0123456789").Return(nil, nil, fmt.Errorf("pop")).Once() req = httptest.NewRequest("GET", "/abis/23456789abcdef0123456789abcdef0123456789?openapi", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router = &httprouter.Router{} scgw.AddRoutes(router) router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) + + mcs.AssertExpectations(t) } func TestGetContractUI(t *testing.T) { @@ -872,15 +856,15 @@ func TestGetContractUI(t *testing.T) { }, nil, nil, nil, nil, ) - cs := &mockContractStore{} + mcs := &contractregistrymocks.ContractStore{} scgw := s.(*smartContractGW) - scgw.cs = cs + scgw.cs = mcs - cs.contractInfo = &contractregistry.ContractInfo{ + mcs.On("GetContractByAddress", "123456789abcdef0123456789abcdef012345678").Return(&contractregistry.ContractInfo{ ABI: "abi1", Address: "123456789abcdef0123456789abcdef012345678", - } - cs.deployMsg = &messages.DeployContract{} + }, nil) + mcs.On("GetABIByID", "abi1").Return(&messages.DeployContract{}, nil, nil) req := httptest.NewRequest("GET", "/contracts/123456789abcdef0123456789abcdef012345678?ui", bytes.NewReader([]byte{})) res := httptest.NewRecorder() @@ -890,6 +874,8 @@ func TestGetContractUI(t *testing.T) { assert.Equal(200, res.Result().StatusCode) body, _ := ioutil.ReadAll(res.Body) assert.Regexp("Ethconnect REST Gateway", string(body)) + + mcs.AssertExpectations(t) } func TestAddABISingleSolidity(t *testing.T) { diff --git a/mocks/contractregistrymocks/contract_store.go b/mocks/contractregistrymocks/contract_store.go new file mode 100644 index 00000000..b483f1e8 --- /dev/null +++ b/mocks/contractregistrymocks/contract_store.go @@ -0,0 +1,183 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package contractregistrymocks + +import ( + contractregistry "github.com/hyperledger-labs/firefly-ethconnect/internal/contractregistry" + messages "github.com/hyperledger-labs/firefly-ethconnect/internal/messages" + + mock "github.com/stretchr/testify/mock" + + time "time" +) + +// ContractStore is an autogenerated mock type for the ContractStore type +type ContractStore struct { + mock.Mock +} + +// AddABI provides a mock function with given fields: id, deployMsg, createdTime +func (_m *ContractStore) AddABI(id string, deployMsg *messages.DeployContract, createdTime time.Time) *contractregistry.ABIInfo { + ret := _m.Called(id, deployMsg, createdTime) + + var r0 *contractregistry.ABIInfo + if rf, ok := ret.Get(0).(func(string, *messages.DeployContract, time.Time) *contractregistry.ABIInfo); ok { + r0 = rf(id, deployMsg, createdTime) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*contractregistry.ABIInfo) + } + } + + return r0 +} + +// AddContract provides a mock function with given fields: addrHexNo0x, abiID, pathName, registerAs +func (_m *ContractStore) AddContract(addrHexNo0x string, abiID string, pathName string, registerAs string) (*contractregistry.ContractInfo, error) { + ret := _m.Called(addrHexNo0x, abiID, pathName, registerAs) + + var r0 *contractregistry.ContractInfo + if rf, ok := ret.Get(0).(func(string, string, string, string) *contractregistry.ContractInfo); ok { + r0 = rf(addrHexNo0x, abiID, pathName, registerAs) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*contractregistry.ContractInfo) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, string, string, string) error); ok { + r1 = rf(addrHexNo0x, abiID, pathName, registerAs) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CheckNameAvailable provides a mock function with given fields: name, isRemote +func (_m *ContractStore) CheckNameAvailable(name string, isRemote bool) error { + ret := _m.Called(name, isRemote) + + var r0 error + if rf, ok := ret.Get(0).(func(string, bool) error); ok { + r0 = rf(name, isRemote) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// GetABIByID provides a mock function with given fields: abi +func (_m *ContractStore) GetABIByID(abi string) (*messages.DeployContract, *contractregistry.ABIInfo, error) { + ret := _m.Called(abi) + + var r0 *messages.DeployContract + if rf, ok := ret.Get(0).(func(string) *messages.DeployContract); ok { + r0 = rf(abi) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*messages.DeployContract) + } + } + + var r1 *contractregistry.ABIInfo + if rf, ok := ret.Get(1).(func(string) *contractregistry.ABIInfo); ok { + r1 = rf(abi) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*contractregistry.ABIInfo) + } + } + + var r2 error + if rf, ok := ret.Get(2).(func(string) error); ok { + r2 = rf(abi) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// GetContractByAddress provides a mock function with given fields: addrHex +func (_m *ContractStore) GetContractByAddress(addrHex string) (*contractregistry.ContractInfo, error) { + ret := _m.Called(addrHex) + + var r0 *contractregistry.ContractInfo + if rf, ok := ret.Get(0).(func(string) *contractregistry.ContractInfo); ok { + r0 = rf(addrHex) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*contractregistry.ContractInfo) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(addrHex) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Init provides a mock function with given fields: +func (_m *ContractStore) Init() { + _m.Called() +} + +// ListABIs provides a mock function with given fields: +func (_m *ContractStore) ListABIs() []messages.TimeSortable { + ret := _m.Called() + + var r0 []messages.TimeSortable + if rf, ok := ret.Get(0).(func() []messages.TimeSortable); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]messages.TimeSortable) + } + } + + return r0 +} + +// ListContracts provides a mock function with given fields: +func (_m *ContractStore) ListContracts() []messages.TimeSortable { + ret := _m.Called() + + var r0 []messages.TimeSortable + if rf, ok := ret.Get(0).(func() []messages.TimeSortable); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]messages.TimeSortable) + } + } + + return r0 +} + +// ResolveContractAddress provides a mock function with given fields: registeredName +func (_m *ContractStore) ResolveContractAddress(registeredName string) (string, error) { + ret := _m.Called(registeredName) + + var r0 string + if rf, ok := ret.Get(0).(func(string) string); ok { + r0 = rf(registeredName) + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(registeredName) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} From d666804f09914c69c3967a96652e14b4a1dfa7c0 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Tue, 14 Sep 2021 10:34:16 -0400 Subject: [PATCH 2/6] Use mockery for RemoteRegistry mocks Signed-off-by: Andrew Richardson --- Makefile | 3 +- internal/contractgateway/rest2eth_test.go | 93 +++++++++--------- .../contractgateway/smartcontractgw_test.go | 52 +++++----- .../contractregistrymocks/remote_registry.go | 94 +++++++++++++++++++ 4 files changed, 171 insertions(+), 71 deletions(-) create mode 100644 mocks/contractregistrymocks/remote_registry.go diff --git a/Makefile b/Makefile index 6b49110f..503706a7 100644 --- a/Makefile +++ b/Makefile @@ -58,4 +58,5 @@ mocks-$(strip $(1))-$(strip $(2)): ${MOCKERY} ${MOCKERY} --case underscore --dir $(1) --name $(2) --outpkg $(3) --output mocks/$(strip $(3)) endef -$(eval $(call makemock, internal/contractregistry, ContractStore, contractregistrymocks)) \ No newline at end of file +$(eval $(call makemock, internal/contractregistry, ContractStore, contractregistrymocks)) +$(eval $(call makemock, internal/contractregistry, RemoteRegistry, contractregistrymocks)) diff --git a/internal/contractgateway/rest2eth_test.go b/internal/contractgateway/rest2eth_test.go index 5b156adb..bb19c350 100644 --- a/internal/contractgateway/rest2eth_test.go +++ b/internal/contractgateway/rest2eth_test.go @@ -150,36 +150,6 @@ func (m *mockSubMgr) ResetSubscription(ctx context.Context, id, initialBlock str } func (m *mockSubMgr) Close() {} -type mockRR struct { - idCapture string - addrCapture string - lookupCapture string - refreshCapture bool - deployMsg *contractregistry.DeployContractWithAddress - err error -} - -func (rr *mockRR) LoadFactoryForGateway(id string, refresh bool) (*messages.DeployContract, error) { - rr.idCapture = id - rr.refreshCapture = refresh - if rr.deployMsg == nil { - return nil, rr.err - } - return &rr.deployMsg.DeployContract, rr.err -} -func (rr *mockRR) LoadFactoryForInstance(id string, refresh bool) (*contractregistry.DeployContractWithAddress, error) { - rr.addrCapture = id - rr.refreshCapture = refresh - return rr.deployMsg, rr.err -} -func (rr *mockRR) RegisterInstance(lookupStr, address string) error { - rr.lookupCapture = lookupStr - rr.addrCapture = address - return rr.err -} -func (rr *mockRR) Close() {} -func (rr *mockRR) Init() error { return nil } - func newTestDeployMsg(t *testing.T, addr string) *contractregistry.DeployContractWithAddress { compiled, err := eth.CompileContract(simpleEventsSource(), "SimpleEvents", "", "") assert.NoError(t, err) @@ -193,8 +163,9 @@ func newTestREST2Eth(dispatcher *mockREST2EthDispatcher) (*rest2eth, *mockRPC, * mockRPC := &mockRPC{} gateway := &mockGateway{} contractResolver := &contractregistrymocks.ContractStore{} + remoteRegistry := &contractregistrymocks.RemoteRegistry{} mockProcessor := &mockProcessor{} - r := newREST2eth(gateway, contractResolver, mockRPC, nil, nil, mockProcessor, dispatcher, dispatcher) + r := newREST2eth(gateway, contractResolver, mockRPC, nil, remoteRegistry, mockProcessor, dispatcher, dispatcher) router := &httprouter.Router{} r.addRoutes(router) @@ -606,10 +577,12 @@ func TestDeployContractSyncRemoteRegistryInstance(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) - r.rr = &mockRR{ - deployMsg: newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), - } + mrr := r.rr.(*contractregistrymocks.RemoteRegistry) + mrr.On("LoadFactoryForInstance", "myinstance", false). + Return(newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/instances/myinstance/set?fly-sync", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -618,70 +591,88 @@ func TestDeployContractSyncRemoteRegistryInstance(t *testing.T) { assert.Equal(200, res.Result().StatusCode) assert.Equal(to, dispatcher.sendTransactionMsg.To) assert.Equal(from, dispatcher.sendTransactionMsg.From) + + mrr.AssertExpectations(t) } -func TestDeployContractSyncRemoteRegitryInstance500(t *testing.T) { +func TestDeployContractSyncRemoteRegistryInstance500(t *testing.T) { assert := assert.New(t) dir := tempdir() defer cleanup(dir) bodyMap := make(map[string]interface{}) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) - r.rr = &mockRR{ - err: fmt.Errorf("pop"), - } + mrr := r.rr.(*contractregistrymocks.RemoteRegistry) + mrr.On("LoadFactoryForInstance", "myinstance", false).Return(nil, fmt.Errorf("pop")) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/instances/myinstance/set?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) + + mrr.AssertExpectations(t) } -func TestDeployContractSyncRemoteRegitryInstance404(t *testing.T) { +func TestDeployContractSyncRemoteRegistryInstance404(t *testing.T) { assert := assert.New(t) dir := tempdir() defer cleanup(dir) bodyMap := make(map[string]interface{}) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) - r.rr = &mockRR{} + mrr := r.rr.(*contractregistrymocks.RemoteRegistry) + mrr.On("LoadFactoryForInstance", "myinstance", false).Return(nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/instances/myinstance/set?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) + + mrr.AssertExpectations(t) } -func TestDeployContractSyncRemoteRegitryGateway500(t *testing.T) { +func TestDeployContractSyncRemoteRegistryGateway500(t *testing.T) { assert := assert.New(t) dir := tempdir() defer cleanup(dir) bodyMap := make(map[string]interface{}) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) - r.rr = &mockRR{ - err: fmt.Errorf("pop"), - } + mrr := r.rr.(*contractregistrymocks.RemoteRegistry) + mrr.On("LoadFactoryForGateway", "mygw", false).Return(nil, fmt.Errorf("pop")) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/g/mygw?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) + + mrr.AssertExpectations(t) } -func TestDeployContractSyncRemoteRegitryGateway404(t *testing.T) { +func TestDeployContractSyncRemoteRegistryGateway404(t *testing.T) { assert := assert.New(t) dir := tempdir() defer cleanup(dir) bodyMap := make(map[string]interface{}) + r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) - r.rr = &mockRR{} + mrr := r.rr.(*contractregistrymocks.RemoteRegistry) + mrr.On("LoadFactoryForGateway", "mygw", false).Return(nil, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/g/mygw?fly-sync", bytes.NewReader(body)) router.ServeHTTP(res, req) assert.Equal(404, res.Result().StatusCode) + + mrr.AssertExpectations(t) } func TestDeployContractSyncRemoteRegistryGateway(t *testing.T) { @@ -706,10 +697,12 @@ func TestDeployContractSyncRemoteRegistryGateway(t *testing.T) { dispatcher := &mockREST2EthDispatcher{ sendTransactionSyncReceipt: receipt, } + r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) - r.rr = &mockRR{ - deployMsg: newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), - } + mrr := r.rr.(*contractregistrymocks.RemoteRegistry) + mrr.On("LoadFactoryForGateway", "mygateway", false). + Return(&newTestDeployMsg(t, strings.TrimPrefix(to, "0x")).DeployContract, nil) + body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/g/mygateway/567a417717cb6c59ddc1035705f02c0fd1ab1872/set?fly-sync", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -718,6 +711,8 @@ func TestDeployContractSyncRemoteRegistryGateway(t *testing.T) { assert.Equal(200, res.Result().StatusCode) assert.Equal(to, dispatcher.sendTransactionMsg.To) assert.Equal(from, dispatcher.sendTransactionMsg.From) + + mrr.AssertExpectations(t) } func TestSendTransactionSyncFail(t *testing.T) { diff --git a/internal/contractgateway/smartcontractgw_test.go b/internal/contractgateway/smartcontractgw_test.go index 2331f490..8ad9b8bf 100644 --- a/internal/contractgateway/smartcontractgw_test.go +++ b/internal/contractgateway/smartcontractgw_test.go @@ -365,14 +365,13 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { ) iMsg := newTestDeployMsg(t, "0123456789abcdef0123456789abcdef01234567") iMsg.Headers.ID = "xyz12345" - rr := &mockRR{ - deployMsg: iMsg, - } - scgw.(*smartContractGW).rr = rr + mrr := &contractregistrymocks.RemoteRegistry{} + scgw.(*smartContractGW).rr = mrr router := &httprouter.Router{} scgw.AddRoutes(router) + mrr.On("LoadFactoryForGateway", "test", false).Return(&iMsg.DeployContract, nil).Once() req := httptest.NewRequest("GET", "/g/test?swagger", bytes.NewReader([]byte{})) res := httptest.NewRecorder() router.ServeHTTP(res, req) @@ -381,6 +380,7 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { json.NewDecoder(res.Body).Decode(&returnedSwagger) assert.Equal("/api/v1/g/test", returnedSwagger.BasePath) + mrr.On("LoadFactoryForGateway", "test", false).Return(&iMsg.DeployContract, nil).Once() req = httptest.NewRequest("GET", "/g/test?abi", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) @@ -388,8 +388,8 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { assert.Equal(200, res.Code) json.NewDecoder(res.Body).Decode(&returnedABI) assert.Equal("set", returnedABI.Methods["set"].Name) - assert.False(rr.refreshCapture) + mrr.On("LoadFactoryForInstance", "test", true).Return(iMsg, nil).Once() req = httptest.NewRequest("GET", "/i/test?openapi&refresh", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) @@ -397,8 +397,8 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { assert.Equal(200, res.Code) json.NewDecoder(res.Body).Decode(&returnedSwagger) assert.Equal("/api/v1/i/test", returnedSwagger.BasePath) - assert.True(rr.refreshCapture) + mrr.On("LoadFactoryForInstance", "test", false).Return(iMsg, nil).Once() req = httptest.NewRequest("GET", "/instances/test", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) @@ -408,6 +408,7 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { assert.Equal("xyz12345", jsonRes["id"].(string)) assert.Equal("0123456789abcdef0123456789abcdef01234567", jsonRes["address"].(string)) + mrr.On("LoadFactoryForInstance", "test", false).Return(iMsg, nil).Once() req = httptest.NewRequest("GET", "/i/test?ui", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) @@ -416,6 +417,7 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { assert.Contains(string(html), "") assert.Contains(string(html), "/instances/test?swagger") + mrr.On("LoadFactoryForGateway", "test", false).Return(&iMsg.DeployContract, nil).Once() req = httptest.NewRequest("GET", "/g/test?ui&from=0x12345", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) @@ -425,6 +427,7 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { assert.Contains(string(html), "/gateways/test?swagger") assert.Contains(string(html), "0x12345") + mrr.On("LoadFactoryForGateway", "test", false).Return(&iMsg.DeployContract, nil).Once() req = httptest.NewRequest("GET", "/g/test?ui&from=0x12345&factory", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) @@ -433,33 +436,36 @@ func TestRemoteRegistrySwaggerOrABI(t *testing.T) { assert.Contains(string(html), "") assert.Contains(string(html), "Factory API") - rr.deployMsg = nil - + mrr.On("LoadFactoryForInstance", "test", false).Return(nil, nil).Once() req = httptest.NewRequest("GET", "/instances/test?openapi", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(404, res.Code) + mrr.On("LoadFactoryForGateway", "test", false).Return(nil, nil).Once() req = httptest.NewRequest("GET", "/gateways/test?openapi", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(404, res.Code) - rr.err = fmt.Errorf("pop") + mrr.On("LoadFactoryForInstance", "test", false).Return(nil, fmt.Errorf("pop")).Once() req = httptest.NewRequest("GET", "/instances/test?openapi", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(500, res.Code) + mrr.On("LoadFactoryForGateway", "test", false).Return(nil, fmt.Errorf("pop")).Once() req = httptest.NewRequest("GET", "/gateways/test?openapi", bytes.NewReader([]byte{})) res = httptest.NewRecorder() router.ServeHTTP(res, req) assert.Equal(500, res.Code) + mrr.On("Close").Return() scgw.Shutdown() + mrr.AssertExpectations(t) } -func TestRemoteRegistryBadBI(t *testing.T) { +func TestRemoteRegistryBadABI(t *testing.T) { assert := assert.New(t) scgw, _ := NewSmartContractGateway( @@ -480,15 +486,13 @@ func TestRemoteRegistryBadBI(t *testing.T) { iMsg.ABI = append(iMsg.ABI, ethbinding.ABIElementMarshaling{ Type: "fallback", }) - rr := &mockRR{ - deployMsg: iMsg, - } - - scgw.(*smartContractGW).rr = rr + mrr := &contractregistrymocks.RemoteRegistry{} + scgw.(*smartContractGW).rr = mrr router := &httprouter.Router{} scgw.AddRoutes(router) + mrr.On("LoadFactoryForGateway", "test", false).Return(&iMsg.DeployContract, nil) req := httptest.NewRequest("GET", "/g/test?swagger", bytes.NewReader([]byte{})) res := httptest.NewRecorder() router.ServeHTTP(res, req) @@ -497,7 +501,9 @@ func TestRemoteRegistryBadBI(t *testing.T) { json.NewDecoder(res.Body).Decode(&msg) assert.Regexp("Invalid ABI", msg["error"]) + mrr.On("Close").Return() scgw.Shutdown() + mrr.AssertExpectations(t) } func TestRegisterContractBadAddress(t *testing.T) { @@ -697,8 +703,8 @@ func TestPostDeployRemoteRegisteredName(t *testing.T) { }, nil, nil, nil, nil, ) - rr := &mockRR{} - s.(*smartContractGW).rr = rr + mrr := &contractregistrymocks.RemoteRegistry{} + s.(*smartContractGW).rr = mrr contractAddr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") scgw := s.(*smartContractGW) @@ -718,6 +724,8 @@ func TestPostDeployRemoteRegisteredName(t *testing.T) { RegisterAs: "lobster", } + mrr.On("RegisterInstance", "lobster", "0x0123456789abcdef0123456789abcdef01234567").Return(nil) + deployFile := path.Join(dir, "abi_message1.deploy.json") deployMsg := &messages.DeployContract{} deployBytes, _ := json.Marshal(deployMsg) @@ -725,8 +733,9 @@ func TestPostDeployRemoteRegisteredName(t *testing.T) { err := scgw.PostDeploy(replyMsg) assert.NoError(err) - assert.Equal("0x0123456789abcdef0123456789abcdef01234567", rr.addrCapture) assert.Equal("http://localhost/api/v1/instances/lobster?openapi", replyMsg.ContractSwagger) + + mrr.AssertExpectations(t) } func TestPostDeployRemoteRegisteredNameNotSuccess(t *testing.T) { @@ -743,8 +752,8 @@ func TestPostDeployRemoteRegisteredNameNotSuccess(t *testing.T) { }, nil, nil, nil, nil, ) - rr := &mockRR{} - s.(*smartContractGW).rr = rr + mrr := &contractregistrymocks.RemoteRegistry{} + s.(*smartContractGW).rr = mrr contractAddr := ethbind.API.HexToAddress("0x0123456789AbcdeF0123456789abCdef01234567") scgw := s.(*smartContractGW) @@ -771,8 +780,9 @@ func TestPostDeployRemoteRegisteredNameNotSuccess(t *testing.T) { err := scgw.PostDeploy(replyMsg) assert.NoError(err) - assert.Empty(rr.addrCapture) assert.Empty(replyMsg.ContractSwagger) + + mrr.AssertExpectations(t) } func TestPostDeployMissingContractAddress(t *testing.T) { diff --git a/mocks/contractregistrymocks/remote_registry.go b/mocks/contractregistrymocks/remote_registry.go new file mode 100644 index 00000000..9263b5d8 --- /dev/null +++ b/mocks/contractregistrymocks/remote_registry.go @@ -0,0 +1,94 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package contractregistrymocks + +import ( + contractregistry "github.com/hyperledger-labs/firefly-ethconnect/internal/contractregistry" + messages "github.com/hyperledger-labs/firefly-ethconnect/internal/messages" + + mock "github.com/stretchr/testify/mock" +) + +// RemoteRegistry is an autogenerated mock type for the RemoteRegistry type +type RemoteRegistry struct { + mock.Mock +} + +// Close provides a mock function with given fields: +func (_m *RemoteRegistry) Close() { + _m.Called() +} + +// Init provides a mock function with given fields: +func (_m *RemoteRegistry) Init() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// LoadFactoryForGateway provides a mock function with given fields: lookupStr, refresh +func (_m *RemoteRegistry) LoadFactoryForGateway(lookupStr string, refresh bool) (*messages.DeployContract, error) { + ret := _m.Called(lookupStr, refresh) + + var r0 *messages.DeployContract + if rf, ok := ret.Get(0).(func(string, bool) *messages.DeployContract); ok { + r0 = rf(lookupStr, refresh) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*messages.DeployContract) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, bool) error); ok { + r1 = rf(lookupStr, refresh) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// LoadFactoryForInstance provides a mock function with given fields: lookupStr, refresh +func (_m *RemoteRegistry) LoadFactoryForInstance(lookupStr string, refresh bool) (*contractregistry.DeployContractWithAddress, error) { + ret := _m.Called(lookupStr, refresh) + + var r0 *contractregistry.DeployContractWithAddress + if rf, ok := ret.Get(0).(func(string, bool) *contractregistry.DeployContractWithAddress); ok { + r0 = rf(lookupStr, refresh) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*contractregistry.DeployContractWithAddress) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, bool) error); ok { + r1 = rf(lookupStr, refresh) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// RegisterInstance provides a mock function with given fields: lookupStr, address +func (_m *RemoteRegistry) RegisterInstance(lookupStr string, address string) error { + ret := _m.Called(lookupStr, address) + + var r0 error + if rf, ok := ret.Get(0).(func(string, string) error); ok { + r0 = rf(lookupStr, address) + } else { + r0 = ret.Error(0) + } + + return r0 +} From fb351d5410037a219203e0af696c4b065e0886f7 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Tue, 14 Sep 2021 12:02:47 -0400 Subject: [PATCH 3/6] Use mockery for sarama package Signed-off-by: Andrew Richardson --- Makefile | 12 +- go.mod | 1 - go.sum | 37 -- internal/kafka/client_test.go | 87 +-- internal/kafka/mock_sarama/sarama_mocks.go | 618 -------------------- mocks/saramamocks/client.go | 418 +++++++++++++ mocks/saramamocks/consumer_group.go | 59 ++ mocks/saramamocks/consumer_group_claim.go | 85 +++ mocks/saramamocks/consumer_group_session.go | 95 +++ 9 files changed, 709 insertions(+), 703 deletions(-) delete mode 100644 internal/kafka/mock_sarama/sarama_mocks.go create mode 100644 mocks/saramamocks/client.go create mode 100644 mocks/saramamocks/consumer_group.go create mode 100644 mocks/saramamocks/consumer_group_claim.go create mode 100644 mocks/saramamocks/consumer_group_session.go diff --git a/Makefile b/Makefile index 503706a7..691e2106 100644 --- a/Makefile +++ b/Makefile @@ -7,6 +7,8 @@ BINARY_WIN=$(BINARY_NAME)-win GOBIN := $(shell $(VGO) env GOPATH)/bin MOCKERY := $(GOBIN)/mockery +SARAMA_PATH := $(shell $(VGO) list -f '{{.Dir}}' github.com/Shopify/sarama) + .DELETE_ON_ERROR: GOFILES := $(shell find . -name '*.go' -print) @@ -26,8 +28,6 @@ coverage.txt: $(GOFILES) $(VGO) test ./... -cover -coverprofile=coverage.txt -covermode=atomic -timeout 30s coverage.html: $(VGO) tool cover -html=coverage.txt -mocks: - mockgen github.com/Shopify/sarama Client,ConsumerGroup,ConsumerGroupSession,ConsumerGroupClaim > internal/kafka/mock_sarama/sarama_mocks.go test: coverage.txt coverage: coverage.txt coverage.html clean: force @@ -58,5 +58,9 @@ mocks-$(strip $(1))-$(strip $(2)): ${MOCKERY} ${MOCKERY} --case underscore --dir $(1) --name $(2) --outpkg $(3) --output mocks/$(strip $(3)) endef -$(eval $(call makemock, internal/contractregistry, ContractStore, contractregistrymocks)) -$(eval $(call makemock, internal/contractregistry, RemoteRegistry, contractregistrymocks)) +$(eval $(call makemock, internal/contractregistry, ContractStore, contractregistrymocks)) +$(eval $(call makemock, internal/contractregistry, RemoteRegistry, contractregistrymocks)) +$(eval $(call makemock, $(SARAMA_PATH), Client, saramamocks)) +$(eval $(call makemock, $(SARAMA_PATH), ConsumerGroup, saramamocks)) +$(eval $(call makemock, $(SARAMA_PATH), ConsumerGroupSession, saramamocks)) +$(eval $(call makemock, $(SARAMA_PATH), ConsumerGroupClaim, saramamocks)) diff --git a/go.mod b/go.mod index 5cd4c2aa..ad90546e 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,6 @@ require ( github.com/go-openapi/jsonreference v0.19.5 github.com/go-openapi/spec v0.20.3 github.com/go-openapi/swag v0.19.15 // indirect - github.com/golang/mock v1.6.0 github.com/gorilla/websocket v1.4.2 github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d github.com/icza/dyno v0.0.0-20200205103839-49cb13720835 diff --git a/go.sum b/go.sum index 1ae51fe5..dc292c06 100644 --- a/go.sum +++ b/go.sum @@ -91,7 +91,6 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexkohler/prealloc v1.0.0/go.mod h1:VetnK3dIgFBBKmg0YnD9F9x6Icjd+9cvfHR56wJVlKE= -github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= @@ -110,9 +109,7 @@ github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmV github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= github.com/ashanbrown/forbidigo v1.1.0/go.mod h1:vVW7PEdqEFqapJe95xHkTfB1+XvZXBFg8t0sG2FIxmI= -github.com/ashanbrown/forbidigo v1.2.0/go.mod h1:vVW7PEdqEFqapJe95xHkTfB1+XvZXBFg8t0sG2FIxmI= github.com/ashanbrown/makezero v0.0.0-20210308000810-4155955488a0/go.mod h1:oG9Dnez7/ESBqc4EdrdNlryeo7d0KcW1ftXHm7nU/UU= -github.com/ashanbrown/makezero v0.0.0-20210520155254-b6261585ddde/go.mod h1:oG9Dnez7/ESBqc4EdrdNlryeo7d0KcW1ftXHm7nU/UU= github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= github.com/aws/aws-sdk-go v1.23.20/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.25.37/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= @@ -161,9 +158,7 @@ github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghf github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charithe/durationcheck v0.0.6/go.mod h1:SSbRIBVfMjCi/kEB6K65XEA83D6prSM8ap1UCpNKtgg= -github.com/charithe/durationcheck v0.0.8/go.mod h1:SSbRIBVfMjCi/kEB6K65XEA83D6prSM8ap1UCpNKtgg= github.com/chavacava/garif v0.0.0-20210405163807-87a70f3d418b/go.mod h1:Qjyv4H3//PWVzTeCezG2b9IRn6myJxJSr4TD/xo6ojU= -github.com/chavacava/garif v0.0.0-20210405164556-e8a0a408d6af/go.mod h1:Qjyv4H3//PWVzTeCezG2b9IRn6myJxJSr4TD/xo6ojU= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -241,7 +236,6 @@ github.com/ettle/strcase v0.1.1/go.mod h1:hzDLsPC7/lwKyBOywSHEP89nt2pDgdy+No1NBA github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= -github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= github.com/fjl/memsize v0.0.0-20190710130421-bcb5799ab5e5/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= @@ -269,11 +263,9 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2 github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0 h1:TrB8swr/68K7m9CcGut2g3UOihhbcbiMAYiuTXdEih4= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM= @@ -297,7 +289,6 @@ github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-toolsmith/astcast v1.0.0/go.mod h1:mt2OdQTeAQcY4DQgPSArJjHCcOwlX+Wl/kwN+LbLGQ4= github.com/go-toolsmith/astcopy v1.0.0/go.mod h1:vrgyG+5Bxrnz4MZWPF+pI4R8h3qKRjjyvV/DSez4WVQ= github.com/go-toolsmith/astequal v1.0.0/go.mod h1:H+xSiq0+LtiDC11+h1G32h7Of5O3CYFJ99GVbS5lDKY= @@ -332,10 +323,7 @@ github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFU github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -350,7 +338,6 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= @@ -363,7 +350,6 @@ github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a/go.mod h1:ryS0uhF+x9 github.com/golangci/go-misc v0.0.0-20180628070357-927a3d87b613/go.mod h1:SyvUF2NxV+sN8upjjeVYr5W7tyxaT1JVtvhKhOn2ii8= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= github.com/golangci/golangci-lint v1.40.1/go.mod h1:OyFTr1muxaWeGTcHQcL3B7C4rETnDphTKYenZDgH2/g= -github.com/golangci/golangci-lint v1.41.1/go.mod h1:LPtcY3aAAU8wydHrKpnanx9Og8K/cblZSyGmI5CJZUk= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca/go.mod h1:tvlJhZqDe4LMs4ZHD0oMUlt9G2LWuDGoisJTBzLMV9o= github.com/golangci/misspell v0.3.5/go.mod h1:dEbvlSfYbMQDtrpRMQU675gSDLDNa8sCPPChZ7PhiVA= @@ -405,7 +391,6 @@ github.com/google/uuid v1.1.5/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gookit/color v1.3.8/go.mod h1:R3ogXq2B9rTbXoSHJ1HyUVAZ3poOJHpd9nQmyGZsfvQ= -github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gordonklaus/ineffassign v0.0.0-20200309095847-7953dde2c7bf/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU= github.com/gordonklaus/ineffassign v0.0.0-20210225214923-2e10b2664254/go.mod h1:M9mZEtGIsR1oDaZagNPNG9iq9n2HrhZ17dsXk73V3Lw= @@ -414,9 +399,7 @@ github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51 github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= -github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -511,10 +494,8 @@ github.com/jedisct1/go-minisign v0.0.0-20190909160543-45766022959e/go.mod h1:G1C github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jgautheron/goconst v1.4.0/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= -github.com/jgautheron/goconst v1.5.1/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= github.com/jhump/protoreflect v1.6.1/go.mod h1:RZQ/lnuN+zqeRVpQigTwO6o0AJUkxbnSnpuG7toUTG4= github.com/jingyugao/rowserrcheck v0.0.0-20210315055705-d907ca737bb1/go.mod h1:TOQpc2SLx6huPfoFGK3UOnEG+u02D3C1GeosjupAKCA= -github.com/jingyugao/rowserrcheck v1.1.0/go.mod h1:TOQpc2SLx6huPfoFGK3UOnEG+u02D3C1GeosjupAKCA= github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af/go.mod h1:HEWGJkRDzjJY2sqdDwxccsGicWEf9BQOZsq2tV+xzM0= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= @@ -542,8 +523,6 @@ github.com/julz/importas v0.0.0-20210419104244-841f0c0fe66d/go.mod h1:oSFU2R4XK/ github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef/go.mod h1:Ct9fl0F6iIOGgxJ5npU/IUOhOhqlVrGjyIZc8/MagT0= github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= -github.com/kaleido-io/ethbinding v0.0.0-20210527224458-a2622d9a2bde h1:kEWTGgD9ZD4S9138/vrT+U0x4KG7qK8Xf/xP/MJEK0s= -github.com/kaleido-io/ethbinding v0.0.0-20210527224458-a2622d9a2bde/go.mod h1:WxeDEWweMHKtq0D3vQ5gAqkJu591pfCkSb2RTM0r7fE= github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= @@ -631,7 +610,6 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5 github.com/mbilski/exhaustivestruct v1.2.0/go.mod h1:OeTBVxQWoEmB2J2JCHmXWPJ0aksxSUOUy+nvtVEfzXc= github.com/mgechev/dots v0.0.0-20190921121421-c36f7dcfbb81/go.mod h1:KQ7+USdGKfpPjXk4Ga+5XxQM4Lm4e3gAogrreFAYpOg= github.com/mgechev/revive v1.0.6/go.mod h1:Lj5gIVxjBlH8REa3icEOkdfchwYc291nShzZ4QYWyMo= -github.com/mgechev/revive v1.0.7/go.mod h1:vuE5ox/4L/HDd63MCcCk3H6wTLQ6XXezRphJ8cJJOxY= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mholt/archiver v3.1.1+incompatible h1:1dCVxuqs0dJseYEhi5pl7MYPH9zDa1wBi7mF09cbNkU= @@ -706,7 +684,6 @@ github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108 github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4= github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= -github.com/onsi/ginkgo v1.16.1/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= @@ -714,7 +691,6 @@ github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7J github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= -github.com/onsi/gomega v1.11.0/go.mod h1:azGKhqFUon9Vuj0YmTfLSmx0FUwqXYSTl5re8lQLTUg= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/openconfig/gnmi v0.0.0-20210226144353-8eae1937bf84/go.mod h1:H/20NXlnWbCPFC593nxpiKJ+OU//7mW7s7Qk7uVdg3Q= github.com/openconfig/goyang v0.0.0-20200115183954-d0a48929f0ea/go.mod h1:dhXaV0JgHJzdrHi2l+w0fZrwArtXL7jEFoiqLEdmkvU= @@ -755,7 +731,6 @@ github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/polyfloyd/go-errorlint v0.0.0-20210418123303-74da32850375/go.mod h1:wi9BfjxjF/bwiZ701TzmfKu6UKC357IOAtNr0Td0Lvw= -github.com/polyfloyd/go-errorlint v0.0.0-20210510181950-ab96adb96fea/go.mod h1:wi9BfjxjF/bwiZ701TzmfKu6UKC357IOAtNr0Td0Lvw= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= @@ -813,16 +788,13 @@ github.com/rs/xhandler v0.0.0-20160618193221-ed27b6fd6521/go.mod h1:RvLn4FgxWubr github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryancurrah/gomodguard v1.2.0/go.mod h1:rNqbC4TOIdUDcVMSIpNNAzTbzXAZa6W5lnUepvuMMgQ= -github.com/ryancurrah/gomodguard v1.2.2/go.mod h1:tpI+C/nzvfUR3bF28b5QHpTn/jM/zlGniI++6ZlIWeE= github.com/ryanrolds/sqlclosecheck v0.3.0/go.mod h1:1gREqxyTGR3lVtpngyFo3hZAgk0KCtEdgEkHwDbigdA= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= github.com/sanposhiho/wastedassign v1.0.0/go.mod h1:LGpq5Hsv74QaqM47WtIsRSF/ik9kqk07kchgv66tLVE= -github.com/sanposhiho/wastedassign/v2 v2.0.6/go.mod h1:KyZ0MWTwxxBmfwn33zh3k1dmsbF2ud9pAAGfoLfjhtI= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/securego/gosec/v2 v2.7.0/go.mod h1:xNbGArrGUspJLuz3LS5XCY1EBW/0vABAl/LWfSklmiM= -github.com/securego/gosec/v2 v2.8.0/go.mod h1:hJZ6NT5TqoY+jmOsaxAV4cXoEdrMRLVaNPnSpUCvCZs= github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/segmentio/kafka-go v0.2.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= @@ -832,7 +804,6 @@ github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go github.com/shirou/gopsutil v3.21.4+incompatible h1:fuHcTm5mX+wzo542cmYcV9RTGQLbnHLI5SyQ5ryTVck= github.com/shirou/gopsutil v3.21.4+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil/v3 v3.21.4/go.mod h1:ghfMypLDrFSWN2c9cDYFLHyynQ+QUht0cv/18ZqVczw= -github.com/shirou/gopsutil/v3 v3.21.5/go.mod h1:ghfMypLDrFSWN2c9cDYFLHyynQ+QUht0cv/18ZqVczw= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= @@ -890,7 +861,6 @@ github.com/tdakkota/asciicheck v0.0.0-20200416200610-e657995f937b/go.mod h1:yHp0 github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU= github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4= github.com/tetafro/godot v1.4.6/go.mod h1:LR3CJpxDVGlYOWn3ZZg1PgNZdTUvzsZWu8xaEohUpn8= -github.com/tetafro/godot v1.4.7/go.mod h1:LR3CJpxDVGlYOWn3ZZg1PgNZdTUvzsZWu8xaEohUpn8= github.com/tidwall/gjson v1.8.0 h1:Qt+orfosKn0rbNTZqHYDqBrmm3UDA4KRkv70fDzG+PQ= github.com/tidwall/gjson v1.8.0/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk= github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE= @@ -914,7 +884,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1 github.com/tomarrell/wrapcheck/v2 v2.1.0/go.mod h1:crK5eI4RGSUrb9duDTQ5GqcukbKZvi85vX6nbhsBAeI= github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4= github.com/tommy-muehle/go-mnd/v2 v2.3.2/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= -github.com/tommy-muehle/go-mnd/v2 v2.4.0/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= @@ -943,7 +912,6 @@ github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofm github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= -github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xtaci/kcp-go v5.4.20+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45a+AZwO7eyRCmEIbtvE= github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE= @@ -1289,10 +1257,7 @@ golang.org/x/tools v0.0.0-20201230224404-63754364767c/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210104081019-d8d6ddbec6ee/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.2-0.20210512205948-8287d5da45e4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1396,7 +1361,6 @@ google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/bsm/ratelimit.v1 v1.0.0-20160220154919-db14e161995a/go.mod h1:KF9sEfUPAXdG8Oev9e99iLGnl2uJMjc5B+4y3O7x610= @@ -1447,7 +1411,6 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.1.3/go.mod h1:NgwopIslSNH47DimFoV78dnkksY2EFtX0ajyb3K/las= honnef.co/go/tools v0.1.4/go.mod h1:NgwopIslSNH47DimFoV78dnkksY2EFtX0ajyb3K/las= -honnef.co/go/tools v0.2.0/go.mod h1:lPVVZ2BS5TfnjLyizF7o7hv7j9/L+8cZY2hLyjP9cGY= mvdan.cc/gofumpt v0.1.1/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed/go.mod h1:Xkxe497xwlCKkIaQYRfC7CSLworTXY9RMqwhhCm+8Nc= mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jCoyKnw3vv5biOc3JnIcYfL4= diff --git a/internal/kafka/client_test.go b/internal/kafka/client_test.go index 11ed7723..740cfa82 100644 --- a/internal/kafka/client_test.go +++ b/internal/kafka/client_test.go @@ -21,14 +21,13 @@ import ( "time" "github.com/Shopify/sarama" - "github.com/golang/mock/gomock" - "github.com/hyperledger-labs/firefly-ethconnect/internal/kafka/mock_sarama" + "github.com/hyperledger-labs/firefly-ethconnect/mocks/saramamocks" log "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" ) type mockConsumerGroupFactory struct { - mcg *mock_sarama.MockConsumerGroup + mcg *saramamocks.ConsumerGroup err error called bool } @@ -39,43 +38,38 @@ func (m *mockConsumerGroupFactory) NewConsumerGroupFromClient(groupID string, cl } func TestConsumerGroupHandler(t *testing.T) { - assert := assert.New(t) log.SetLevel(log.DebugLevel) - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mc := mock_sarama.NewMockClient(ctrl) - mcg := mock_sarama.NewMockConsumerGroup(ctrl) + mc := &saramamocks.Client{} + mcg := &saramamocks.ConsumerGroup{} mf := &mockConsumerGroupFactory{ mcg: mcg, } - ms := mock_sarama.NewMockConsumerGroupSession(ctrl) - mcgc := mock_sarama.NewMockConsumerGroupClaim(ctrl) + ms := &saramamocks.ConsumerGroupSession{} + mcgc := &saramamocks.ConsumerGroupClaim{} stopConsume := make(chan bool) consumeOnce := make(chan bool) errors := make(chan error) messages := make(chan *sarama.ConsumerMessage) - ms.EXPECT().Claims().MinTimes(1) - ms.EXPECT().MemberID().MinTimes(1) - ms.EXPECT().GenerationID().MinTimes(1) - ms.EXPECT().MarkMessage(gomock.Any(), gomock.Any()).Times(1) - mcgc.EXPECT().Messages().Return(messages).Times(1) - mcg.EXPECT().Close().Return(nil).Times(1) - mcg.EXPECT().Errors().Return(errors).Times(1) - mcg.EXPECT().Consume(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( - func(ctx context.Context, topics []string, handler sarama.ConsumerGroupHandler) error { - assert.Equal([]string{"topic1"}, topics) - t.Logf("Starting consume") + + ms.On("Claims").Return(nil) + ms.On("MemberID").Return("") + ms.On("GenerationID").Return(int32(0)) + ms.On("MarkMessage", mock.Anything, "mymeta").Return().Once() + mcg.On("Errors").Return((<-chan error)(errors)) + mcg.On("Close").Return(nil).Once() + mcgc.On("Messages").Return((<-chan *sarama.ConsumerMessage)(messages)) + mcg.On("Consume", context.Background(), []string{"topic1"}, mock.Anything). + Run(func(args mock.Arguments) { + handler := args[2].(sarama.ConsumerGroupHandler) handler.Setup(ms) - t.Logf("Setup completed") handler.ConsumeClaim(ms, mcgc) consumeOnce <- true <-stopConsume handler.Cleanup(ms) - t.Logf("Cleanup completed") - return nil - }).MinTimes(1) + }). + Return(nil) h := newSaramaKafkaConsumerGroupHandler(mf, mc, "group1", []string{"topic1"}, 10*time.Millisecond) go func() { @@ -95,14 +89,17 @@ func TestConsumerGroupHandler(t *testing.T) { h.wg.Wait() close(stopConsume) close(consumeOnce) + + mc.AssertExpectations(t) + mcg.AssertExpectations(t) + ms.AssertExpectations(t) + mcgc.AssertExpectations(t) } func TestConsumerGroupHandlerCreateFail(t *testing.T) { log.SetLevel(log.DebugLevel) - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mc := mock_sarama.NewMockClient(ctrl) + mc := &saramamocks.Client{} mf := &mockConsumerGroupFactory{ err: fmt.Errorf("pop"), } @@ -114,15 +111,15 @@ func TestConsumerGroupHandlerCreateFail(t *testing.T) { h.Close() h.wg.Wait() + + mc.AssertExpectations(t) } func TestConsumerGroupHandlerReconnect(t *testing.T) { log.SetLevel(log.DebugLevel) - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mc := mock_sarama.NewMockClient(ctrl) - mcg := mock_sarama.NewMockConsumerGroup(ctrl) + mc := &saramamocks.Client{} + mcg := &saramamocks.ConsumerGroup{} mf := &mockConsumerGroupFactory{ mcg: mcg, } @@ -130,16 +127,17 @@ func TestConsumerGroupHandlerReconnect(t *testing.T) { consumeOnce := make(chan bool) errors := make(chan error) firstLoop := true - mcg.EXPECT().Close().Return(nil).MinTimes(1) - mcg.EXPECT().Errors().Return(errors).MinTimes(1) - mcg.EXPECT().Consume(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( - func(ctx context.Context, topics []string, handler sarama.ConsumerGroupHandler) error { - if firstLoop { - consumeOnce <- true - firstLoop = false - } - return fmt.Errorf("pop") - }).MinTimes(1) + + mcg.On("Close").Return(nil) + mcg.On("Errors").Return((<-chan error)(errors)) + mconsume := mcg.On("Consume", context.Background(), []string{"topic1"}, mock.Anything) + mconsume.RunFn = func(args mock.Arguments) { + if firstLoop { + consumeOnce <- true + firstLoop = false + } + mconsume.ReturnArguments = mock.Arguments{fmt.Errorf("pop")} + } h := newSaramaKafkaConsumerGroupHandler(mf, mc, "group1", []string{"topic1"}, 10*time.Millisecond) go func() { @@ -150,4 +148,7 @@ func TestConsumerGroupHandlerReconnect(t *testing.T) { close(errors) h.wg.Wait() close(consumeOnce) + + mc.AssertExpectations(t) + mcg.AssertExpectations(t) } diff --git a/internal/kafka/mock_sarama/sarama_mocks.go b/internal/kafka/mock_sarama/sarama_mocks.go deleted file mode 100644 index bbac1bfd..00000000 --- a/internal/kafka/mock_sarama/sarama_mocks.go +++ /dev/null @@ -1,618 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/Shopify/sarama (interfaces: Client,ConsumerGroup,ConsumerGroupSession,ConsumerGroupClaim) - -// Package mock_sarama is a generated GoMock package. -package mock_sarama - -import ( - context "context" - reflect "reflect" - - sarama "github.com/Shopify/sarama" - gomock "github.com/golang/mock/gomock" -) - -// MockClient is a mock of Client interface. -type MockClient struct { - ctrl *gomock.Controller - recorder *MockClientMockRecorder -} - -// MockClientMockRecorder is the mock recorder for MockClient. -type MockClientMockRecorder struct { - mock *MockClient -} - -// NewMockClient creates a new mock instance. -func NewMockClient(ctrl *gomock.Controller) *MockClient { - mock := &MockClient{ctrl: ctrl} - mock.recorder = &MockClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockClient) EXPECT() *MockClientMockRecorder { - return m.recorder -} - -// Broker mocks base method. -func (m *MockClient) Broker(arg0 int32) (*sarama.Broker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Broker", arg0) - ret0, _ := ret[0].(*sarama.Broker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Broker indicates an expected call of Broker. -func (mr *MockClientMockRecorder) Broker(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Broker", reflect.TypeOf((*MockClient)(nil).Broker), arg0) -} - -// Brokers mocks base method. -func (m *MockClient) Brokers() []*sarama.Broker { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Brokers") - ret0, _ := ret[0].([]*sarama.Broker) - return ret0 -} - -// Brokers indicates an expected call of Brokers. -func (mr *MockClientMockRecorder) Brokers() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Brokers", reflect.TypeOf((*MockClient)(nil).Brokers)) -} - -// Close mocks base method. -func (m *MockClient) Close() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close. -func (mr *MockClientMockRecorder) Close() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockClient)(nil).Close)) -} - -// Closed mocks base method. -func (m *MockClient) Closed() bool { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Closed") - ret0, _ := ret[0].(bool) - return ret0 -} - -// Closed indicates an expected call of Closed. -func (mr *MockClientMockRecorder) Closed() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Closed", reflect.TypeOf((*MockClient)(nil).Closed)) -} - -// Config mocks base method. -func (m *MockClient) Config() *sarama.Config { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Config") - ret0, _ := ret[0].(*sarama.Config) - return ret0 -} - -// Config indicates an expected call of Config. -func (mr *MockClientMockRecorder) Config() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Config", reflect.TypeOf((*MockClient)(nil).Config)) -} - -// Controller mocks base method. -func (m *MockClient) Controller() (*sarama.Broker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Controller") - ret0, _ := ret[0].(*sarama.Broker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Controller indicates an expected call of Controller. -func (mr *MockClientMockRecorder) Controller() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Controller", reflect.TypeOf((*MockClient)(nil).Controller)) -} - -// Coordinator mocks base method. -func (m *MockClient) Coordinator(arg0 string) (*sarama.Broker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Coordinator", arg0) - ret0, _ := ret[0].(*sarama.Broker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Coordinator indicates an expected call of Coordinator. -func (mr *MockClientMockRecorder) Coordinator(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Coordinator", reflect.TypeOf((*MockClient)(nil).Coordinator), arg0) -} - -// GetOffset mocks base method. -func (m *MockClient) GetOffset(arg0 string, arg1 int32, arg2 int64) (int64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetOffset", arg0, arg1, arg2) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetOffset indicates an expected call of GetOffset. -func (mr *MockClientMockRecorder) GetOffset(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOffset", reflect.TypeOf((*MockClient)(nil).GetOffset), arg0, arg1, arg2) -} - -// InSyncReplicas mocks base method. -func (m *MockClient) InSyncReplicas(arg0 string, arg1 int32) ([]int32, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InSyncReplicas", arg0, arg1) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// InSyncReplicas indicates an expected call of InSyncReplicas. -func (mr *MockClientMockRecorder) InSyncReplicas(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InSyncReplicas", reflect.TypeOf((*MockClient)(nil).InSyncReplicas), arg0, arg1) -} - -// InitProducerID mocks base method. -func (m *MockClient) InitProducerID() (*sarama.InitProducerIDResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitProducerID") - ret0, _ := ret[0].(*sarama.InitProducerIDResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// InitProducerID indicates an expected call of InitProducerID. -func (mr *MockClientMockRecorder) InitProducerID() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitProducerID", reflect.TypeOf((*MockClient)(nil).InitProducerID)) -} - -// Leader mocks base method. -func (m *MockClient) Leader(arg0 string, arg1 int32) (*sarama.Broker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Leader", arg0, arg1) - ret0, _ := ret[0].(*sarama.Broker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Leader indicates an expected call of Leader. -func (mr *MockClientMockRecorder) Leader(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Leader", reflect.TypeOf((*MockClient)(nil).Leader), arg0, arg1) -} - -// OfflineReplicas mocks base method. -func (m *MockClient) OfflineReplicas(arg0 string, arg1 int32) ([]int32, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OfflineReplicas", arg0, arg1) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OfflineReplicas indicates an expected call of OfflineReplicas. -func (mr *MockClientMockRecorder) OfflineReplicas(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OfflineReplicas", reflect.TypeOf((*MockClient)(nil).OfflineReplicas), arg0, arg1) -} - -// Partitions mocks base method. -func (m *MockClient) Partitions(arg0 string) ([]int32, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Partitions", arg0) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Partitions indicates an expected call of Partitions. -func (mr *MockClientMockRecorder) Partitions(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Partitions", reflect.TypeOf((*MockClient)(nil).Partitions), arg0) -} - -// RefreshBrokers mocks base method. -func (m *MockClient) RefreshBrokers(arg0 []string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RefreshBrokers", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// RefreshBrokers indicates an expected call of RefreshBrokers. -func (mr *MockClientMockRecorder) RefreshBrokers(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshBrokers", reflect.TypeOf((*MockClient)(nil).RefreshBrokers), arg0) -} - -// RefreshController mocks base method. -func (m *MockClient) RefreshController() (*sarama.Broker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RefreshController") - ret0, _ := ret[0].(*sarama.Broker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// RefreshController indicates an expected call of RefreshController. -func (mr *MockClientMockRecorder) RefreshController() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshController", reflect.TypeOf((*MockClient)(nil).RefreshController)) -} - -// RefreshCoordinator mocks base method. -func (m *MockClient) RefreshCoordinator(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RefreshCoordinator", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// RefreshCoordinator indicates an expected call of RefreshCoordinator. -func (mr *MockClientMockRecorder) RefreshCoordinator(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshCoordinator", reflect.TypeOf((*MockClient)(nil).RefreshCoordinator), arg0) -} - -// RefreshMetadata mocks base method. -func (m *MockClient) RefreshMetadata(arg0 ...string) error { - m.ctrl.T.Helper() - varargs := []interface{}{} - for _, a := range arg0 { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "RefreshMetadata", varargs...) - ret0, _ := ret[0].(error) - return ret0 -} - -// RefreshMetadata indicates an expected call of RefreshMetadata. -func (mr *MockClientMockRecorder) RefreshMetadata(arg0 ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshMetadata", reflect.TypeOf((*MockClient)(nil).RefreshMetadata), arg0...) -} - -// Replicas mocks base method. -func (m *MockClient) Replicas(arg0 string, arg1 int32) ([]int32, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Replicas", arg0, arg1) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Replicas indicates an expected call of Replicas. -func (mr *MockClientMockRecorder) Replicas(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Replicas", reflect.TypeOf((*MockClient)(nil).Replicas), arg0, arg1) -} - -// Topics mocks base method. -func (m *MockClient) Topics() ([]string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Topics") - ret0, _ := ret[0].([]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Topics indicates an expected call of Topics. -func (mr *MockClientMockRecorder) Topics() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Topics", reflect.TypeOf((*MockClient)(nil).Topics)) -} - -// WritablePartitions mocks base method. -func (m *MockClient) WritablePartitions(arg0 string) ([]int32, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WritablePartitions", arg0) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WritablePartitions indicates an expected call of WritablePartitions. -func (mr *MockClientMockRecorder) WritablePartitions(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WritablePartitions", reflect.TypeOf((*MockClient)(nil).WritablePartitions), arg0) -} - -// MockConsumerGroup is a mock of ConsumerGroup interface. -type MockConsumerGroup struct { - ctrl *gomock.Controller - recorder *MockConsumerGroupMockRecorder -} - -// MockConsumerGroupMockRecorder is the mock recorder for MockConsumerGroup. -type MockConsumerGroupMockRecorder struct { - mock *MockConsumerGroup -} - -// NewMockConsumerGroup creates a new mock instance. -func NewMockConsumerGroup(ctrl *gomock.Controller) *MockConsumerGroup { - mock := &MockConsumerGroup{ctrl: ctrl} - mock.recorder = &MockConsumerGroupMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockConsumerGroup) EXPECT() *MockConsumerGroupMockRecorder { - return m.recorder -} - -// Close mocks base method. -func (m *MockConsumerGroup) Close() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close. -func (mr *MockConsumerGroupMockRecorder) Close() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockConsumerGroup)(nil).Close)) -} - -// Consume mocks base method. -func (m *MockConsumerGroup) Consume(arg0 context.Context, arg1 []string, arg2 sarama.ConsumerGroupHandler) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Consume", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// Consume indicates an expected call of Consume. -func (mr *MockConsumerGroupMockRecorder) Consume(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Consume", reflect.TypeOf((*MockConsumerGroup)(nil).Consume), arg0, arg1, arg2) -} - -// Errors mocks base method. -func (m *MockConsumerGroup) Errors() <-chan error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Errors") - ret0, _ := ret[0].(<-chan error) - return ret0 -} - -// Errors indicates an expected call of Errors. -func (mr *MockConsumerGroupMockRecorder) Errors() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Errors", reflect.TypeOf((*MockConsumerGroup)(nil).Errors)) -} - -// MockConsumerGroupSession is a mock of ConsumerGroupSession interface. -type MockConsumerGroupSession struct { - ctrl *gomock.Controller - recorder *MockConsumerGroupSessionMockRecorder -} - -// MockConsumerGroupSessionMockRecorder is the mock recorder for MockConsumerGroupSession. -type MockConsumerGroupSessionMockRecorder struct { - mock *MockConsumerGroupSession -} - -// NewMockConsumerGroupSession creates a new mock instance. -func NewMockConsumerGroupSession(ctrl *gomock.Controller) *MockConsumerGroupSession { - mock := &MockConsumerGroupSession{ctrl: ctrl} - mock.recorder = &MockConsumerGroupSessionMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockConsumerGroupSession) EXPECT() *MockConsumerGroupSessionMockRecorder { - return m.recorder -} - -// Claims mocks base method. -func (m *MockConsumerGroupSession) Claims() map[string][]int32 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Claims") - ret0, _ := ret[0].(map[string][]int32) - return ret0 -} - -// Claims indicates an expected call of Claims. -func (mr *MockConsumerGroupSessionMockRecorder) Claims() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Claims", reflect.TypeOf((*MockConsumerGroupSession)(nil).Claims)) -} - -// Commit mocks base method. -func (m *MockConsumerGroupSession) Commit() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Commit") -} - -// Commit indicates an expected call of Commit. -func (mr *MockConsumerGroupSessionMockRecorder) Commit() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockConsumerGroupSession)(nil).Commit)) -} - -// Context mocks base method. -func (m *MockConsumerGroupSession) Context() context.Context { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Context") - ret0, _ := ret[0].(context.Context) - return ret0 -} - -// Context indicates an expected call of Context. -func (mr *MockConsumerGroupSessionMockRecorder) Context() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*MockConsumerGroupSession)(nil).Context)) -} - -// GenerationID mocks base method. -func (m *MockConsumerGroupSession) GenerationID() int32 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GenerationID") - ret0, _ := ret[0].(int32) - return ret0 -} - -// GenerationID indicates an expected call of GenerationID. -func (mr *MockConsumerGroupSessionMockRecorder) GenerationID() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerationID", reflect.TypeOf((*MockConsumerGroupSession)(nil).GenerationID)) -} - -// MarkMessage mocks base method. -func (m *MockConsumerGroupSession) MarkMessage(arg0 *sarama.ConsumerMessage, arg1 string) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "MarkMessage", arg0, arg1) -} - -// MarkMessage indicates an expected call of MarkMessage. -func (mr *MockConsumerGroupSessionMockRecorder) MarkMessage(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkMessage", reflect.TypeOf((*MockConsumerGroupSession)(nil).MarkMessage), arg0, arg1) -} - -// MarkOffset mocks base method. -func (m *MockConsumerGroupSession) MarkOffset(arg0 string, arg1 int32, arg2 int64, arg3 string) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "MarkOffset", arg0, arg1, arg2, arg3) -} - -// MarkOffset indicates an expected call of MarkOffset. -func (mr *MockConsumerGroupSessionMockRecorder) MarkOffset(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkOffset", reflect.TypeOf((*MockConsumerGroupSession)(nil).MarkOffset), arg0, arg1, arg2, arg3) -} - -// MemberID mocks base method. -func (m *MockConsumerGroupSession) MemberID() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MemberID") - ret0, _ := ret[0].(string) - return ret0 -} - -// MemberID indicates an expected call of MemberID. -func (mr *MockConsumerGroupSessionMockRecorder) MemberID() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MemberID", reflect.TypeOf((*MockConsumerGroupSession)(nil).MemberID)) -} - -// ResetOffset mocks base method. -func (m *MockConsumerGroupSession) ResetOffset(arg0 string, arg1 int32, arg2 int64, arg3 string) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "ResetOffset", arg0, arg1, arg2, arg3) -} - -// ResetOffset indicates an expected call of ResetOffset. -func (mr *MockConsumerGroupSessionMockRecorder) ResetOffset(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResetOffset", reflect.TypeOf((*MockConsumerGroupSession)(nil).ResetOffset), arg0, arg1, arg2, arg3) -} - -// MockConsumerGroupClaim is a mock of ConsumerGroupClaim interface. -type MockConsumerGroupClaim struct { - ctrl *gomock.Controller - recorder *MockConsumerGroupClaimMockRecorder -} - -// MockConsumerGroupClaimMockRecorder is the mock recorder for MockConsumerGroupClaim. -type MockConsumerGroupClaimMockRecorder struct { - mock *MockConsumerGroupClaim -} - -// NewMockConsumerGroupClaim creates a new mock instance. -func NewMockConsumerGroupClaim(ctrl *gomock.Controller) *MockConsumerGroupClaim { - mock := &MockConsumerGroupClaim{ctrl: ctrl} - mock.recorder = &MockConsumerGroupClaimMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockConsumerGroupClaim) EXPECT() *MockConsumerGroupClaimMockRecorder { - return m.recorder -} - -// HighWaterMarkOffset mocks base method. -func (m *MockConsumerGroupClaim) HighWaterMarkOffset() int64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HighWaterMarkOffset") - ret0, _ := ret[0].(int64) - return ret0 -} - -// HighWaterMarkOffset indicates an expected call of HighWaterMarkOffset. -func (mr *MockConsumerGroupClaimMockRecorder) HighWaterMarkOffset() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HighWaterMarkOffset", reflect.TypeOf((*MockConsumerGroupClaim)(nil).HighWaterMarkOffset)) -} - -// InitialOffset mocks base method. -func (m *MockConsumerGroupClaim) InitialOffset() int64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitialOffset") - ret0, _ := ret[0].(int64) - return ret0 -} - -// InitialOffset indicates an expected call of InitialOffset. -func (mr *MockConsumerGroupClaimMockRecorder) InitialOffset() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitialOffset", reflect.TypeOf((*MockConsumerGroupClaim)(nil).InitialOffset)) -} - -// Messages mocks base method. -func (m *MockConsumerGroupClaim) Messages() <-chan *sarama.ConsumerMessage { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Messages") - ret0, _ := ret[0].(<-chan *sarama.ConsumerMessage) - return ret0 -} - -// Messages indicates an expected call of Messages. -func (mr *MockConsumerGroupClaimMockRecorder) Messages() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Messages", reflect.TypeOf((*MockConsumerGroupClaim)(nil).Messages)) -} - -// Partition mocks base method. -func (m *MockConsumerGroupClaim) Partition() int32 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Partition") - ret0, _ := ret[0].(int32) - return ret0 -} - -// Partition indicates an expected call of Partition. -func (mr *MockConsumerGroupClaimMockRecorder) Partition() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Partition", reflect.TypeOf((*MockConsumerGroupClaim)(nil).Partition)) -} - -// Topic mocks base method. -func (m *MockConsumerGroupClaim) Topic() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Topic") - ret0, _ := ret[0].(string) - return ret0 -} - -// Topic indicates an expected call of Topic. -func (mr *MockConsumerGroupClaimMockRecorder) Topic() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Topic", reflect.TypeOf((*MockConsumerGroupClaim)(nil).Topic)) -} diff --git a/mocks/saramamocks/client.go b/mocks/saramamocks/client.go new file mode 100644 index 00000000..d1994098 --- /dev/null +++ b/mocks/saramamocks/client.go @@ -0,0 +1,418 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package saramamocks + +import ( + sarama "github.com/Shopify/sarama" + mock "github.com/stretchr/testify/mock" +) + +// Client is an autogenerated mock type for the Client type +type Client struct { + mock.Mock +} + +// Broker provides a mock function with given fields: brokerID +func (_m *Client) Broker(brokerID int32) (*sarama.Broker, error) { + ret := _m.Called(brokerID) + + var r0 *sarama.Broker + if rf, ok := ret.Get(0).(func(int32) *sarama.Broker); ok { + r0 = rf(brokerID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sarama.Broker) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(int32) error); ok { + r1 = rf(brokerID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Brokers provides a mock function with given fields: +func (_m *Client) Brokers() []*sarama.Broker { + ret := _m.Called() + + var r0 []*sarama.Broker + if rf, ok := ret.Get(0).(func() []*sarama.Broker); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*sarama.Broker) + } + } + + return r0 +} + +// Close provides a mock function with given fields: +func (_m *Client) Close() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Closed provides a mock function with given fields: +func (_m *Client) Closed() bool { + ret := _m.Called() + + var r0 bool + if rf, ok := ret.Get(0).(func() bool); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// Config provides a mock function with given fields: +func (_m *Client) Config() *sarama.Config { + ret := _m.Called() + + var r0 *sarama.Config + if rf, ok := ret.Get(0).(func() *sarama.Config); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sarama.Config) + } + } + + return r0 +} + +// Controller provides a mock function with given fields: +func (_m *Client) Controller() (*sarama.Broker, error) { + ret := _m.Called() + + var r0 *sarama.Broker + if rf, ok := ret.Get(0).(func() *sarama.Broker); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sarama.Broker) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Coordinator provides a mock function with given fields: consumerGroup +func (_m *Client) Coordinator(consumerGroup string) (*sarama.Broker, error) { + ret := _m.Called(consumerGroup) + + var r0 *sarama.Broker + if rf, ok := ret.Get(0).(func(string) *sarama.Broker); ok { + r0 = rf(consumerGroup) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sarama.Broker) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(consumerGroup) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetOffset provides a mock function with given fields: topic, partitionID, time +func (_m *Client) GetOffset(topic string, partitionID int32, time int64) (int64, error) { + ret := _m.Called(topic, partitionID, time) + + var r0 int64 + if rf, ok := ret.Get(0).(func(string, int32, int64) int64); ok { + r0 = rf(topic, partitionID, time) + } else { + r0 = ret.Get(0).(int64) + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, int32, int64) error); ok { + r1 = rf(topic, partitionID, time) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// InSyncReplicas provides a mock function with given fields: topic, partitionID +func (_m *Client) InSyncReplicas(topic string, partitionID int32) ([]int32, error) { + ret := _m.Called(topic, partitionID) + + var r0 []int32 + if rf, ok := ret.Get(0).(func(string, int32) []int32); ok { + r0 = rf(topic, partitionID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]int32) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, int32) error); ok { + r1 = rf(topic, partitionID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// InitProducerID provides a mock function with given fields: +func (_m *Client) InitProducerID() (*sarama.InitProducerIDResponse, error) { + ret := _m.Called() + + var r0 *sarama.InitProducerIDResponse + if rf, ok := ret.Get(0).(func() *sarama.InitProducerIDResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sarama.InitProducerIDResponse) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Leader provides a mock function with given fields: topic, partitionID +func (_m *Client) Leader(topic string, partitionID int32) (*sarama.Broker, error) { + ret := _m.Called(topic, partitionID) + + var r0 *sarama.Broker + if rf, ok := ret.Get(0).(func(string, int32) *sarama.Broker); ok { + r0 = rf(topic, partitionID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sarama.Broker) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, int32) error); ok { + r1 = rf(topic, partitionID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// OfflineReplicas provides a mock function with given fields: topic, partitionID +func (_m *Client) OfflineReplicas(topic string, partitionID int32) ([]int32, error) { + ret := _m.Called(topic, partitionID) + + var r0 []int32 + if rf, ok := ret.Get(0).(func(string, int32) []int32); ok { + r0 = rf(topic, partitionID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]int32) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, int32) error); ok { + r1 = rf(topic, partitionID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Partitions provides a mock function with given fields: topic +func (_m *Client) Partitions(topic string) ([]int32, error) { + ret := _m.Called(topic) + + var r0 []int32 + if rf, ok := ret.Get(0).(func(string) []int32); ok { + r0 = rf(topic) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]int32) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(topic) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// RefreshBrokers provides a mock function with given fields: addrs +func (_m *Client) RefreshBrokers(addrs []string) error { + ret := _m.Called(addrs) + + var r0 error + if rf, ok := ret.Get(0).(func([]string) error); ok { + r0 = rf(addrs) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// RefreshController provides a mock function with given fields: +func (_m *Client) RefreshController() (*sarama.Broker, error) { + ret := _m.Called() + + var r0 *sarama.Broker + if rf, ok := ret.Get(0).(func() *sarama.Broker); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sarama.Broker) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// RefreshCoordinator provides a mock function with given fields: consumerGroup +func (_m *Client) RefreshCoordinator(consumerGroup string) error { + ret := _m.Called(consumerGroup) + + var r0 error + if rf, ok := ret.Get(0).(func(string) error); ok { + r0 = rf(consumerGroup) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// RefreshMetadata provides a mock function with given fields: topics +func (_m *Client) RefreshMetadata(topics ...string) error { + _va := make([]interface{}, len(topics)) + for _i := range topics { + _va[_i] = topics[_i] + } + var _ca []interface{} + _ca = append(_ca, _va...) + ret := _m.Called(_ca...) + + var r0 error + if rf, ok := ret.Get(0).(func(...string) error); ok { + r0 = rf(topics...) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Replicas provides a mock function with given fields: topic, partitionID +func (_m *Client) Replicas(topic string, partitionID int32) ([]int32, error) { + ret := _m.Called(topic, partitionID) + + var r0 []int32 + if rf, ok := ret.Get(0).(func(string, int32) []int32); ok { + r0 = rf(topic, partitionID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]int32) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string, int32) error); ok { + r1 = rf(topic, partitionID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Topics provides a mock function with given fields: +func (_m *Client) Topics() ([]string, error) { + ret := _m.Called() + + var r0 []string + if rf, ok := ret.Get(0).(func() []string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]string) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// WritablePartitions provides a mock function with given fields: topic +func (_m *Client) WritablePartitions(topic string) ([]int32, error) { + ret := _m.Called(topic) + + var r0 []int32 + if rf, ok := ret.Get(0).(func(string) []int32); ok { + r0 = rf(topic) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]int32) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(topic) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} diff --git a/mocks/saramamocks/consumer_group.go b/mocks/saramamocks/consumer_group.go new file mode 100644 index 00000000..230f95f4 --- /dev/null +++ b/mocks/saramamocks/consumer_group.go @@ -0,0 +1,59 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package saramamocks + +import ( + context "context" + + sarama "github.com/Shopify/sarama" + mock "github.com/stretchr/testify/mock" +) + +// ConsumerGroup is an autogenerated mock type for the ConsumerGroup type +type ConsumerGroup struct { + mock.Mock +} + +// Close provides a mock function with given fields: +func (_m *ConsumerGroup) Close() error { + ret := _m.Called() + + var r0 error + if rf, ok := ret.Get(0).(func() error); ok { + r0 = rf() + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Consume provides a mock function with given fields: ctx, topics, handler +func (_m *ConsumerGroup) Consume(ctx context.Context, topics []string, handler sarama.ConsumerGroupHandler) error { + ret := _m.Called(ctx, topics, handler) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, []string, sarama.ConsumerGroupHandler) error); ok { + r0 = rf(ctx, topics, handler) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// Errors provides a mock function with given fields: +func (_m *ConsumerGroup) Errors() <-chan error { + ret := _m.Called() + + var r0 <-chan error + if rf, ok := ret.Get(0).(func() <-chan error); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(<-chan error) + } + } + + return r0 +} diff --git a/mocks/saramamocks/consumer_group_claim.go b/mocks/saramamocks/consumer_group_claim.go new file mode 100644 index 00000000..cd2a8a69 --- /dev/null +++ b/mocks/saramamocks/consumer_group_claim.go @@ -0,0 +1,85 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package saramamocks + +import ( + sarama "github.com/Shopify/sarama" + mock "github.com/stretchr/testify/mock" +) + +// ConsumerGroupClaim is an autogenerated mock type for the ConsumerGroupClaim type +type ConsumerGroupClaim struct { + mock.Mock +} + +// HighWaterMarkOffset provides a mock function with given fields: +func (_m *ConsumerGroupClaim) HighWaterMarkOffset() int64 { + ret := _m.Called() + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +// InitialOffset provides a mock function with given fields: +func (_m *ConsumerGroupClaim) InitialOffset() int64 { + ret := _m.Called() + + var r0 int64 + if rf, ok := ret.Get(0).(func() int64); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int64) + } + + return r0 +} + +// Messages provides a mock function with given fields: +func (_m *ConsumerGroupClaim) Messages() <-chan *sarama.ConsumerMessage { + ret := _m.Called() + + var r0 <-chan *sarama.ConsumerMessage + if rf, ok := ret.Get(0).(func() <-chan *sarama.ConsumerMessage); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(<-chan *sarama.ConsumerMessage) + } + } + + return r0 +} + +// Partition provides a mock function with given fields: +func (_m *ConsumerGroupClaim) Partition() int32 { + ret := _m.Called() + + var r0 int32 + if rf, ok := ret.Get(0).(func() int32); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int32) + } + + return r0 +} + +// Topic provides a mock function with given fields: +func (_m *ConsumerGroupClaim) Topic() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} diff --git a/mocks/saramamocks/consumer_group_session.go b/mocks/saramamocks/consumer_group_session.go new file mode 100644 index 00000000..5ed06184 --- /dev/null +++ b/mocks/saramamocks/consumer_group_session.go @@ -0,0 +1,95 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package saramamocks + +import ( + context "context" + + sarama "github.com/Shopify/sarama" + mock "github.com/stretchr/testify/mock" +) + +// ConsumerGroupSession is an autogenerated mock type for the ConsumerGroupSession type +type ConsumerGroupSession struct { + mock.Mock +} + +// Claims provides a mock function with given fields: +func (_m *ConsumerGroupSession) Claims() map[string][]int32 { + ret := _m.Called() + + var r0 map[string][]int32 + if rf, ok := ret.Get(0).(func() map[string][]int32); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(map[string][]int32) + } + } + + return r0 +} + +// Commit provides a mock function with given fields: +func (_m *ConsumerGroupSession) Commit() { + _m.Called() +} + +// Context provides a mock function with given fields: +func (_m *ConsumerGroupSession) Context() context.Context { + ret := _m.Called() + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// GenerationID provides a mock function with given fields: +func (_m *ConsumerGroupSession) GenerationID() int32 { + ret := _m.Called() + + var r0 int32 + if rf, ok := ret.Get(0).(func() int32); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(int32) + } + + return r0 +} + +// MarkMessage provides a mock function with given fields: msg, metadata +func (_m *ConsumerGroupSession) MarkMessage(msg *sarama.ConsumerMessage, metadata string) { + _m.Called(msg, metadata) +} + +// MarkOffset provides a mock function with given fields: topic, partition, offset, metadata +func (_m *ConsumerGroupSession) MarkOffset(topic string, partition int32, offset int64, metadata string) { + _m.Called(topic, partition, offset, metadata) +} + +// MemberID provides a mock function with given fields: +func (_m *ConsumerGroupSession) MemberID() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// ResetOffset provides a mock function with given fields: topic, partition, offset, metadata +func (_m *ConsumerGroupSession) ResetOffset(topic string, partition int32, offset int64, metadata string) { + _m.Called(topic, partition, offset, metadata) +} From b4e61842a0a0e80135674602e1576c6cab73ec5d Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Tue, 14 Sep 2021 13:24:20 -0400 Subject: [PATCH 4/6] Use mockery for eth.RPCClient mocks Signed-off-by: Andrew Richardson --- Makefile | 1 + internal/contractgateway/rest2eth_test.go | 200 ++++++++++++---------- internal/eth/rpc_test.go | 58 +++---- internal/eth/rpcmock.go | 95 ---------- internal/events/eventstream_test.go | 160 ++++++++++------- internal/events/submanager_test.go | 26 ++- internal/events/subscription_test.go | 70 +++++--- mocks/ethmocks/rpc_client.go | 31 ++++ 8 files changed, 332 insertions(+), 309 deletions(-) delete mode 100644 internal/eth/rpcmock.go create mode 100644 mocks/ethmocks/rpc_client.go diff --git a/Makefile b/Makefile index 691e2106..3c85660b 100644 --- a/Makefile +++ b/Makefile @@ -60,6 +60,7 @@ endef $(eval $(call makemock, internal/contractregistry, ContractStore, contractregistrymocks)) $(eval $(call makemock, internal/contractregistry, RemoteRegistry, contractregistrymocks)) +$(eval $(call makemock, internal/eth, RPCClient, ethmocks)) $(eval $(call makemock, $(SARAMA_PATH), Client, saramamocks)) $(eval $(call makemock, $(SARAMA_PATH), ConsumerGroup, saramamocks)) $(eval $(call makemock, $(SARAMA_PATH), ConsumerGroupSession, saramamocks)) diff --git a/internal/contractgateway/rest2eth_test.go b/internal/contractgateway/rest2eth_test.go index bb19c350..babcd54e 100644 --- a/internal/contractgateway/rest2eth_test.go +++ b/internal/contractgateway/rest2eth_test.go @@ -21,7 +21,6 @@ import ( "fmt" "net/http" "net/http/httptest" - "reflect" "strings" "testing" @@ -33,10 +32,12 @@ import ( "github.com/hyperledger-labs/firefly-ethconnect/internal/events" "github.com/hyperledger-labs/firefly-ethconnect/internal/messages" "github.com/hyperledger-labs/firefly-ethconnect/mocks/contractregistrymocks" + "github.com/hyperledger-labs/firefly-ethconnect/mocks/ethmocks" "github.com/julienschmidt/httprouter" ethbinding "github.com/kaleido-io/ethbinding/pkg" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" ) type mockREST2EthDispatcher struct { @@ -89,21 +90,6 @@ func (m *mockGateway) PostDeploy(msg *messages.TransactionReceipt) error { func (m *mockGateway) AddRoutes(router *httprouter.Router) { return } func (m *mockGateway) Shutdown() { return } -type mockRPC struct { - capturedMethod string - capturedArgs []interface{} - mockError error - result interface{} -} - -func (m *mockRPC) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { - m.capturedMethod = method - m.capturedArgs = args - v := reflect.ValueOf(result) - v.Elem().Set(reflect.ValueOf(m.result)) - return m.mockError -} - type mockSubMgr struct { err error updateStreamErr error @@ -159,8 +145,8 @@ func newTestDeployMsg(t *testing.T, addr string) *contractregistry.DeployContrac } } -func newTestREST2Eth(dispatcher *mockREST2EthDispatcher) (*rest2eth, *mockRPC, *httprouter.Router) { - mockRPC := &mockRPC{} +func newTestREST2Eth(dispatcher *mockREST2EthDispatcher) (*rest2eth, *httprouter.Router) { + mockRPC := ðmocks.RPCClient{} gateway := &mockGateway{} contractResolver := &contractregistrymocks.ContractStore{} remoteRegistry := &contractregistrymocks.RemoteRegistry{} @@ -169,18 +155,17 @@ func newTestREST2Eth(dispatcher *mockREST2EthDispatcher) (*rest2eth, *mockRPC, * router := &httprouter.Router{} r.addRoutes(router) - return r, mockRPC, router + return r, router } -func newTestREST2EthAndMsg(dispatcher *mockREST2EthDispatcher, from, to string, bodyMap map[string]interface{}) (*rest2eth, *mockRPC, *httprouter.Router, *httptest.ResponseRecorder, *http.Request) { +func newTestREST2EthAndMsg(dispatcher *mockREST2EthDispatcher, from, to string, bodyMap map[string]interface{}) (*rest2eth, *httprouter.Router, *httptest.ResponseRecorder, *http.Request) { body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) res := httptest.NewRecorder() - r, mockRPC, router := newTestREST2Eth(dispatcher) - - return r, mockRPC, router, res, req + r, router := newTestREST2Eth(dispatcher) + return r, router, res, req } func TestSendTransactionAsyncSuccess(t *testing.T) { @@ -200,7 +185,7 @@ func TestSendTransactionAsyncSuccess(t *testing.T) { }, } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -242,7 +227,7 @@ func TestDeployContractAsyncSuccess(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -283,7 +268,7 @@ func TestDeployContractAsyncHDWallet(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -321,7 +306,7 @@ func TestDeployContractAsyncDuplicate(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "abi1").Return(&messages.DeployContract{}, nil, nil) mcr.On("CheckNameAvailable", "random", false).Return(fmt.Errorf("spent already")) @@ -363,7 +348,7 @@ func TestSendTransactionSyncSuccess(t *testing.T) { sendTransactionSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -405,7 +390,7 @@ func TestSendTransactionSyncFailure(t *testing.T) { sendTransactionSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -449,7 +434,7 @@ func TestSendTransactionSyncPostDeployErr(t *testing.T) { sendTransactionSyncReceipt: receipt, } - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) r.gw = &mockGateway{ postDeployError: fmt.Errorf("pop"), } @@ -497,7 +482,7 @@ func TestSendTransactionSyncViaABISuccess(t *testing.T) { sendTransactionSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", abi).Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -537,7 +522,7 @@ func TestDeployContractSyncSuccess(t *testing.T) { deployContractSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -578,7 +563,7 @@ func TestDeployContractSyncRemoteRegistryInstance(t *testing.T) { sendTransactionSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mrr := r.rr.(*contractregistrymocks.RemoteRegistry) mrr.On("LoadFactoryForInstance", "myinstance", false). Return(newTestDeployMsg(t, strings.TrimPrefix(to, "0x")), nil) @@ -602,7 +587,7 @@ func TestDeployContractSyncRemoteRegistryInstance500(t *testing.T) { bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) mrr := r.rr.(*contractregistrymocks.RemoteRegistry) mrr.On("LoadFactoryForInstance", "myinstance", false).Return(nil, fmt.Errorf("pop")) @@ -622,7 +607,7 @@ func TestDeployContractSyncRemoteRegistryInstance404(t *testing.T) { bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) mrr := r.rr.(*contractregistrymocks.RemoteRegistry) mrr.On("LoadFactoryForInstance", "myinstance", false).Return(nil, nil) @@ -642,7 +627,7 @@ func TestDeployContractSyncRemoteRegistryGateway500(t *testing.T) { bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) mrr := r.rr.(*contractregistrymocks.RemoteRegistry) mrr.On("LoadFactoryForGateway", "mygw", false).Return(nil, fmt.Errorf("pop")) @@ -662,7 +647,7 @@ func TestDeployContractSyncRemoteRegistryGateway404(t *testing.T) { bodyMap := make(map[string]interface{}) - r, _, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(&mockREST2EthDispatcher{}, "", "", bodyMap) mrr := r.rr.(*contractregistrymocks.RemoteRegistry) mrr.On("LoadFactoryForGateway", "mygw", false).Return(nil, nil) @@ -698,7 +683,7 @@ func TestDeployContractSyncRemoteRegistryGateway(t *testing.T) { sendTransactionSyncReceipt: receipt, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mrr := r.rr.(*contractregistrymocks.RemoteRegistry) mrr.On("LoadFactoryForGateway", "mygateway", false). Return(&newTestDeployMsg(t, strings.TrimPrefix(to, "0x")).DeployContract, nil) @@ -729,7 +714,7 @@ func TestSendTransactionSyncFail(t *testing.T) { sendTransactionSyncError: fmt.Errorf("pop"), } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -760,7 +745,7 @@ func TestSendTransactionAsyncFail(t *testing.T) { asyncDispatchError: fmt.Errorf("pop"), } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -789,7 +774,7 @@ func TestDeployContractAsyncFail(t *testing.T) { asyncDispatchError: fmt.Errorf("pop"), } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -821,7 +806,7 @@ func TestSendTransactionAsyncBadMethod(t *testing.T) { asyncDispatchError: fmt.Errorf("pop"), } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -851,7 +836,7 @@ func TestSendTransactionBadContract(t *testing.T) { asyncDispatchError: fmt.Errorf("pop"), } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("ResolveContractAddress", "badness").Return("my-contract", nil) mcr.On("GetContractByAddress", "my-contract").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) @@ -880,7 +865,7 @@ func TestSendTransactionUnknownRegisteredName(t *testing.T) { from := "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" dispatcher := &mockREST2EthDispatcher{} - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("ResolveContractAddress", "random").Return("", fmt.Errorf("unregistered")) @@ -909,7 +894,7 @@ func TestSendTransactionMissingContract(t *testing.T) { asyncDispatchError: fmt.Errorf("pop"), } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -936,7 +921,7 @@ func TestSendTransactionBadMethodABI(t *testing.T) { }, } - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8"). Return(&contractregistry.ContractInfo{ABI: "abi-id"}, nil) @@ -975,7 +960,7 @@ func TestSendTransactionBadEventABI(t *testing.T) { }, } - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8"). Return(&contractregistry.ContractInfo{ABI: "abi-id"}, nil) @@ -1014,7 +999,7 @@ func TestSendTransactionBadConstructorABI(t *testing.T) { }, } - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "testabi"). Return(&messages.DeployContract{ @@ -1051,7 +1036,7 @@ func TestSendTransactionDefaultConstructorABI(t *testing.T) { }, } - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "testabi"). Return(&messages.DeployContract{ @@ -1078,7 +1063,7 @@ func TestSendTransactionUnnamedParamsABI(t *testing.T) { }, } - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "testabi"). Return(&messages.DeployContract{ @@ -1119,7 +1104,7 @@ func TestSendTransactionBadFrom(t *testing.T) { asyncDispatchError: fmt.Errorf("pop"), } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1151,7 +1136,7 @@ func TestSendTransactionInvalidContract(t *testing.T) { }, } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(nil, fmt.Errorf("pop")) @@ -1182,7 +1167,7 @@ func TestDeployContractInvalidABI(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1?fly-sync", bytes.NewReader(body)) req.Header.Add("x-firefly-from", from) @@ -1218,7 +1203,7 @@ func TestSendTransactionInvalidMethod(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1251,7 +1236,7 @@ func TestSendTransactionParamInQuery(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1280,7 +1265,7 @@ func TestSendTransactionRegisteredName(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("ResolveContractAddress", "transponster").Return("c6c572a18d31ff36d661d680c0060307e038dc47", nil) mcr.On("GetContractByAddress", "c6c572a18d31ff36d661d680c0060307e038dc47").Return(&contractregistry.ContractInfo{ABI: "abi-id"}, nil) @@ -1310,7 +1295,7 @@ func TestSendTransactionMissingParam(t *testing.T) { }, } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1341,7 +1326,7 @@ func TestSendTransactionBadBody(t *testing.T) { }, } - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1368,18 +1353,22 @@ func TestCallMethodSuccess(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} - r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + mockRPC := r.rpc.(*ethmocks.RPCClient) + mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "latest"). + Run(func(args mock.Arguments) { + result := args[1].(*string) + *result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" + }). + Return(nil) req := httptest.NewRequest("GET", "/contracts/"+to+"/get", bytes.NewReader([]byte{})) - mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) - assert.Equal("eth_call", mockRPC.capturedMethod) - assert.Equal("latest", mockRPC.capturedArgs[1]) var reply map[string]interface{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) @@ -1389,6 +1378,7 @@ func TestCallMethodSuccess(t *testing.T) { assert.Equal("testing", reply["s"]) mcr.AssertExpectations(t) + mockRPC.AssertExpectations(t) } func TestCallMethodHDWalletSuccess(t *testing.T) { @@ -1401,19 +1391,23 @@ func TestCallMethodHDWalletSuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} from := "HD-u01234abcd-u01234abcd-12345" - r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + mockRPC := r.rpc.(*ethmocks.RPCClient) + mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "latest"). + Run(func(args mock.Arguments) { + result := args[1].(*string) + *result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" + }). + Return(nil) r.processor.(*mockProcessor).resolvedFrom = "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" req := httptest.NewRequest("GET", "/contracts/"+to+"/get?fly-from="+from, bytes.NewReader([]byte{})) - mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) - assert.Equal("eth_call", mockRPC.capturedMethod) - assert.Equal("latest", mockRPC.capturedArgs[1]) var reply map[string]interface{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) @@ -1423,6 +1417,7 @@ func TestCallMethodHDWalletSuccess(t *testing.T) { assert.Equal("testing", reply["s"]) mcr.AssertExpectations(t) + mockRPC.AssertExpectations(t) } func TestCallMethodHDWalletFail(t *testing.T) { @@ -1435,7 +1430,7 @@ func TestCallMethodHDWalletFail(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} from := "HD-u01234abcd-u01234abcd-12345" - r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1443,7 +1438,6 @@ func TestCallMethodHDWalletFail(t *testing.T) { r.processor.(*mockProcessor).resolvedFrom = "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" r.processor.(*mockProcessor).err = fmt.Errorf("pop") req := httptest.NewRequest("GET", "/contracts/"+to+"/get?fly-from="+from, bytes.NewReader([]byte{})) - mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -1463,18 +1457,22 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} - r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + mockRPC := r.rpc.(*ethmocks.RPCClient) + mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "0x3039"). + Run(func(args mock.Arguments) { + result := args[1].(*string) + *result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" + }). + Return(nil) req := httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=12345", bytes.NewReader([]byte{})) - mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) - assert.Equal("eth_call", mockRPC.capturedMethod) - assert.Equal("0x3039", mockRPC.capturedArgs[1]) var reply map[string]interface{} err := json.NewDecoder(res.Result().Body).Decode(&reply) assert.NoError(err) @@ -1484,40 +1482,51 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { assert.Equal("testing", reply["s"]) mcr.AssertExpectations(t) + mockRPC.AssertExpectations(t) to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} - r, mockRPC, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr = r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + mockRPC = r.rpc.(*ethmocks.RPCClient) + mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "0xab1234"). + Run(func(args mock.Arguments) { + result := args[1].(*string) + *result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" + }). + Return(nil) req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=0xab1234", bytes.NewReader([]byte{})) - mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) - assert.Equal("eth_call", mockRPC.capturedMethod) - assert.Equal("0xab1234", mockRPC.capturedArgs[1]) mcr.AssertExpectations(t) + mockRPC.AssertExpectations(t) to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} - r, mockRPC, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr = r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + mockRPC = r.rpc.(*ethmocks.RPCClient) + mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "pending"). + Run(func(args mock.Arguments) { + result := args[1].(*string) + *result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" + }). + Return(nil) req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=pending", bytes.NewReader([]byte{})) - mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(200, res.Result().StatusCode) - assert.Equal("eth_call", mockRPC.capturedMethod) - assert.Equal("pending", mockRPC.capturedArgs[1]) mcr.AssertExpectations(t) + mockRPC.AssertExpectations(t) } func TestCallMethodFail(t *testing.T) { @@ -1528,13 +1537,14 @@ func TestCallMethodFail(t *testing.T) { to := "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher := &mockREST2EthDispatcher{} - r, mockRPC, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + mockRPC := r.rpc.(*ethmocks.RPCClient) + mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "latest"). + Return(fmt.Errorf("pop")) - mockRPC.result = "" - mockRPC.mockError = fmt.Errorf("pop") req := httptest.NewRequest("GET", "/contracts/"+to+"/get", bytes.NewReader([]byte{})) router.ServeHTTP(res, req) @@ -1545,17 +1555,17 @@ func TestCallMethodFail(t *testing.T) { assert.Regexp("Call failed: pop", reply.Message) mcr.AssertExpectations(t) + mockRPC.AssertExpectations(t) to = "0x567a417717cb6c59ddc1035705f02c0fd1ab1872" dispatcher = &mockREST2EthDispatcher{} - r, mockRPC, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr = r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=ab1234", bytes.NewReader([]byte{})) - mockRPC.result = "0x000000000000000000000000000000000000000000000000000000000001e2400000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000774657374696e6700000000000000000000000000000000000000000000000000" router.ServeHTTP(res, req) assert.Equal(500, res.Result().StatusCode) @@ -1570,7 +1580,7 @@ func TestCallMethodViaABIBadAddress(t *testing.T) { to := "badness" dispatcher := &mockREST2EthDispatcher{} - r, _, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) + r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1593,7 +1603,7 @@ func TestSubscribeNoAddressNoSubMgr(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1620,7 +1630,7 @@ func TestSubscribeNoAddressUnknownEvent(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1648,7 +1658,7 @@ func TestSubscribeUnauthorized(t *testing.T) { auth.RegisterSecurityModule(&authtest.TestSecurityModule{}) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1675,7 +1685,7 @@ func TestSubscribeNoAddressMissingStream(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1700,7 +1710,7 @@ func TestSubscribeNoAddressSuccess(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1732,7 +1742,7 @@ func TestSubscribeWithAddressSuccess(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1765,7 +1775,7 @@ func TestSubscribeWithAddressBadAddress(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("ResolveContractAddress", "badness").Return("", fmt.Errorf("unregistered")) @@ -1794,7 +1804,7 @@ func TestSubscribeWithAddressSubmgrFailure(t *testing.T) { defer cleanup(dir) dispatcher := &mockREST2EthDispatcher{} - r, _, router := newTestREST2Eth(dispatcher) + r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) @@ -1835,7 +1845,7 @@ func TestSendTransactionWithIDAsyncSuccess(t *testing.T) { }, } - r, _, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) + r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) diff --git a/internal/eth/rpc_test.go b/internal/eth/rpc_test.go index 78f3834c..1d8eb51c 100644 --- a/internal/eth/rpc_test.go +++ b/internal/eth/rpc_test.go @@ -41,6 +41,25 @@ func (w *mockEthClient) Subscribe(ctx context.Context, namespace string, channel } func (w *mockEthClient) Close() {} +// mockRPCSubscription is used internally within this class for testing the wrapping layer itself +type mockRPCSubscription struct { + Namespace string + Args []interface{} + ErrChan chan error + MsgChan chan<- interface{} + Subscribed bool +} + +// Err returns the configured mock error channel +func (ms *mockRPCSubscription) Err() <-chan error { + return ms.ErrChan +} + +// Unsubscribe captures the unsubscribe call +func (ms *mockRPCSubscription) Unsubscribe() { + ms.Subscribed = false +} + func TestRPCWrapperConformsToInterface(t *testing.T) { // This test doesn't verify any interesting function, simply that the rpcWrapper // type mapper can be invoked without panics @@ -96,37 +115,14 @@ func TestRPCConnectFail(t *testing.T) { func TestSubscribeWrapper(t *testing.T) { assert := assert.New(t) - - mockRPC := NewMockRPCClientForAsync(nil) - var iRPC RPCClientAsync - iRPC = mockRPC - c := make(chan interface{}) - sub, err := iRPC.Subscribe(context.Background(), "testns", c, "arg1") - assert.NoError(err) - assert.Equal("testns", mockRPC.SubResult.Namespace) - assert.Equal([]interface{}{"arg1"}, mockRPC.SubResult.Args) - assert.True(mockRPC.SubResult.Subscribed) - assert.NotNil(sub.Err()) - sub.Unsubscribe() - assert.False(mockRPC.SubResult.Subscribed) - iRPC.(RPCClosable).Close() - assert.True(mockRPC.Closed) -} - -func TestCallContextWrapper(t *testing.T) { - assert := assert.New(t) - - mockRPC := NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { - *(res.(*string)) = "mock result" - }) - var iRPC RPCClient - iRPC = mockRPC - var strRetval string - err := iRPC.CallContext(context.Background(), &strRetval, "rpcmethod1", "arg1", "arg2") - assert.NoError(err) - assert.Equal("mock result", strRetval) - assert.Equal("rpcmethod1", mockRPC.MethodCapture) - assert.Equal([]interface{}{"arg1", "arg2"}, mockRPC.ArgsCapture) + ms := &mockRPCSubscription{ + ErrChan: make(chan error), + Subscribed: true, + } + w := &subWrapper{s: ms} + assert.NotNil(w.Err()) + w.Unsubscribe() + assert.Equal(false, ms.Subscribed) } func TestCallContextWrapperAuth(t *testing.T) { diff --git a/internal/eth/rpcmock.go b/internal/eth/rpcmock.go deleted file mode 100644 index 8207dbe9..00000000 --- a/internal/eth/rpcmock.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2019 Kaleido - -// 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 eth - -import ( - "context" -) - -// MockRPCSubscription allows convenient subscription mocking in other packages -type MockRPCSubscription struct { - Namespace string - Args []interface{} - ErrChan chan error - MsgChan chan<- interface{} - Subscribed bool -} - -// Err returns the configured mock error channel -func (ms *MockRPCSubscription) Err() <-chan error { - return ms.ErrChan -} - -// Unsubscribe captures the unsubscribe call -func (ms *MockRPCSubscription) Unsubscribe() { - ms.Subscribed = false -} - -// MockRPCClient implements RPCClientAll -type MockRPCClient struct { - // Requests for behaviour - callError error - resultWranger func(string, interface{}, ...interface{}) - // Captured results - SubscribeErr error - SubResult *MockRPCSubscription - MethodCapture string - ArgsCapture []interface{} - Closed bool -} - -// NewMockRPCClientForAsync contructs a mock client for async testing -func NewMockRPCClientForAsync(subscribeErr error) *MockRPCClient { - m := &MockRPCClient{ - SubscribeErr: subscribeErr, - SubResult: &MockRPCSubscription{ - Subscribed: true, - ErrChan: make(chan error), - }, - } - return m -} - -// NewMockRPCClientForSync contructs a mock client for sync testing -func NewMockRPCClientForSync(callErr error, resultWranger func(string, interface{}, ...interface{})) *MockRPCClient { - m := &MockRPCClient{ - callError: callErr, - resultWranger: resultWranger, - } - return m -} - -// CallContext invokes the supplied result wranger, and captures the args -func (m *MockRPCClient) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { - m.MethodCapture = method - m.ArgsCapture = args - if m.resultWranger != nil { - m.resultWranger(method, result, args...) - } - return m.callError -} - -// Subscribe returns the subscription already configured in the mock -func (m *MockRPCClient) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (RPCClientSubscription, error) { - m.SubResult.Namespace = namespace - m.SubResult.Args = args - m.SubResult.MsgChan = channel.(chan interface{}) - return &subWrapper{s: m.SubResult}, m.SubscribeErr -} - -// Close captures the fact close was called -func (m *MockRPCClient) Close() { - m.Closed = true -} diff --git a/internal/events/eventstream_test.go b/internal/events/eventstream_test.go index 82d148f1..62cd3be3 100644 --- a/internal/events/eventstream_test.go +++ b/internal/events/eventstream_test.go @@ -27,12 +27,13 @@ import ( "time" "github.com/hyperledger-labs/firefly-ethconnect/internal/errors" - "github.com/hyperledger-labs/firefly-ethconnect/internal/eth" "github.com/hyperledger-labs/firefly-ethconnect/internal/ethbind" "github.com/hyperledger-labs/firefly-ethconnect/internal/kvstore" + "github.com/hyperledger-labs/firefly-ethconnect/mocks/ethmocks" ethbinding "github.com/kaleido-io/ethbinding/pkg" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" ) func TestConstructorNoSpec(t *testing.T) { @@ -431,23 +432,32 @@ func setupTestSubscription(assert *assert.Assertions, sm *subscriptionMGR, strea callCount := 0 filterChangeCalls := 0 - rpc := eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { - callCount++ - log.Infof("UT %s call=%d", method, callCount) - if method == "eth_blockNumber" || method == "eth_newFilter" { - } else if method == "eth_getFilterLogs" { - *(res.(*[]*logEntry)) = testData[0:2] - } else if method == "eth_getFilterChanges" { - if filterChangeCalls == 0 { - *(res.(*[]*logEntry)) = testData[2:] - } else { - *(res.(*[]*logEntry)) = []*logEntry{} + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + res := args[1] + method := args[2].(string) + callCount++ + log.Infof("UT %s call=%d", method, callCount) + switch method { + case "eth_blockNumber": + // ignore + case "eth_newFilter": + // ignore + case "eth_getFilterLogs": + *(res.(*[]*logEntry)) = testData[0:2] + case "eth_getFilterChanges": + if filterChangeCalls == 0 { + *(res.(*[]*logEntry)) = testData[2:] + } else { + *(res.(*[]*logEntry)) = []*logEntry{} + } + filterChangeCalls++ + case "eth_getBlockByNumber": + *(res.(*ethbinding.Header)) = *testBlock } - filterChangeCalls++ - } else if method == "eth_getBlockByNumber" { - *(res.(*ethbinding.Header)) = *testBlock - } - }) + }). + Return(nil) sm.rpc = rpc event := ðbinding.ABIElementMarshaling{ @@ -500,31 +510,37 @@ func setupCatchupTestSubscription(assert *assert.Assertions, sm *subscriptionMGR callCount := 0 getLogsCalls := 0 - rpc := eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { - callCount++ - log.Infof("UT %s call=%d", method, callCount) - if method == "eth_blockNumber" { - (*(res.(*ethbinding.HexBigInt))).ToInt().SetString("501", 10) - } else if method == "eth_getLogs" { - if getLogsCalls == 0 { - // Catchup page with data - *(res.(*[]*logEntry)) = testData[0:2] - } else { - // Catchup page with no data + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + res := args[1] + method := args[2].(string) + callCount++ + log.Infof("UT %s call=%d", method, callCount) + switch method { + case "eth_blockNumber": + (*(res.(*ethbinding.HexBigInt))).ToInt().SetString("501", 10) + case "eth_getLogs": + if getLogsCalls == 0 { + // Catchup page with data + *(res.(*[]*logEntry)) = testData[0:2] + } else { + // Catchup page with no data + *(res.(*[]*logEntry)) = []*logEntry{} + } + getLogsCalls++ + assert.LessOrEqual(getLogsCalls, 2) + case "eth_getFilterLogs": + // First page after catchup + *(res.(*[]*logEntry)) = testData[2:] + case "eth_getFilterChanges": + // No further updates *(res.(*[]*logEntry)) = []*logEntry{} + case "eth_getBlockByNumber": + *(res.(*ethbinding.Header)) = *testBlock } - getLogsCalls++ - assert.LessOrEqual(getLogsCalls, 2) - } else if method == "eth_getFilterLogs" { - // First page after catchup - *(res.(*[]*logEntry)) = testData[2:] - } else if method == "eth_getFilterChanges" { - // No further updates - *(res.(*[]*logEntry)) = []*logEntry{} - } else if method == "eth_getBlockByNumber" { - *(res.(*ethbinding.Header)) = *testBlock - } - }) + }). + Return(nil) sm.rpc = rpc event := ðbinding.ABIElementMarshaling{ @@ -941,16 +957,22 @@ func TestCheckpointRecovery(t *testing.T) { var newFilterBlock uint64 sub := sm.subscriptions[s.ID] sub.filterStale = true - sub.rpc = eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { - if method == "eth_newFilter" { - newFilterBlock = args[0].(*ethFilter).FromBlock.ToInt().Uint64() - t.Logf("New filter block after checkpoint recovery: %d", newFilterBlock) - } else if method == "eth_getFilterChanges" { - *(res.(*[]*logEntry)) = []*logEntry{} - } else if method == "eth_uninstallFilter" { - *(res.(*bool)) = true - } - }) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + res := args[1] + method := args[2].(string) + if method == "eth_newFilter" { + newFilterBlock = args[3].(*ethFilter).FromBlock.ToInt().Uint64() + t.Logf("New filter block after checkpoint recovery: %d", newFilterBlock) + } else if method == "eth_getFilterChanges" { + *(res.(*[]*logEntry)) = []*logEntry{} + } else if method == "eth_uninstallFilter" { + *(res.(*bool)) = true + } + }). + Return(nil) + sub.rpc = rpc stream.resume() for stream.pollerDone { @@ -961,6 +983,7 @@ func TestCheckpointRecovery(t *testing.T) { time.Sleep(1 * time.Millisecond) } + rpc.AssertExpectations(t) } func TestWithoutCheckpointRecovery(t *testing.T) { @@ -984,17 +1007,23 @@ func TestWithoutCheckpointRecovery(t *testing.T) { var initialEndBlock string sub := sm.subscriptions[s.ID] sub.filterStale = true - sub.rpc = eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { - if method == "eth_blockNumber" { - } else if method == "eth_newFilter" { - initialEndBlock = args[0].(*ethFilter).ToBlock - t.Logf("New filter block after recovery with no checkpoint: %s", initialEndBlock) - } else if method == "eth_getFilterChanges" { - *(res.(*[]*logEntry)) = []*logEntry{} - } else if method == "eth_uninstallFilter" { - *(res.(*bool)) = true - } - }) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + res := args[1] + method := args[2].(string) + if method == "eth_blockNumber" { + } else if method == "eth_newFilter" { + initialEndBlock = args[3].(*ethFilter).ToBlock + t.Logf("New filter block after recovery with no checkpoint: %s", initialEndBlock) + } else if method == "eth_getFilterChanges" { + *(res.(*[]*logEntry)) = []*logEntry{} + } else if method == "eth_uninstallFilter" { + *(res.(*bool)) = true + } + }). + Return(nil) + sub.rpc = rpc stream.resume() for stream.pollerDone { @@ -1004,6 +1033,7 @@ func TestWithoutCheckpointRecovery(t *testing.T) { time.Sleep(1 * time.Millisecond) } + rpc.AssertExpectations(t) } func TestMarkStaleOnError(t *testing.T) { @@ -1026,7 +1056,12 @@ func TestMarkStaleOnError(t *testing.T) { sm.subscriptions[s.ID].filterStale = false sub := sm.subscriptions[s.ID] - sub.rpc = eth.NewMockRPCClientForSync(fmt.Errorf("filter not found"), nil) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_getFilterLogs", mock.Anything). + Return(fmt.Errorf("filter not found")) + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_uninstallFilter", mock.Anything). + Return(nil) + sub.rpc = rpc stream.resume() for stream.pollerDone { @@ -1036,6 +1071,7 @@ func TestMarkStaleOnError(t *testing.T) { time.Sleep(1 * time.Millisecond) } + rpc.AssertExpectations(t) } func TestStoreCheckpointLoadError(t *testing.T) { diff --git a/internal/events/submanager_test.go b/internal/events/submanager_test.go index d5d27344..2e984b9a 100644 --- a/internal/events/submanager_test.go +++ b/internal/events/submanager_test.go @@ -27,10 +27,12 @@ import ( "github.com/hyperledger-labs/firefly-ethconnect/internal/eth" "github.com/hyperledger-labs/firefly-ethconnect/internal/kvstore" + "github.com/hyperledger-labs/firefly-ethconnect/mocks/ethmocks" "github.com/julienschmidt/httprouter" ethbinding "github.com/kaleido-io/ethbinding/pkg" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" ) type mockWebSocket struct { @@ -71,7 +73,7 @@ func newMockWebSocket() *mockWebSocket { func newTestSubscriptionManager() *subscriptionMGR { smconf := &SubscriptionManagerConf{} sm := NewSubscriptionManager(smconf, nil, newMockWebSocket()).(*subscriptionMGR) - sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.rpc = ðmocks.RPCClient{} sm.db = kvstore.NewMockKV(nil) sm.config().WebhooksAllowPrivateIPs = true sm.config().EventPollingIntervalSec = 0 @@ -119,8 +121,16 @@ func TestActionAndSubscriptionLifecyle(t *testing.T) { dir := tempdir(t) subscriptionName := "testSub" defer cleanup(t, dir) + + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_blockNumber").Return(nil) + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_newFilter", mock.Anything).Return(nil) + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_getFilterLogs", mock.Anything).Return(nil) + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_uninstallFilter", mock.Anything).Return(nil) + sm := newTestSubscriptionManager() - sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.rpc = rpc + sm.db, _ = kvstore.NewLDBKeyValueStore(path.Join(dir, "db")) defer sm.db.Close() @@ -174,6 +184,7 @@ func TestActionAndSubscriptionLifecyle(t *testing.T) { defer svr.Close() sm = newTestSubscriptionManager() sm.conf.EventLevelDBPath = path.Join(dir, "db") + sm.rpc = rpc sm.rpcConf = ð.RPCConnOpts{URL: svr.URL} err = sm.Init() assert.NoError(err) @@ -198,7 +209,7 @@ func TestActionChildCleanup(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.rpc = ðmocks.RPCClient{} sm.db, _ = kvstore.NewLDBKeyValueStore(path.Join(dir, "db")) defer sm.db.Close() @@ -224,7 +235,7 @@ func TestStreamAndSubscriptionErrors(t *testing.T) { subscriptionName := "testSub" defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + sm.rpc = ðmocks.RPCClient{} sm.db, _ = kvstore.NewLDBKeyValueStore(path.Join(dir, "db")) defer sm.db.Close() @@ -256,7 +267,11 @@ func TestResetSubscriptionErrors(t *testing.T) { dir := tempdir(t) defer cleanup(t, dir) sm := newTestSubscriptionManager() - sm.rpc = eth.NewMockRPCClientForSync(nil, nil) + + rpc := ðmocks.RPCClient{} + sm.rpc = rpc + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_uninstallFilter", mock.Anything).Return(nil) + sm.db = kvstore.NewMockKV(fmt.Errorf("pop")) defer sm.db.Close() @@ -311,5 +326,4 @@ func TestRecoverErrors(t *testing.T) { assert.Equal(0, len(sm.streams)) assert.Equal(0, len(sm.subscriptions)) - } diff --git a/internal/events/subscription_test.go b/internal/events/subscription_test.go index e40ad86e..1879e183 100644 --- a/internal/events/subscription_test.go +++ b/internal/events/subscription_test.go @@ -20,12 +20,13 @@ import ( "math/big" "testing" - "github.com/hyperledger-labs/firefly-ethconnect/internal/eth" "github.com/hyperledger-labs/firefly-ethconnect/internal/ethbind" "github.com/hyperledger-labs/firefly-ethconnect/internal/kvstore" + "github.com/hyperledger-labs/firefly-ethconnect/mocks/ethmocks" ethbinding "github.com/kaleido-io/ethbinding/pkg" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" ) type mockSubMgr struct { @@ -73,7 +74,7 @@ func testSubInfo(event *ethbinding.ABIElementMarshaling) *SubscriptionInfo { func TestCreateWebhookSub(t *testing.T) { assert := assert.New(t) - rpc := eth.NewMockRPCClientForSync(nil, nil) + rpc := ðmocks.RPCClient{} event := ðbinding.ABIElementMarshaling{ Name: "glastonbury", Inputs: []ethbinding.ABIArgumentMarshaling{ @@ -113,7 +114,7 @@ func TestCreateWebhookSub(t *testing.T) { func TestCreateWebhookSubWithAddr(t *testing.T) { assert := assert.New(t) - rpc := eth.NewMockRPCClientForSync(nil, nil) + rpc := ðmocks.RPCClient{} m := &mockSubMgr{stream: newTestStream()} event := ðbinding.ABIElementMarshaling{ Name: "devcon", @@ -181,9 +182,11 @@ func TestRestoreSubscriptionBadType(t *testing.T) { func TestProcessEventsStaleFilter(t *testing.T) { assert := assert.New(t) - s := &subscription{ - rpc: eth.NewMockRPCClientForSync(fmt.Errorf("filter not found"), nil), - } + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_getFilterLogs", mock.Anything). + Return(fmt.Errorf("filter not found")) + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_uninstallFilter", mock.Anything).Return(nil) + s := &subscription{rpc: rpc} err := s.processNewEvents(context.Background()) assert.EqualError(err, "filter not found") assert.True(s.filterStale) @@ -191,14 +194,20 @@ func TestProcessEventsStaleFilter(t *testing.T) { func TestProcessEventsCannotProcess(t *testing.T) { assert := assert.New(t) - s := &subscription{ - rpc: eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_getFilterLogs", mock.Anything). + Run(func(args mock.Arguments) { + res := args[1] les := res.(*[]*logEntry) *les = append(*les, &logEntry{ Data: "0x no hex here sorry", }) - }), - lp: newLogProcessor("", ðbinding.ABIEvent{}, newTestStream()), + }). + Return(nil) + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_uninstallFilter", mock.Anything).Return(nil) + s := &subscription{ + rpc: rpc, + lp: newLogProcessor("", ðbinding.ABIEvent{}, newTestStream()), } err := s.processNewEvents(context.Background()) // We swallow the error in this case - as we simply couldn't read the event @@ -207,12 +216,16 @@ func TestProcessEventsCannotProcess(t *testing.T) { func TestInitialFilterFail(t *testing.T) { assert := assert.New(t) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_blockNumber"). + Return(fmt.Errorf("pop")) s := &subscription{ info: &SubscriptionInfo{}, - rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: rpc, } _, err := s.setInitialBlockHeight(context.Background()) assert.EqualError(err, "eth_blockNumber returned: pop") + rpc.AssertExpectations(t) } func TestInitialFilterBadInitialBlock(t *testing.T) { @@ -221,7 +234,7 @@ func TestInitialFilterBadInitialBlock(t *testing.T) { info: &SubscriptionInfo{ FromBlock: "!integer", }, - rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: ðmocks.RPCClient{}, } _, err := s.setInitialBlockHeight(context.Background()) assert.EqualError(err, "FromBlock cannot be parsed as a BigInt") @@ -241,60 +254,77 @@ func TestInitialFilterCustomInitialBlock(t *testing.T) { func TestRestartFilterFail(t *testing.T) { assert := assert.New(t) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_blockNumber"). + Return(fmt.Errorf("pop")) s := &subscription{ info: &SubscriptionInfo{}, - rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: rpc, } err := s.restartFilter(context.Background(), big.NewInt(0)) assert.EqualError(err, "eth_blockNumber returned: pop") + rpc.AssertExpectations(t) } func TestCreateFilterFail(t *testing.T) { assert := assert.New(t) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_newFilter", mock.Anything). + Return(fmt.Errorf("pop")) s := &subscription{ info: &SubscriptionInfo{}, - rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: rpc, } err := s.createFilter(context.Background(), big.NewInt(0)) assert.EqualError(err, "eth_newFilter returned: pop") + rpc.AssertExpectations(t) } func TestProcessCatchupBlocksFail(t *testing.T) { assert := assert.New(t) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_getLogs", mock.Anything). + Return(fmt.Errorf("pop")) s := &subscription{ info: &SubscriptionInfo{}, - rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: rpc, catchupBlock: big.NewInt(12345), } err := s.processCatchupBlocks(context.Background()) assert.EqualError(err, "eth_getLogs returned: pop") + rpc.AssertExpectations(t) } func TestEventTimestampFail(t *testing.T) { assert := assert.New(t) stream := newTestStream() lp := &logProcessor{stream: stream} - + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_getBlockByNumber", mock.Anything, mock.Anything). + Return(fmt.Errorf("pop")) s := &subscription{ lp: lp, info: &SubscriptionInfo{}, - rpc: eth.NewMockRPCClientForSync(fmt.Errorf("pop"), nil), + rpc: rpc, } l := &logEntry{Timestamp: 100} // set it to a fake value, should get overwritten s.getEventTimestamp(context.Background(), l) assert.Equal(l.Timestamp, uint64(0)) + rpc.AssertExpectations(t) } func TestUnsubscribe(t *testing.T) { assert := assert.New(t) + rpc := ðmocks.RPCClient{} + rpc.On("CallContext", mock.Anything, mock.Anything, "eth_uninstallFilter", mock.Anything). + Return(fmt.Errorf("pop")) s := &subscription{ - rpc: eth.NewMockRPCClientForSync(nil, func(method string, res interface{}, args ...interface{}) { - *(res.(*bool)) = true - }), + rpc: rpc, } err := s.unsubscribe(context.Background(), true) assert.NoError(err) assert.True(s.filterStale) + rpc.AssertExpectations(t) } func TestLoadCheckpointBadJSON(t *testing.T) { diff --git a/mocks/ethmocks/rpc_client.go b/mocks/ethmocks/rpc_client.go new file mode 100644 index 00000000..e128a48e --- /dev/null +++ b/mocks/ethmocks/rpc_client.go @@ -0,0 +1,31 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +package ethmocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" +) + +// RPCClient is an autogenerated mock type for the RPCClient type +type RPCClient struct { + mock.Mock +} + +// CallContext provides a mock function with given fields: ctx, result, method, args +func (_m *RPCClient) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { + var _ca []interface{} + _ca = append(_ca, ctx, result, method) + _ca = append(_ca, args...) + ret := _m.Called(_ca...) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, interface{}, string, ...interface{}) error); ok { + r0 = rf(ctx, result, method, args...) + } else { + r0 = ret.Error(0) + } + + return r0 +} From 116c307ed34e28985dcf2010d480192af1c81cd5 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Wed, 15 Sep 2021 15:36:56 -0400 Subject: [PATCH 5/6] Add helpers for common conditions in rest2eth_test Signed-off-by: Andrew Richardson --- internal/contractgateway/rest2eth_test.go | 117 ++++++++++------------ 1 file changed, 53 insertions(+), 64 deletions(-) diff --git a/internal/contractgateway/rest2eth_test.go b/internal/contractgateway/rest2eth_test.go index babcd54e..0c0267f8 100644 --- a/internal/contractgateway/rest2eth_test.go +++ b/internal/contractgateway/rest2eth_test.go @@ -168,6 +168,15 @@ func newTestREST2EthAndMsg(dispatcher *mockREST2EthDispatcher, from, to string, return r, router, res, req } +func expectContractSuccess(t *testing.T, mcr *contractregistrymocks.ContractStore, address string) { + mcr.On("GetContractByAddress", address).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) + expectABISuccess(t, mcr, "abi1") +} + +func expectABISuccess(t *testing.T, mcr *contractregistrymocks.ContractStore, abiID string) { + mcr.On("GetABIByID", abiID).Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) +} + func TestSendTransactionAsyncSuccess(t *testing.T) { assert := assert.New(t) dir := tempdir() @@ -187,8 +196,7 @@ func TestSendTransactionAsyncSuccess(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) req.Header.Set("X-Firefly-PrivateFrom", "0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90") req.Header.Set("X-Firefly-PrivateFor", "0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745,0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C") @@ -229,7 +237,7 @@ func TestDeployContractAsyncSuccess(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "abi1") body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1?fly-privateFrom=0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90&fly-privateFor=0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745&fly-privateFor=0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C", bytes.NewReader(body)) @@ -270,7 +278,7 @@ func TestDeployContractAsyncHDWallet(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "abi1") body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1", bytes.NewReader(body)) @@ -308,7 +316,7 @@ func TestDeployContractAsyncDuplicate(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "abi1").Return(&messages.DeployContract{}, nil, nil) + expectABISuccess(t, mcr, "abi1") mcr.On("CheckNameAvailable", "random", false).Return(fmt.Errorf("spent already")) body, _ := json.Marshal(&bodyMap) @@ -350,8 +358,7 @@ func TestSendTransactionSyncSuccess(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) @@ -392,8 +399,7 @@ func TestSendTransactionSyncFailure(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) @@ -439,8 +445,7 @@ func TestSendTransactionSyncPostDeployErr(t *testing.T) { postDeployError: fmt.Errorf("pop"), } mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) @@ -484,7 +489,7 @@ func TestSendTransactionSyncViaABISuccess(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", abi).Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, abi) body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/"+abi+"/"+to+"/set?fly-sync&fly-ethvalue=1234", bytes.NewReader(body)) @@ -524,7 +529,7 @@ func TestDeployContractSyncSuccess(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "abi1") body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1?fly-sync", bytes.NewReader(body)) @@ -716,8 +721,7 @@ func TestSendTransactionSyncFail(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) req.Header.Set("x-firefly-sync", "true") router.ServeHTTP(res, req) @@ -747,8 +751,7 @@ func TestSendTransactionAsyncFail(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) router.ServeHTTP(res, req) @@ -776,7 +779,7 @@ func TestDeployContractAsyncFail(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, "", bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "abi1") body, _ := json.Marshal(&bodyMap) req := httptest.NewRequest("POST", "/abis/abi1", bytes.NewReader(body)) @@ -808,8 +811,7 @@ func TestSendTransactionAsyncBadMethod(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) router.ServeHTTP(res, req) @@ -839,8 +841,7 @@ func TestSendTransactionBadContract(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("ResolveContractAddress", "badness").Return("my-contract", nil) - mcr.On("GetContractByAddress", "my-contract").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, "my-contract") router.ServeHTTP(res, req) @@ -896,8 +897,7 @@ func TestSendTransactionMissingContract(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) router.ServeHTTP(res, req) @@ -1106,8 +1106,7 @@ func TestSendTransactionBadFrom(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) router.ServeHTTP(res, req) @@ -1205,8 +1204,7 @@ func TestSendTransactionInvalidMethod(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) req := httptest.NewRequest("POST", "/contracts/"+to+"/shazaam", bytes.NewReader([]byte("{}"))) req.Header.Set("x-firefly-from", from) @@ -1238,8 +1236,7 @@ func TestSendTransactionParamInQuery(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&fly-ethvalue=12345", bytes.NewReader([]byte("{}"))) req.Header.Set("x-firefly-from", from) @@ -1268,8 +1265,7 @@ func TestSendTransactionRegisteredName(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) mcr.On("ResolveContractAddress", "transponster").Return("c6c572a18d31ff36d661d680c0060307e038dc47", nil) - mcr.On("GetContractByAddress", "c6c572a18d31ff36d661d680c0060307e038dc47").Return(&contractregistry.ContractInfo{ABI: "abi-id"}, nil) - mcr.On("GetABIByID", "abi-id").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, "c6c572a18d31ff36d661d680c0060307e038dc47") req := httptest.NewRequest("POST", "/contracts/"+to+"/set?i=999&s=msg&fly-ethvalue=12345", bytes.NewReader([]byte("{}"))) req.Header.Set("x-firefly-from", from) @@ -1297,8 +1293,7 @@ func TestSendTransactionMissingParam(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) router.ServeHTTP(res, req) @@ -1328,8 +1323,7 @@ func TestSendTransactionBadBody(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) req := httptest.NewRequest("POST", "/contracts/"+to+"/set?x=999", bytes.NewReader([]byte(":not json or yaml"))) req.Header.Set("x-firefly-from", from) @@ -1355,8 +1349,8 @@ func TestCallMethodSuccess(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) + mockRPC := r.rpc.(*ethmocks.RPCClient) mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "latest"). Run(func(args mock.Arguments) { @@ -1393,8 +1387,8 @@ func TestCallMethodHDWalletSuccess(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) + mockRPC := r.rpc.(*ethmocks.RPCClient) mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "latest"). Run(func(args mock.Arguments) { @@ -1432,8 +1426,7 @@ func TestCallMethodHDWalletFail(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) r.processor.(*mockProcessor).resolvedFrom = "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8" r.processor.(*mockProcessor).err = fmt.Errorf("pop") @@ -1459,8 +1452,8 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) + mockRPC := r.rpc.(*ethmocks.RPCClient) mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "0x3039"). Run(func(args mock.Arguments) { @@ -1489,8 +1482,8 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { r, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr = r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) + mockRPC = r.rpc.(*ethmocks.RPCClient) mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "0xab1234"). Run(func(args mock.Arguments) { @@ -1511,8 +1504,8 @@ func TestCallReadOnlyMethodViaPOSTSuccess(t *testing.T) { r, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr = r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) + mockRPC = r.rpc.(*ethmocks.RPCClient) mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "pending"). Run(func(args mock.Arguments) { @@ -1539,8 +1532,8 @@ func TestCallMethodFail(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) + mockRPC := r.rpc.(*ethmocks.RPCClient) mockRPC.On("CallContext", mock.Anything, mock.Anything, "eth_call", mock.Anything, "latest"). Return(fmt.Errorf("pop")) @@ -1562,8 +1555,7 @@ func TestCallMethodFail(t *testing.T) { r, router, res, _ = newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr = r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) req = httptest.NewRequest("POST", "/contracts/"+to+"/get?fly-blocknumber=ab1234", bytes.NewReader([]byte{})) router.ServeHTTP(res, req) @@ -1582,7 +1574,7 @@ func TestCallMethodViaABIBadAddress(t *testing.T) { r, router, res, _ := newTestREST2EthAndMsg(dispatcher, "", to, map[string]interface{}{}) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "ABI1") req := httptest.NewRequest("GET", "/abis/ABI1/badaddress/get", bytes.NewReader([]byte{})) router.ServeHTTP(res, req) @@ -1605,7 +1597,7 @@ func TestSubscribeNoAddressNoSubMgr(t *testing.T) { r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "ABI1") bodyBytes, _ := json.Marshal(&map[string]string{ "stream": "stream1", @@ -1632,7 +1624,7 @@ func TestSubscribeNoAddressUnknownEvent(t *testing.T) { r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "ABI1") bodyBytes, _ := json.Marshal(&map[string]string{ "stream": "stream1", @@ -1660,7 +1652,7 @@ func TestSubscribeUnauthorized(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "ABI1") bodyBytes, _ := json.Marshal(&map[string]string{ "stream": "stream1", @@ -1687,7 +1679,7 @@ func TestSubscribeNoAddressMissingStream(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "ABI1") r.subMgr = &mockSubMgr{} bodyBytes, _ := json.Marshal(&map[string]string{}) @@ -1712,7 +1704,7 @@ func TestSubscribeNoAddressSuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetABIByID", "ABI1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectABISuccess(t, mcr, "ABI1") sm := &mockSubMgr{ sub: &events.SubscriptionInfo{ID: "sub1", Name: "stream-without-address"}, @@ -1744,8 +1736,7 @@ func TestSubscribeWithAddressSuccess(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") sm := &mockSubMgr{ sub: &events.SubscriptionInfo{ID: "sub1"}, @@ -1806,8 +1797,7 @@ func TestSubscribeWithAddressSubmgrFailure(t *testing.T) { dispatcher := &mockREST2EthDispatcher{} r, router := newTestREST2Eth(dispatcher) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8").Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, "0x66c5fe653e7a9ebb628a6d40f0452d1e358baee8") r.subMgr = &mockSubMgr{ err: fmt.Errorf("pop"), @@ -1847,8 +1837,7 @@ func TestSendTransactionWithIDAsyncSuccess(t *testing.T) { r, router, res, req := newTestREST2EthAndMsg(dispatcher, from, to, bodyMap) mcr := r.cr.(*contractregistrymocks.ContractStore) - mcr.On("GetContractByAddress", to).Return(&contractregistry.ContractInfo{ABI: "abi1"}, nil) - mcr.On("GetABIByID", "abi1").Return(&newTestDeployMsg(t, "").DeployContract, nil, nil) + expectContractSuccess(t, mcr, to) req.Header.Set("X-Firefly-PrivateFrom", "0xdC416B907857Fa8c0e0d55ec21766Ee3546D5f90") req.Header.Set("X-Firefly-PrivateFor", "0xE7E32f0d5A2D55B2aD27E0C2d663807F28f7c745,0xB92F8CebA52fFb5F08f870bd355B1d32f0fd9f7C") From bf07afd2406aff5f0e55ca50467951f9764ff646 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Mon, 20 Sep 2021 17:57:24 -0400 Subject: [PATCH 6/6] Don't download sarama unless actually building mocks Previously it was downloading as soon as the Makefile was invoked, due to the inline "go list" command. Signed-off-by: Andrew Richardson --- Makefile | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index 3c85660b..03cf429e 100644 --- a/Makefile +++ b/Makefile @@ -7,8 +7,6 @@ BINARY_WIN=$(BINARY_NAME)-win GOBIN := $(shell $(VGO) env GOPATH)/bin MOCKERY := $(GOBIN)/mockery -SARAMA_PATH := $(shell $(VGO) list -f '{{.Dir}}' github.com/Shopify/sarama) - .DELETE_ON_ERROR: GOFILES := $(shell find . -name '*.go' -print) @@ -51,17 +49,19 @@ build-win: ${MOCKERY}: $(VGO) install github.com/vektra/mockery/cmd/mockery@latest +sarama: + $(eval SARAMA_PATH := $(shell $(VGO) list -f '{{.Dir}}' github.com/Shopify/sarama)) define makemock mocks: mocks-$(strip $(1))-$(strip $(2)) -mocks-$(strip $(1))-$(strip $(2)): ${MOCKERY} +mocks-$(strip $(1))-$(strip $(2)): ${MOCKERY} sarama ${MOCKERY} --case underscore --dir $(1) --name $(2) --outpkg $(3) --output mocks/$(strip $(3)) endef $(eval $(call makemock, internal/contractregistry, ContractStore, contractregistrymocks)) $(eval $(call makemock, internal/contractregistry, RemoteRegistry, contractregistrymocks)) $(eval $(call makemock, internal/eth, RPCClient, ethmocks)) -$(eval $(call makemock, $(SARAMA_PATH), Client, saramamocks)) -$(eval $(call makemock, $(SARAMA_PATH), ConsumerGroup, saramamocks)) -$(eval $(call makemock, $(SARAMA_PATH), ConsumerGroupSession, saramamocks)) -$(eval $(call makemock, $(SARAMA_PATH), ConsumerGroupClaim, saramamocks)) +$(eval $(call makemock, $$(SARAMA_PATH), Client, saramamocks)) +$(eval $(call makemock, $$(SARAMA_PATH), ConsumerGroup, saramamocks)) +$(eval $(call makemock, $$(SARAMA_PATH), ConsumerGroupSession, saramamocks)) +$(eval $(call makemock, $$(SARAMA_PATH), ConsumerGroupClaim, saramamocks))