test_: improvements for browser connect tests

This commit is contained in:
Sale Djenic 2024-09-19 20:24:28 +02:00 committed by saledjenic
parent 8ddde51445
commit d6565375c1
13 changed files with 405 additions and 425 deletions

View File

@ -1,52 +1,17 @@
package connector
import (
"database/sql"
"context"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
gethrpc "github.com/ethereum/go-ethereum/rpc"
"github.com/status-im/status-go/params"
statusRPC "github.com/status-im/status-go/rpc"
"github.com/status-im/status-go/services/connector/commands"
"github.com/status-im/status-go/t/helpers"
"github.com/status-im/status-go/transactions/fake"
"github.com/status-im/status-go/walletdatabase"
)
func createDB(t *testing.T) (*sql.DB, func()) {
db, cleanup, err := helpers.SetupTestSQLDB(walletdatabase.DbInitializer{}, "provider-tests-")
require.NoError(t, err)
return db, func() { require.NoError(t, cleanup()) }
}
func setupTestAPI(t *testing.T) (*API, func()) {
db, cancel := createDB(t)
txServiceMockCtrl := gomock.NewController(t)
server, _ := fake.NewTestServer(txServiceMockCtrl)
// Creating a dummy status node to simulate what it's done in get_status_node.go
upstreamConfig := params.UpstreamRPCConfig{
URL: "https://mainnet.infura.io/v3/fake",
Enabled: true,
}
client := gethrpc.DialInProc(server)
rpcClient, err := statusRPC.NewClient(client, 1, upstreamConfig, nil, db, nil)
require.NoError(t, err)
service := NewService(db, rpcClient, nil)
return NewAPI(service), cancel
}
func TestCallRPC(t *testing.T) {
api, cancel := setupTestAPI(t)
defer cancel()
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
tests := []struct {
request string
@ -74,9 +39,10 @@ func TestCallRPC(t *testing.T) {
},
}
ctx := context.Background()
for _, tt := range tests {
t.Run(tt.request, func(t *testing.T) {
_, err := api.CallRPC(tt.request)
_, err := state.api.CallRPC(ctx, tt.request)
require.Error(t, err)
require.Equal(t, tt.expectError, err)
})

View File

@ -9,50 +9,44 @@ import (
)
func TestFailToGetAccountWithMissingDAppFields(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &AccountsCommand{Db: db}
state, close := setupCommand(t, Method_EthAccounts)
t.Cleanup(close)
// Missing DApp fields
request, err := ConstructRPCRequest("eth_accounts", []interface{}{}, nil)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestMissingDAppData, err)
assert.Empty(t, result)
}
func TestFailToGetAccountForUnpermittedDApp(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &AccountsCommand{Db: db}
state, close := setupCommand(t, Method_EthAccounts)
t.Cleanup(close)
request, err := ConstructRPCRequest("eth_accounts", []interface{}{}, &testDAppData)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrDAppIsNotPermittedByUser, err)
assert.Empty(t, result)
}
func TestGetAccountForPermittedDApp(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &AccountsCommand{Db: db}
state, close := setupCommand(t, Method_EthAccounts)
t.Cleanup(close)
sharedAccount := types.HexToAddress("0x6d0aa2a774b74bb1d36f97700315adf962c69fcg")
err := PersistDAppData(db, testDAppData, sharedAccount, 0x123)
err := PersistDAppData(state.walletDb, testDAppData, sharedAccount, 0x123)
assert.NoError(t, err)
request, err := ConstructRPCRequest("eth_accounts", []interface{}{}, &testDAppData)
assert.NoError(t, err)
expectedResponse := FormatAccountAddressToResponse(sharedAccount)
response, err := cmd.Execute(request)
response, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, expectedResponse, response)
}

View File

@ -1,7 +1,6 @@
package commands
import (
"database/sql"
"fmt"
"strconv"
"testing"
@ -9,54 +8,31 @@ import (
"github.com/stretchr/testify/assert"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/params"
"github.com/status-im/status-go/services/connector/chainutils"
walletCommon "github.com/status-im/status-go/services/wallet/common"
)
func setupNetworks(db *sql.DB) *ChainIDCommand {
nm := NetworkManagerMock{}
nm.SetNetworks([]*params.Network{
{
ChainID: walletCommon.EthereumMainnet,
},
{
ChainID: walletCommon.EthereumGoerli,
},
})
cmd := &ChainIDCommand{
Db: db,
NetworkManager: &nm,
}
return cmd
}
func TestFailToGetChainIdWithMissingDAppFields(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := setupNetworks(db)
state, close := setupCommand(t, Method_EthChainId)
t.Cleanup(close)
// Missing DApp fields
request, err := ConstructRPCRequest("eth_chainId", []interface{}{}, nil)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestMissingDAppData, err)
assert.Empty(t, result)
}
func TestGetDefaultChainIdForUnpermittedDApp(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := setupNetworks(db)
state, close := setupCommand(t, Method_EthChainId)
t.Cleanup(close)
request, err := ConstructRPCRequest("eth_chainId", []interface{}{}, &testDAppData)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
chainId, err := chainutils.GetHexChainID(strconv.FormatUint(walletCommon.EthereumMainnet, 16))
assert.NoError(t, err)
@ -64,21 +40,19 @@ func TestGetDefaultChainIdForUnpermittedDApp(t *testing.T) {
}
func TestGetChainIdForPermittedDApp(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := setupNetworks(db)
state, close := setupCommand(t, Method_EthChainId)
t.Cleanup(close)
sharedAccount := types.HexToAddress("0x6d0aa2a774b74bb1d36f97700315adf962c69fcg")
chainID := uint64(0x123)
err := PersistDAppData(db, testDAppData, sharedAccount, chainID)
err := PersistDAppData(state.walletDb, testDAppData, sharedAccount, chainID)
assert.NoError(t, err)
request, err := ConstructRPCRequest("eth_chainId", []interface{}{}, &testDAppData)
assert.NoError(t, err)
response, err := cmd.Execute(request)
response, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
chainId := fmt.Sprintf(`0x%s`, strconv.FormatUint(chainID, 16))
assert.Equal(t, chainId, response)

View File

@ -21,25 +21,21 @@ func preparePersonalSignRequest(dApp signal.ConnectorDApp, challenge, address st
}
func TestFailToPersonalSignWithMissingDAppFields(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &PersonalSignCommand{Db: db}
state, close := setupCommand(t, Method_PersonalSign)
t.Cleanup(close)
// Missing DApp fields
request, err := ConstructRPCRequest("personal_sign", []interface{}{}, nil)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestMissingDAppData, err)
assert.Empty(t, result)
}
func TestFailToPersonalSignForUnpermittedDApp(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &PersonalSignCommand{Db: db}
state, close := setupCommand(t, Method_PersonalSign)
t.Cleanup(close)
request, err := preparePersonalSignRequest(testDAppData,
"0x506c65617365207369676e2074686973206d65737361676520746f20636f6e6669726d20796f7572206964656e746974792e",
@ -47,37 +43,28 @@ func TestFailToPersonalSignForUnpermittedDApp(t *testing.T) {
)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrDAppIsNotPermittedByUser, err)
assert.Empty(t, result)
}
func TestFailToPersonalSignWithoutParams(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &PersonalSignCommand{Db: db}
state, close := setupCommand(t, Method_PersonalSign)
t.Cleanup(close)
request, err := ConstructRPCRequest("personal_sign", nil, &testDAppData)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrEmptyRPCParams, err)
assert.Empty(t, result)
}
func TestFailToPersonalSignWithSignalTimout(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
state, close := setupCommand(t, Method_PersonalSign)
t.Cleanup(close)
clientHandler := NewClientSideHandler()
cmd := &PersonalSignCommand{
Db: db,
ClientHandler: clientHandler,
}
err := PersistDAppData(db, testDAppData, types.Address{0x01}, uint64(0x1))
err := PersistDAppData(state.walletDb, testDAppData, types.Address{0x01}, uint64(0x1))
assert.NoError(t, err)
request, err := preparePersonalSignRequest(testDAppData,
@ -89,25 +76,18 @@ func TestFailToPersonalSignWithSignalTimout(t *testing.T) {
backupWalletResponseMaxInterval := WalletResponseMaxInterval
WalletResponseMaxInterval = 1 * time.Millisecond
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrWalletResponseTimeout, err)
WalletResponseMaxInterval = backupWalletResponseMaxInterval
}
func TestPersonalSignWithSignalAccepted(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
state, close := setupCommand(t, Method_PersonalSign)
t.Cleanup(close)
fakedSignature := "0x051"
clientHandler := NewClientSideHandler()
cmd := &PersonalSignCommand{
Db: db,
ClientHandler: clientHandler,
}
err := PersistDAppData(db, testDAppData, types.Address{0x01}, uint64(0x1))
err := PersistDAppData(state.walletDb, testDAppData, types.Address{0x01}, uint64(0x1))
assert.NoError(t, err)
challenge := "0x506c65617365207369676e2074686973206d65737361676520746f20636f6e6669726d20796f7572206964656e746974792e"
@ -128,7 +108,7 @@ func TestPersonalSignWithSignalAccepted(t *testing.T) {
assert.Equal(t, ev.Challenge, challenge)
assert.Equal(t, ev.Address, address)
err = clientHandler.PersonalSignAccepted(PersonalSignAcceptedArgs{
err = state.handler.PersonalSignAccepted(PersonalSignAcceptedArgs{
Signature: fakedSignature,
RequestID: ev.RequestID,
})
@ -137,23 +117,16 @@ func TestPersonalSignWithSignalAccepted(t *testing.T) {
}))
t.Cleanup(signal.ResetMobileSignalHandler)
response, err := cmd.Execute(request)
response, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, response, fakedSignature)
}
func TestPersonalSignWithSignalRejected(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
state, close := setupCommand(t, Method_PersonalSign)
t.Cleanup(close)
clientHandler := NewClientSideHandler()
cmd := &PersonalSignCommand{
Db: db,
ClientHandler: clientHandler,
}
err := PersistDAppData(db, testDAppData, types.Address{0x01}, uint64(0x1))
err := PersistDAppData(state.walletDb, testDAppData, types.Address{0x01}, uint64(0x1))
assert.NoError(t, err)
challenge := "0x506c65617365207369676e2074686973206d65737361676520746f20636f6e6669726d20796f7572206964656e746974792e"
@ -172,7 +145,7 @@ func TestPersonalSignWithSignalRejected(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = clientHandler.PersonalSignRejected(RejectedArgs{
err = state.handler.PersonalSignRejected(RejectedArgs{
RequestID: ev.RequestID,
})
assert.NoError(t, err)
@ -180,6 +153,6 @@ func TestPersonalSignWithSignalRejected(t *testing.T) {
}))
t.Cleanup(signal.ResetMobileSignalHandler)
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrPersonalSignRejectedByUser, err)
}

View File

@ -14,30 +14,21 @@ import (
)
func TestFailToRequestAccountsWithMissingDAppFields(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &RequestAccountsCommand{Db: db}
state, close := setupCommand(t, Method_EthRequestAccounts)
t.Cleanup(close)
// Missing DApp fields
request, err := ConstructRPCRequest("eth_requestAccounts", []interface{}{}, nil)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestMissingDAppData, err)
assert.Empty(t, result)
}
func TestRequestAccountsWithSignalTimeout(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
clientHandler := NewClientSideHandler()
cmd := &RequestAccountsCommand{
ClientHandler: clientHandler,
Db: db,
}
state, close := setupCommand(t, Method_EthRequestAccounts)
t.Cleanup(close)
request, err := prepareSendTransactionRequest(testDAppData, types.Address{0x01})
assert.NoError(t, err)
@ -45,21 +36,14 @@ func TestRequestAccountsWithSignalTimeout(t *testing.T) {
backupWalletResponseMaxInterval := WalletResponseMaxInterval
WalletResponseMaxInterval = 1 * time.Millisecond
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrWalletResponseTimeout, err)
WalletResponseMaxInterval = backupWalletResponseMaxInterval
}
func TestRequestAccountsAcceptedAndRequestAgain(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
clientHandler := NewClientSideHandler()
cmd := &RequestAccountsCommand{
ClientHandler: clientHandler,
Db: db,
}
state, close := setupCommand(t, Method_EthRequestAccounts)
t.Cleanup(close)
request, err := ConstructRPCRequest("eth_requestAccounts", []interface{}{}, &testDAppData)
assert.NoError(t, err)
@ -78,7 +62,7 @@ func TestRequestAccountsAcceptedAndRequestAgain(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = clientHandler.RequestAccountsAccepted(RequestAccountsAcceptedArgs{
err = state.handler.RequestAccountsAccepted(RequestAccountsAcceptedArgs{
RequestID: ev.RequestID,
Account: accountAddress,
ChainID: walletCommon.EthereumMainnet,
@ -91,13 +75,13 @@ func TestRequestAccountsAcceptedAndRequestAgain(t *testing.T) {
t.Cleanup(signal.ResetMobileSignalHandler)
expectedResponse := FormatAccountAddressToResponse(accountAddress)
response, err := cmd.Execute(request)
response, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
assert.NoError(t, err)
assert.Equal(t, expectedResponse, response)
// Check dApp in the database
dApp, err := persistence.SelectDAppByUrl(db, request.URL)
dApp, err := persistence.SelectDAppByUrl(state.walletDb, request.URL)
assert.NoError(t, err)
assert.Equal(t, request.Name, dApp.Name)
assert.Equal(t, request.IconURL, dApp.IconURL)
@ -105,7 +89,7 @@ func TestRequestAccountsAcceptedAndRequestAgain(t *testing.T) {
assert.Equal(t, walletCommon.EthereumMainnet, dApp.ChainID)
// This should not invoke UI side
response, err = cmd.Execute(request)
response, err = state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, expectedResponse, response)
@ -113,15 +97,8 @@ func TestRequestAccountsAcceptedAndRequestAgain(t *testing.T) {
}
func TestRequestAccountsRejected(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
clientHandler := NewClientSideHandler()
cmd := &RequestAccountsCommand{
ClientHandler: clientHandler,
Db: db,
}
state, close := setupCommand(t, Method_EthRequestAccounts)
t.Cleanup(close)
request, err := ConstructRPCRequest("eth_requestAccounts", []interface{}{}, &testDAppData)
assert.NoError(t, err)
@ -137,7 +114,7 @@ func TestRequestAccountsRejected(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = clientHandler.RequestAccountsRejected(RejectedArgs{
err = state.handler.RequestAccountsRejected(RejectedArgs{
RequestID: ev.RequestID,
})
assert.NoError(t, err)
@ -145,6 +122,6 @@ func TestRequestAccountsRejected(t *testing.T) {
}))
t.Cleanup(signal.ResetMobileSignalHandler)
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestAccountsRejectedByUser, err)
}

View File

@ -7,19 +7,21 @@ import (
)
func TestFailToRequestPermissionsWithMissingDAppFields(t *testing.T) {
cmd := &RequestPermissionsCommand{}
state, close := setupCommand(t, Method_RequestPermissions)
t.Cleanup(close)
// Missing DApp fields
request, err := ConstructRPCRequest("wallet_requestPermissions", []interface{}{}, nil)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestMissingDAppData, err)
assert.Empty(t, result)
}
func TestRequestPermissionsResponse(t *testing.T) {
cmd := &RequestPermissionsCommand{}
state, close := setupCommand(t, Method_RequestPermissions)
t.Cleanup(close)
testCases := []struct {
name string
@ -87,7 +89,7 @@ func TestRequestPermissionsResponse(t *testing.T) {
request, err := ConstructRPCRequest("wallet_requestPermissions", tc.params, &testDAppData)
assert.NoError(t, err)
response, err := cmd.Execute(request)
response, err := state.cmd.Execute(state.ctx, request)
if tc.expectedError != nil {
assert.Error(t, err)
assert.Equal(t, err, tc.expectedError)

View File

@ -12,36 +12,33 @@ import (
)
func TestFailToRevokePermissionsWithMissingDAppFields(t *testing.T) {
cmd := &RequestPermissionsCommand{}
state, close := setupCommand(t, Method_RevokePermissions)
t.Cleanup(close)
// Missing DApp fields
request, err := ConstructRPCRequest("wallet_revokePermissions", []interface{}{}, nil)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestMissingDAppData, err)
assert.Empty(t, result)
}
func TestFailToRevokePermissionsForUnpermittedDApp(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &RevokePermissionsCommand{Db: db}
state, close := setupCommand(t, Method_RevokePermissions)
t.Cleanup(close)
request, err := ConstructRPCRequest("wallet_revokePermissions", []interface{}{}, &testDAppData)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrDAppIsNotPermittedByUser, err)
assert.Empty(t, result)
}
func TestRevokePermissionsSucceeded(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &RevokePermissionsCommand{Db: db}
state, close := setupCommand(t, Method_RevokePermissions)
t.Cleanup(close)
sharedAccount := types.BytesToAddress(types.FromHex("0x6d0aa2a774b74bb1d36f97700315adf962c69fcg"))
dAppPermissionRevoked := false
@ -58,17 +55,17 @@ func TestRevokePermissionsSucceeded(t *testing.T) {
}))
t.Cleanup(signal.ResetMobileSignalHandler)
err := PersistDAppData(db, testDAppData, sharedAccount, 0x123)
err := PersistDAppData(state.walletDb, testDAppData, sharedAccount, 0x123)
assert.NoError(t, err)
request, err := ConstructRPCRequest("wallet_revokePermissions", []interface{}{}, &testDAppData)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
assert.Empty(t, result)
dApp, err := persistence.SelectDAppByUrl(db, testDAppData.URL)
dApp, err := persistence.SelectDAppByUrl(state.walletDb, testDAppData.URL)
assert.NoError(t, err)
assert.Nil(t, dApp)

View File

@ -2,13 +2,17 @@ package commands
import (
"encoding/json"
"errors"
"math/big"
"testing"
"time"
"github.com/stretchr/testify/assert"
hexutil "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/status-im/status-go/eth-node/types"
mock_client "github.com/status-im/status-go/rpc/chain/mock/client"
"github.com/status-im/status-go/signal"
"github.com/status-im/status-go/transactions"
)
@ -38,77 +42,68 @@ func prepareSendTransactionRequest(dApp signal.ConnectorDApp, from types.Address
}
func TestFailToSendTransactionWithoutPermittedDApp(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &SendTransactionCommand{Db: db}
state, close := setupCommand(t, Method_EthSendTransaction)
t.Cleanup(close)
// Don't save dApp in the database
request, err := prepareSendTransactionRequest(testDAppData, types.Address{0x1})
assert.NoError(t, err)
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrDAppIsNotPermittedByUser, err)
}
func TestFailToSendTransactionWithWrongAddress(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
state, close := setupCommand(t, Method_EthSendTransaction)
t.Cleanup(close)
cmd := &SendTransactionCommand{Db: db}
err := PersistDAppData(db, testDAppData, types.Address{0x01}, uint64(0x1))
err := PersistDAppData(state.walletDb, testDAppData, types.Address{0x01}, uint64(0x1))
assert.NoError(t, err)
request, err := prepareSendTransactionRequest(testDAppData, types.Address{0x02})
assert.NoError(t, err)
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrParamsFromAddressIsNotShared, err)
}
func TestSendTransactionWithSignalTimout(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
state, close := setupCommand(t, Method_EthSendTransaction)
t.Cleanup(close)
clientHandler := NewClientSideHandler()
cmd := &SendTransactionCommand{
Db: db,
ClientHandler: clientHandler,
}
err := PersistDAppData(db, testDAppData, types.Address{0x01}, uint64(0x1))
accountAddress := types.Address{0x01}
err := PersistDAppData(state.walletDb, testDAppData, accountAddress, uint64(0x1))
assert.NoError(t, err)
request, err := prepareSendTransactionRequest(testDAppData, types.Address{0x01})
request, err := prepareSendTransactionRequest(testDAppData, accountAddress)
assert.NoError(t, err)
backupWalletResponseMaxInterval := WalletResponseMaxInterval
WalletResponseMaxInterval = 1 * time.Millisecond
_, err = cmd.Execute(request)
mockedChainClient := mock_client.NewMockClientInterface(state.mockCtrl)
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().SuggestGasPrice(state.ctx).Times(1).Return(big.NewInt(1), nil)
mockedChainClient.EXPECT().SuggestGasTipCap(state.ctx).Times(1).Return(big.NewInt(0), errors.New("EIP-1559 is not enabled"))
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().PendingNonceAt(state.ctx, common.Address(accountAddress)).Times(1).Return(uint64(10), nil)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrWalletResponseTimeout, err)
WalletResponseMaxInterval = backupWalletResponseMaxInterval
}
func TestSendTransactionWithSignalAccepted(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
state, close := setupCommand(t, Method_EthSendTransaction)
t.Cleanup(close)
fakedTransactionHash := types.Hash{0x051}
clientHandler := NewClientSideHandler()
cmd := &SendTransactionCommand{
Db: db,
ClientHandler: clientHandler,
}
err := PersistDAppData(db, testDAppData, types.Address{0x01}, uint64(0x1))
accountAddress := types.Address{0x01}
err := PersistDAppData(state.walletDb, testDAppData, accountAddress, uint64(0x1))
assert.NoError(t, err)
request, err := prepareSendTransactionRequest(testDAppData, types.Address{0x01})
request, err := prepareSendTransactionRequest(testDAppData, accountAddress)
assert.NoError(t, err)
signal.SetMobileSignalHandler(signal.MobileSignalHandler(func(s []byte) {
@ -122,7 +117,7 @@ func TestSendTransactionWithSignalAccepted(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = clientHandler.SendTransactionAccepted(SendTransactionAcceptedArgs{
err = state.handler.SendTransactionAccepted(SendTransactionAcceptedArgs{
Hash: fakedTransactionHash,
RequestID: ev.RequestID,
})
@ -131,26 +126,27 @@ func TestSendTransactionWithSignalAccepted(t *testing.T) {
}))
t.Cleanup(signal.ResetMobileSignalHandler)
response, err := cmd.Execute(request)
mockedChainClient := mock_client.NewMockClientInterface(state.mockCtrl)
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().SuggestGasPrice(state.ctx).Times(1).Return(big.NewInt(1), nil)
mockedChainClient.EXPECT().SuggestGasTipCap(state.ctx).Times(1).Return(big.NewInt(0), errors.New("EIP-1559 is not enabled"))
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().PendingNonceAt(state.ctx, common.Address(accountAddress)).Times(1).Return(uint64(10), nil)
response, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, response, fakedTransactionHash.String())
}
func TestSendTransactionWithSignalRejected(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
state, close := setupCommand(t, Method_EthSendTransaction)
t.Cleanup(close)
clientHandler := NewClientSideHandler()
cmd := &SendTransactionCommand{
Db: db,
ClientHandler: clientHandler,
}
err := PersistDAppData(db, testDAppData, types.Address{0x01}, uint64(0x1))
accountAddress := types.Address{0x01}
err := PersistDAppData(state.walletDb, testDAppData, accountAddress, uint64(0x1))
assert.NoError(t, err)
request, err := prepareSendTransactionRequest(testDAppData, types.Address{0x01})
request, err := prepareSendTransactionRequest(testDAppData, accountAddress)
assert.NoError(t, err)
signal.SetMobileSignalHandler(signal.MobileSignalHandler(func(s []byte) {
@ -164,7 +160,7 @@ func TestSendTransactionWithSignalRejected(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = clientHandler.SendTransactionRejected(RejectedArgs{
err = state.handler.SendTransactionRejected(RejectedArgs{
RequestID: ev.RequestID,
})
assert.NoError(t, err)
@ -172,6 +168,13 @@ func TestSendTransactionWithSignalRejected(t *testing.T) {
}))
t.Cleanup(signal.ResetMobileSignalHandler)
_, err = cmd.Execute(request)
mockedChainClient := mock_client.NewMockClientInterface(state.mockCtrl)
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().SuggestGasPrice(state.ctx).Times(1).Return(big.NewInt(1), nil)
mockedChainClient.EXPECT().SuggestGasTipCap(state.ctx).Times(1).Return(big.NewInt(0), errors.New("EIP-1559 is not enabled"))
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().PendingNonceAt(state.ctx, common.Address(accountAddress)).Times(1).Return(uint64(10), nil)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrSendTransactionRejectedByUser, err)
}

View File

@ -8,54 +8,37 @@ import (
"github.com/stretchr/testify/assert"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/params"
walletCommon "github.com/status-im/status-go/services/wallet/common"
"github.com/status-im/status-go/signal"
)
func TestFailToSwitchEthereumChainWithMissingDAppFields(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &SwitchEthereumChainCommand{Db: db}
state, close := setupCommand(t, Method_SwitchEthereumChain)
t.Cleanup(close)
// Missing DApp fields
request, err := ConstructRPCRequest("wallet_switchEthereumChain", []interface{}{}, nil)
assert.NoError(t, err)
result, err := cmd.Execute(request)
result, err := state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrRequestMissingDAppData, err)
assert.Empty(t, result)
}
func TestFailToSwitchEthereumChainWithNoChainId(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
cmd := &SwitchEthereumChainCommand{Db: db}
state, close := setupCommand(t, Method_SwitchEthereumChain)
t.Cleanup(close)
request, err := ConstructRPCRequest("wallet_switchEthereumChain", []interface{}{}, &testDAppData)
assert.NoError(t, err)
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrEmptyRPCParams, err)
}
func TestFailToSwitchEthereumChainWithUnsupportedChainId(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
nm := NetworkManagerMock{}
nm.SetNetworks([]*params.Network{
{
ChainID: walletCommon.EthereumMainnet,
},
})
cmd := &SwitchEthereumChainCommand{
Db: db,
NetworkManager: &nm,
}
state, close := setupCommand(t, Method_SwitchEthereumChain)
t.Cleanup(close)
params := make([]interface{}, 1)
params[0] = map[string]interface{}{
@ -65,23 +48,13 @@ func TestFailToSwitchEthereumChainWithUnsupportedChainId(t *testing.T) {
request, err := ConstructRPCRequest("wallet_switchEthereumChain", params, &testDAppData)
assert.NoError(t, err)
_, err = cmd.Execute(request)
_, err = state.cmd.Execute(state.ctx, request)
assert.Equal(t, ErrUnsupportedNetwork, err)
}
func TestSwitchEthereumChainSuccess(t *testing.T) {
db, close := SetupTestDB(t)
defer close()
nm := NetworkManagerMock{}
nm.SetNetworks([]*params.Network{
{
ChainID: walletCommon.EthereumMainnet,
},
{
ChainID: walletCommon.EthereumGoerli,
},
})
state, close := setupCommand(t, Method_SwitchEthereumChain)
t.Cleanup(close)
chainId := fmt.Sprintf(`0x%s`, walletCommon.ChainID(walletCommon.EthereumMainnet).String())
chainIdSwitched := false
@ -104,11 +77,6 @@ func TestSwitchEthereumChainSuccess(t *testing.T) {
}))
t.Cleanup(signal.ResetMobileSignalHandler)
cmd := &SwitchEthereumChainCommand{
Db: db,
NetworkManager: &nm,
}
params := make([]interface{}, 1)
params[0] = map[string]interface{}{
"chainId": "0x1",
@ -117,10 +85,10 @@ func TestSwitchEthereumChainSuccess(t *testing.T) {
request, err := ConstructRPCRequest("wallet_switchEthereumChain", params, &testDAppData)
assert.NoError(t, err)
err = PersistDAppData(db, testDAppData, types.HexToAddress("0x6d0aa2a774b74bb1d36f97700315adf962c69fcg"), walletCommon.EthereumMainnet)
err = PersistDAppData(state.walletDb, testDAppData, types.HexToAddress("0x6d0aa2a774b74bb1d36f97700315adf962c69fcg"), walletCommon.EthereumMainnet)
assert.NoError(t, err)
response, err := cmd.Execute(request)
response, err := state.cmd.Execute(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, chainId, response)
assert.True(t, chainIdSwitched)

View File

@ -1,15 +1,21 @@
package commands
import (
"context"
"database/sql"
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"github.com/status-im/status-go/appdatabase"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/params"
mock_rpcclient "github.com/status-im/status-go/rpc/mock/client"
"github.com/status-im/status-go/rpc/network"
persistence "github.com/status-im/status-go/services/connector/database"
walletCommon "github.com/status-im/status-go/services/wallet/common"
"github.com/status-im/status-go/signal"
"github.com/status-im/status-go/t/helpers"
"github.com/status-im/status-go/walletdatabase"
@ -21,36 +27,18 @@ var testDAppData = signal.ConnectorDApp{
IconURL: "http://testDAppIconUrl",
}
type RPCClientMock struct {
response string
}
type NetworkManagerMock struct {
networks []*params.Network
}
type EventType struct {
Type string `json:"type"`
Event json.RawMessage `json:"event"`
}
func (c *RPCClientMock) CallRaw(request string) string {
return c.response
func createDB(t *testing.T) (*sql.DB, func()) {
db, cleanup, err := helpers.SetupTestSQLDB(appdatabase.DbInitializer{}, "browser-connect-tests-")
require.NoError(t, err)
return db, func() { require.NoError(t, cleanup()) }
}
func (c *RPCClientMock) SetResponse(response string) {
c.response = response
}
func (nm *NetworkManagerMock) GetActiveNetworks() ([]*params.Network, error) {
return nm.networks, nil
}
func (nm *NetworkManagerMock) SetNetworks(networks []*params.Network) {
nm.networks = networks
}
func SetupTestDB(t *testing.T) (db *sql.DB, close func()) {
func createWalletDB(t *testing.T) (db *sql.DB, close func()) {
db, err := helpers.SetupTestMemorySQLDB(walletdatabase.DbInitializer{})
require.NoError(t, err)
return db, func() {
@ -58,6 +46,91 @@ func SetupTestDB(t *testing.T) (db *sql.DB, close func()) {
}
}
type testState struct {
ctx context.Context
db *sql.DB
walletDb *sql.DB
cmd RPCCommand
handler *ClientSideHandler
mockCtrl *gomock.Controller
rpcClient *mock_rpcclient.MockClientInterface
}
func setupCommand(t *testing.T, method string) (state testState, close func()) {
state.ctx = context.Background()
var (
closeDb func()
closeWalletDb func()
)
state.db, closeDb = createDB(t)
state.walletDb, closeWalletDb = createWalletDB(t)
networkManager := network.NewManager(state.db)
require.NotNil(t, networkManager)
err := networkManager.Init([]params.Network{
{
ChainID: walletCommon.EthereumMainnet,
Layer: 1,
},
{
ChainID: walletCommon.OptimismMainnet,
Layer: 1,
},
})
require.NoError(t, err)
state.handler = NewClientSideHandler()
state.mockCtrl = gomock.NewController(t)
state.rpcClient = mock_rpcclient.NewMockClientInterface(state.mockCtrl)
switch method {
case Method_EthAccounts:
state.cmd = &AccountsCommand{
Db: state.walletDb,
}
case Method_EthRequestAccounts:
state.cmd = &RequestAccountsCommand{
ClientHandler: state.handler,
Db: state.walletDb,
}
case Method_EthChainId:
state.cmd = &ChainIDCommand{
Db: state.walletDb,
NetworkManager: networkManager,
}
case Method_PersonalSign:
state.cmd = &PersonalSignCommand{
Db: state.walletDb,
ClientHandler: state.handler,
}
case Method_EthSendTransaction:
state.cmd = &SendTransactionCommand{
Db: state.walletDb,
ClientHandler: state.handler,
RpcClient: state.rpcClient,
}
case Method_RequestPermissions:
state.cmd = &RequestPermissionsCommand{}
case Method_RevokePermissions:
state.cmd = &RevokePermissionsCommand{
Db: state.walletDb,
}
case Method_SwitchEthereumChain:
state.cmd = &SwitchEthereumChainCommand{
Db: state.walletDb,
NetworkManager: networkManager,
}
}
return state, func() {
closeDb()
closeWalletDb()
}
}
func PersistDAppData(db *sql.DB, dApp signal.ConnectorDApp, sharedAccount types.Address, chainID uint64) error {
dAppDb := persistence.DApp{
URL: dApp.URL,

View File

@ -2,13 +2,16 @@ package connector
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
"github.com/ethereum/go-ethereum/common"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/params"
mock_client "github.com/status-im/status-go/rpc/chain/mock/client"
"github.com/status-im/status-go/services/connector/chainutils"
"github.com/status-im/status-go/services/connector/commands"
walletCommon "github.com/status-im/status-go/services/wallet/common"
@ -16,25 +19,8 @@ import (
)
func TestRequestAccountsSwitchChainAndSendTransactionFlow(t *testing.T) {
db, close := createDB(t)
defer close()
nm := commands.NetworkManagerMock{}
nm.SetNetworks([]*params.Network{
{
ChainID: walletCommon.EthereumMainnet,
Layer: 1,
},
{
ChainID: walletCommon.OptimismMainnet,
Layer: 1,
},
})
rpc := commands.RPCClientMock{}
service := NewService(db, &rpc, &nm)
api := NewAPI(service)
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
accountAddress := types.BytesToAddress(types.FromHex("0x6d0aa2a774b74bb1d36f97700315adf962c69fcg"))
expectedHash := types.BytesToHash(types.FromHex("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"))
@ -58,7 +44,7 @@ func TestRequestAccountsSwitchChainAndSendTransactionFlow(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = api.RequestAccountsAccepted(commands.RequestAccountsAcceptedArgs{
err = state.api.RequestAccountsAccepted(commands.RequestAccountsAcceptedArgs{
RequestID: ev.RequestID,
Account: accountAddress,
ChainID: 0x1,
@ -69,7 +55,7 @@ func TestRequestAccountsSwitchChainAndSendTransactionFlow(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = api.SendTransactionAccepted(commands.SendTransactionAcceptedArgs{
err = state.api.SendTransactionAccepted(commands.SendTransactionAcceptedArgs{
RequestID: ev.RequestID,
Hash: expectedHash,
})
@ -79,7 +65,7 @@ func TestRequestAccountsSwitchChainAndSendTransactionFlow(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = api.PersonalSignAccepted(commands.PersonalSignAcceptedArgs{
err = state.api.PersonalSignAccepted(commands.PersonalSignAcceptedArgs{
RequestID: ev.RequestID,
Signature: expectedSignature,
})
@ -90,7 +76,7 @@ func TestRequestAccountsSwitchChainAndSendTransactionFlow(t *testing.T) {
// Request accounts, now for real
request := "{\"method\": \"eth_requestAccounts\", \"params\": [], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }"
response, err := api.CallRPC(request)
response, err := state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, commands.FormatAccountAddressToResponse(accountAddress), response)
assert.Equal(t, true, dAppPermissionGranted)
@ -100,42 +86,50 @@ func TestRequestAccountsSwitchChainAndSendTransactionFlow(t *testing.T) {
expectedChainID, err := chainutils.GetHexChainID(walletCommon.ChainID(walletCommon.EthereumMainnet).String())
assert.NoError(t, err)
request = fmt.Sprintf("{\"method\": \"wallet_switchEthereumChain\", \"params\": [{\"chainId\": \"%s\"}], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }", expectedChainID)
response, err = api.CallRPC(request)
response, err = state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, expectedChainID, response)
// Check if the chain was switched
request = "{\"method\": \"eth_chainId\", \"params\": [], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }"
response, err = api.CallRPC(request)
response, err = state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, expectedChainID, response)
// Check the account after switching chain
request = "{\"method\": \"eth_accounts\", \"params\": [], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }"
response, err = api.CallRPC(request)
response, err = state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, commands.FormatAccountAddressToResponse(accountAddress), response)
// Send transaction
mockedChainClient := mock_client.NewMockClientInterface(state.mockCtrl)
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().SuggestGasPrice(state.ctx).Times(1).Return(big.NewInt(1), nil)
mockedChainClient.EXPECT().SuggestGasTipCap(state.ctx).Times(1).Return(big.NewInt(0), errors.New("EIP-1559 is not enabled"))
state.rpcClient.EXPECT().EthClient(uint64(1)).Times(1).Return(mockedChainClient, nil)
mockedChainClient.EXPECT().PendingNonceAt(state.ctx, common.Address(accountAddress)).Times(1).Return(uint64(10), nil)
request = fmt.Sprintf("{\"method\": \"eth_sendTransaction\", \"params\":[{\"from\":\"%s\",\"to\":\"0x0200000000000000000000000000000000000000\",\"value\":\"0x12345\",\"data\":\"0x307830\"}], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }", accountAddress.Hex())
response, err = api.CallRPC(request)
response, err = state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, expectedHash.Hex(), response)
// Personal sign
request = "{\"method\": \"personal_sign\", \"params\":[{\"challenge\": \"0x506c65617365207369676e2074686973206d65737361676520746f20636f6e6669726d20796f7572206964656e746974792e\",\"address\":\"0x4B0897b0513FdBeEc7C469D9aF4fA6C0752aBea7\"}], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }"
response, err = api.CallRPC(request)
response, err = state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, expectedSignature, response)
// Revoke permissions
request = "{\"method\": \"wallet_revokePermissions\", \"params\": [], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }"
_, err = api.CallRPC(request)
response, err = state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Empty(t, response)
// Check if the account was revoked
request = fmt.Sprintf("{\"method\": \"eth_sendTransaction\", \"params\":[{\"from\":\"%s\",\"to\":\"0x0200000000000000000000000000000000000000\",\"value\":\"0x12345\",\"data\":\"0x307830\"}], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }", accountAddress.Hex())
response, err = api.CallRPC(request)
response, err = state.api.CallRPC(state.ctx, request)
assert.Empty(t, response)
assert.Error(t, err)
assert.Equal(t, commands.ErrDAppIsNotPermittedByUser, err)
@ -143,13 +137,8 @@ func TestRequestAccountsSwitchChainAndSendTransactionFlow(t *testing.T) {
}
func TestForwardedRPCs(t *testing.T) {
db, close := createDB(t)
defer close()
rpc := commands.RPCClientMock{}
service := NewService(db, &rpc, nil)
api := NewAPI(service)
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
sharedAccount := types.BytesToAddress(types.FromHex("0x3d0ab2a774b74bb1d36f97700315adf962c69fct"))
@ -159,41 +148,33 @@ func TestForwardedRPCs(t *testing.T) {
IconURL: "https://app.test.icon.org",
}
request := "{\"method\": \"eth_blockNumber\", \"params\":[],\"url\":\"https://app.test.org\",\"name\":\"testDAppName\",\"iconUrl\":\"http://testDAppIconUrl\"}"
_, err := api.CallRPC(request)
assert.Equal(t, commands.ErrDAppIsNotPermittedByUser, err)
err = commands.PersistDAppData(db, testDAppData, sharedAccount, 0x123)
requestJson := "{\"method\": \"eth_blockNumber\", \"params\":[],\"url\":\"https://app.test.org\",\"name\":\"testDAppName\",\"iconUrl\":\"http://testDAppIconUrl\"}"
request, err := commands.RPCRequestFromJSON(requestJson)
assert.NoError(t, err)
request.ChainID = 291
byteRequest, err := json.Marshal(request)
assert.NoError(t, err)
expectedResponse := "0xaa37dc"
rpc.SetResponse(fmt.Sprintf(`{"jsonrpc":"2.0","id":37,"result":"%s"}`, expectedResponse))
response, err := api.CallRPC(request)
state.rpcClient.EXPECT().CallRaw(string(byteRequest)).Times(0)
_, err = state.api.CallRPC(state.ctx, requestJson)
assert.Equal(t, commands.ErrDAppIsNotPermittedByUser, err)
err = commands.PersistDAppData(state.walletDb, testDAppData, sharedAccount, 0x123)
assert.NoError(t, err)
state.rpcClient.EXPECT().CallRaw(string(byteRequest)).Times(1).Return(fmt.Sprintf(`{"jsonrpc":"2.0","id":37,"result":"%s"}`, expectedResponse))
response, err := state.api.CallRPC(state.ctx, requestJson)
assert.NoError(t, err)
assert.Equal(t, expectedResponse, response)
}
func TestRequestAccountsAfterPermisasionsRevokeTest(t *testing.T) {
db, close := createDB(t)
defer close()
nm := commands.NetworkManagerMock{}
nm.SetNetworks([]*params.Network{
{
ChainID: walletCommon.EthereumMainnet,
Layer: 1,
},
{
ChainID: walletCommon.OptimismMainnet,
Layer: 1,
},
})
rpc := commands.RPCClientMock{}
service := NewService(db, &rpc, &nm)
api := NewAPI(service)
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
accountAddress := types.BytesToAddress(types.FromHex("0x6d0aa2a774b74bb1d36f97700315adf962c69fcg"))
dAppPermissionRevoked := false
@ -214,7 +195,7 @@ func TestRequestAccountsAfterPermisasionsRevokeTest(t *testing.T) {
err := json.Unmarshal(evt.Event, &ev)
assert.NoError(t, err)
err = api.RequestAccountsAccepted(commands.RequestAccountsAcceptedArgs{
err = state.api.RequestAccountsAccepted(commands.RequestAccountsAcceptedArgs{
RequestID: ev.RequestID,
Account: accountAddress,
ChainID: 0x1,
@ -230,7 +211,7 @@ func TestRequestAccountsAfterPermisasionsRevokeTest(t *testing.T) {
// Request accounts
request := "{\"method\": \"eth_requestAccounts\", \"params\": [], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }"
response, err := api.CallRPC(request)
response, err := state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, commands.FormatAccountAddressToResponse(accountAddress), response)
assert.Equal(t, true, dAppPermissionGranted)
@ -238,7 +219,7 @@ func TestRequestAccountsAfterPermisasionsRevokeTest(t *testing.T) {
// Revoke permissions
request = "{\"method\": \"wallet_revokePermissions\", \"params\": [], \"url\": \"http://testDAppURL123\", \"name\": \"testDAppName\", \"iconUrl\": \"http://testDAppIconUrl\" }"
_, err = api.CallRPC(request)
_, err = state.api.CallRPC(state.ctx, request)
assert.NoError(t, err)
assert.Equal(t, true, dAppPermissionRevoked)
}

View File

@ -4,62 +4,37 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
gethrpc "github.com/ethereum/go-ethereum/rpc"
"github.com/status-im/status-go/params"
statusRPC "github.com/status-im/status-go/rpc"
"github.com/status-im/status-go/services/connector/commands"
"github.com/status-im/status-go/transactions/fake"
)
func TestNewService(t *testing.T) {
db, close := createDB(t)
defer close()
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
txServiceMockCtrl := gomock.NewController(t)
server, _ := fake.NewTestServer(txServiceMockCtrl)
// Creating a dummy status node to simulate what it's done in get_status_node.go
upstreamConfig := params.UpstreamRPCConfig{
URL: "https://mainnet.infura.io/v3/fake",
Enabled: true,
}
client := gethrpc.DialInProc(server)
rpcClient, err := statusRPC.NewClient(client, 1, upstreamConfig, nil, db, nil)
require.NoError(t, err)
service := NewService(db, rpcClient, rpcClient.NetworkManager)
assert.NotNil(t, service)
assert.Equal(t, rpcClient.NetworkManager, service.nm)
assert.NotNil(t, state.service)
assert.Equal(t, state.rpcClient.GetNetworkManager(), state.service.nm)
}
func TestService_Start(t *testing.T) {
db, close := createDB(t)
defer close()
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
service := NewService(db, &commands.RPCClientMock{}, &commands.NetworkManagerMock{})
err := service.Start()
err := state.service.Start()
assert.NoError(t, err)
}
func TestService_Stop(t *testing.T) {
db, close := createDB(t)
defer close()
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
service := NewService(db, &commands.RPCClientMock{}, &commands.NetworkManagerMock{})
err := service.Stop()
err := state.service.Stop()
assert.NoError(t, err)
}
func TestService_APIs(t *testing.T) {
api, cancel := setupTestAPI(t)
defer cancel()
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
apis := api.s.APIs()
apis := state.api.s.APIs()
assert.Len(t, apis, 1)
assert.Equal(t, "connector", apis[0].Namespace)
@ -68,10 +43,9 @@ func TestService_APIs(t *testing.T) {
}
func TestService_Protocols(t *testing.T) {
db, close := createDB(t)
defer close()
state, closeFn := setupTests(t)
t.Cleanup(closeFn)
service := NewService(db, &commands.RPCClientMock{}, &commands.NetworkManagerMock{})
protocols := service.Protocols()
protocols := state.service.Protocols()
assert.Nil(t, protocols)
}

View File

@ -0,0 +1,98 @@
package connector
import (
"context"
"database/sql"
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"github.com/status-im/status-go/appdatabase"
"github.com/status-im/status-go/multiaccounts/settings"
"github.com/status-im/status-go/params"
mock_rpcclient "github.com/status-im/status-go/rpc/mock/client"
"github.com/status-im/status-go/rpc/network"
walletCommon "github.com/status-im/status-go/services/wallet/common"
"github.com/status-im/status-go/t/helpers"
"github.com/status-im/status-go/walletdatabase"
)
type testState struct {
ctx context.Context
db *sql.DB
walletDb *sql.DB
mockCtrl *gomock.Controller
rpcClient *mock_rpcclient.MockClientInterface
service *Service
api *API
}
func createDB(t *testing.T) (*sql.DB, func()) {
db, cleanup, err := helpers.SetupTestSQLDB(appdatabase.DbInitializer{}, "browser-connect-tests-")
require.NoError(t, err)
return db, func() { require.NoError(t, cleanup()) }
}
func createWalletDB(t *testing.T) (db *sql.DB, close func()) {
db, err := helpers.SetupTestMemorySQLDB(walletdatabase.DbInitializer{})
require.NoError(t, err)
return db, func() {
require.NoError(t, db.Close())
}
}
func setupTests(t *testing.T) (state testState, close func()) {
state.ctx = context.Background()
var (
closeDb func()
closeWalletDb func()
)
state.db, closeDb = createDB(t)
state.walletDb, closeWalletDb = createWalletDB(t)
config := params.NodeConfig{
NetworkID: 10,
DataDir: "test",
}
networks := json.RawMessage("{}")
settingsObj := settings.Settings{
Networks: &networks,
}
settDb, err := settings.MakeNewDB(state.db)
require.NoError(t, err)
err = settDb.CreateSettings(settingsObj, config)
require.NoError(t, err)
state.mockCtrl = gomock.NewController(t)
state.rpcClient = mock_rpcclient.NewMockClientInterface(state.mockCtrl)
networkManager := network.NewManager(state.db)
require.NotNil(t, networkManager)
err = networkManager.Init([]params.Network{
{
ChainID: walletCommon.EthereumMainnet,
Layer: 1,
},
{
ChainID: walletCommon.OptimismMainnet,
Layer: 1,
},
})
require.NoError(t, err)
state.rpcClient.EXPECT().GetNetworkManager().AnyTimes().Return(networkManager)
state.service = NewService(state.walletDb, state.rpcClient, state.rpcClient.GetNetworkManager())
state.api = NewAPI(state.service)
return state, func() {
closeDb()
closeWalletDb()
}
}