Working on testing after refactoring

Former-commit-id: a85e9b33e2895c403e625a650fca1d530a0f8230 [formerly f258e65dfbdcde622dcdb3e74b24f8dea33c6751]
Former-commit-id: 94c5da680fdf74217500980089837e7c336d93a4
This commit is contained in:
Preston Van Loon
2018-03-31 17:48:57 -04:00
parent ae1dfbbaf9
commit 7df6110eff
3 changed files with 69 additions and 222 deletions

View File

@@ -1,125 +0,0 @@
package collator
import (
"context"
"flag"
"math/big"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/sharding/contracts"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/rpc"
cli "gopkg.in/urfave/cli.v1"
)
// FakeEthService based on implementation of internal/ethapi.Client
type FakeEthService struct{}
// eth_getCode
func (s *FakeEthService) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (string, error) {
return contracts.SMCBin, nil
}
func (s *FakeEthService) GasPrice(ctx context.Context) (hexutil.Big, error) {
b := big.NewInt(1000)
return hexutil.Big(*b), nil
}
func (s *FakeEthService) EstimateGas(ctx context.Context, msg interface{}) (hexutil.Uint64, error) {
h := hexutil.Uint64(uint64(1000000))
return h, nil
}
func (s *FakeEthService) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Uint64, error) {
return hexutil.Uint64(uint64(1)), nil
}
func (s *FakeEthService) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
return common.Hash{}, nil
}
func (s *FakeEthService) GetTransactionReceipt(hash common.Hash) (*types.Receipt, error) {
return &types.Receipt{
ContractAddress: common.StringToAddress("0x1"),
Logs: []*types.Log{},
}, nil
}
func (s *FakeEthService) GetTransactionByHash(hash common.Hash) (tx *types.Transaction, isPending bool, err error) {
return nil, false, nil
}
type FakeNetworkService struct{}
func (s *FakeNetworkService) Version() (string, error) {
return "100", nil
}
type FakeNewHeadsService struct{}
func (s *FakeNewHeadsService) NewHeads() {
}
// TODO: Use a simulated backend rather than starting a fake node.
func newTestServer(endpoint string) (*rpc.Server, error) {
// Create a default account without password.
scryptN, scryptP, keydir, err := (&node.Config{DataDir: endpoint}).AccountConfig()
if err != nil {
return nil, err
}
if _, err := keystore.StoreKey(keydir, "" /*password*/, scryptN, scryptP); err != nil {
return nil, err
}
// Create server and register eth service with FakeEthService
server := rpc.NewServer()
if err := server.RegisterName("eth", new(FakeEthService)); err != nil {
return nil, err
}
if err := server.RegisterName("net", new(FakeNetworkService)); err != nil {
return nil, err
}
if err := server.RegisterName("newHeads", new(FakeNewHeadsService)); err != nil {
return nil, err
}
l, err := rpc.CreateIPCListener(endpoint + "/geth.ipc")
if err != nil {
return nil, err
}
go server.ServeListener(l)
return server, nil
}
func createContext() *cli.Context {
set := flag.NewFlagSet("test", 0)
set.String(utils.DataDirFlag.Name, "", "")
return cli.NewContext(nil, set, nil)
}
// TODO(prestonvanloon): Fix this test.
// func TestShardingClient(t *testing.T) {
// endpoint := path.Join(os.TempDir(), fmt.Sprintf("go-ethereum-test-ipc-%d-%d", os.Getpid(), rand.Int63()))
// server, err := newTestServer(endpoint)
// if err != nil {
// t.Fatalf("Failed to create a test server: %v", err)
// }
// defer server.Stop()
// ctx := createContext()
// if err := ctx.GlobalSet(utils.DataDirFlag.Name, endpoint); err != nil {
// t.Fatalf("Failed to set global variable for flag %s. Error: %v", utils.DataDirFlag.Name, err)
// }
// c := MakeCollatorClient(ctx)
// if err := c.Start(); err != nil {
// t.Errorf("Failed to start server: %v", err)
// }
// }

View File

@@ -1,119 +1,91 @@
package collator
import (
"context"
"errors"
"math/big"
"strings"
"testing"
"github.com/ethereum/go-ethereum"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/sharding"
"github.com/ethereum/go-ethereum/sharding/contracts"
"github.com/ethereum/go-ethereum/core/types"
)
type FakeCollatorClient struct {
accountAccount *accounts.Account
accountError error
chainReader FakeChainReader
contractCaller FakeContractCaller
var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
addr = crypto.PubkeyToAddress(key.PublicKey)
accountBalance1000Eth, _ = new(big.Int).SetString("1000000000000000000000", 10)
)
// Mock client for testing collator. Should this go into sharding/client/testing?
type mockClient struct {
smc *contracts.SMC
t *testing.T
}
func (c FakeCollatorClient) Account() *accounts.Account {
return c.accountAccount
func (m *mockClient) Account() *accounts.Account {
return &accounts.Account{Address: addr}
}
func (c FakeCollatorClient) ChainReader() ethereum.ChainReader {
return c.chainReader
func (m *mockClient) SMCCaller() *contracts.SMCCaller {
return &m.smc.SMCCaller
}
func (c FakeCollatorClient) SMCCaller() *contracts.SMCCaller {
SMCCaller, err := contracts.NewSMCCaller(common.HexToAddress("0x0"), c.contractCaller)
func (m *mockClient) ChainReader() ethereum.ChainReader {
m.t.Fatal("ChainReader not implemented")
return nil
}
func (m *mockClient) SMCTransactor() *contracts.SMCTransactor {
return &m.smc.SMCTransactor
}
func (m *mockClient) CreateTXOps(value *big.Int) (*bind.TransactOpts, error) {
m.t.Fatal("CreateTXOps not implemented")
return nil, nil
}
// Unused mockClient methods
func (m *mockClient) Start() error {
m.t.Fatal("Start called")
return nil
}
func (m *mockClient) Close() {
m.t.Fatal("Close called")
}
func TestIsAccountInCollatorPool(t *testing.T) {
// Test setup (should this go to sharding/client/testing?)
backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1000Eth}})
transactOpts := bind.NewKeyedTransactor(key)
_, _, smc, _ := contracts.DeploySMC(transactOpts, backend)
backend.Commit()
client := &mockClient{smc: smc, t: t}
// address should not be in pool initially
b, err := isAccountInCollatorPool(client)
if err != nil {
panic(err)
t.Fatal(err)
}
return SMCCaller
}
type FakeChainReader struct {
subscribeNewHeadSubscription ethereum.Subscription
subscribeNewHeadError error
}
func (r FakeChainReader) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
return r.subscribeNewHeadSubscription, r.subscribeNewHeadError
}
func (r FakeChainReader) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
return nil, nil
}
func (r FakeChainReader) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
return nil, nil
}
func (r FakeChainReader) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
return nil, nil
}
func (r FakeChainReader) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
return nil, nil
}
func (r FakeChainReader) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
return 0, nil
}
func (r FakeChainReader) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
return nil, nil
}
type FakeContractCaller struct {
codeAtBytes []byte
codeAtError error
callContractBytes []byte
callContractError error
}
func (c FakeContractCaller) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
return c.codeAtBytes, c.codeAtError
}
func (c FakeContractCaller) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
return c.callContractBytes, c.callContractError
}
func TestCheckSMCForCollator(t *testing.T) {
tests := []struct {
Name string
Head *types.Header
ExpectedPeriod *big.Int
ExpectedError string
CollatorClient FakeCollatorClient
}{
{
Name: "SMCCaller.checkSMCForCollator should return an error",
ExpectedError: "there is no cake",
CollatorClient: FakeCollatorClient{
accountAccount: &accounts.Account{},
contractCaller: FakeContractCaller{
callContractError: errors.New("there is no cake"),
},
},
Head: &types.Header{Number: big.NewInt(100)},
},
if b {
t.Fatal("Account unexpectedly in collator pool")
}
for _, tt := range tests {
t.Run(tt.Name, func(t *testing.T) {
if err := checkSMCForCollator(tt.CollatorClient, tt.Head); !strings.Contains(safeError(err), tt.ExpectedError) {
t.Fatalf("Incorrect error! Wanted %v, got %v", tt.ExpectedError, err)
}
})
// deposit in collator pool, then it should return true
transactOpts.Value = sharding.DepositSize
if _, err := smc.Deposit(transactOpts); err != nil {
t.Fatalf("Failed to deposit: %v", err)
}
}
func safeError(err error) string {
backend.Commit()
b, err = isAccountInCollatorPool(client)
if err != nil {
return err.Error()
t.Fatal(err)
}
if !b {
t.Fatal("Account not in collator pool when expected to be")
}
return "nil"
}

View File

@@ -10,7 +10,7 @@ func TestDepositSize(t *testing.T) {
if !err {
t.Fatalf("Failed to setup test")
}
if depositSize.Cmp(want) != 0 {
t.Errorf("depositSize incorrect. Wanted %d, got %d", want, depositSize)
if DepositSize.Cmp(want) != 0 {
t.Errorf("depositSize incorrect. Wanted %d, got %d", want, DepositSize)
}
}