Apply testutils assertions: final cleanup (#7003)

* slasher/beaconclient tests
* slasher/db/kv tests
* Merge branch 'master' into apply-testutils-assertions-to-slasher
* fix build
* slasher/detection tests
* rest of the tests
* misc tests
* tools tests
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge branch 'master' into apply-testutils-assertions-misc
* agg tests
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge branch 'master' into apply-testutils-assertions-misc
* Merge branch 'apply-testutils-assertions-misc' of github.com:prysmaticlabs/prysm into apply-testutils-assertions-misc
* updates aggregated_test
* beacon-chain/operations/attestations/kv/* tests updated
* beacon-chain/operations/attestations tests updated
* beacon-chain/operations/slashings tests updated
* Merge branch 'master' into apply-testutils-assertions-misc
* gazelle
* beacon-chain/core tests updated
* fixes test
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge branch 'apply-testutils-assertions-misc' of github.com:prysmaticlabs/prysm into apply-testutils-assertions-misc
* beacon-chain/rpc tests updated
* beacon-chain/sync/initial-sync tests
* misc tests
* optimizes error message parsing in testutils
* Merge branch 'assertutils-optimize-processing' into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* endtoend tests
* Merge branch 'apply-testutils-assertions-misc' of github.com:prysmaticlabs/prysm into apply-testutils-assertions-misc
* gazelle
* Merge refs/heads/master into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* beacon-chain/blockchain tests updated
* Merge branch 'apply-testutils-assertions-misc' of github.com:prysmaticlabs/prysm into apply-testutils-assertions-misc
* beacon-chain/state/stategen tests updated
* beacon-chain all left-over tests are done
* Merge refs/heads/master into apply-testutils-assertions-misc
* validator tests updated
* slasher tests
* Merge branch 'master' into apply-testutils-assertions-misc
* gofmt
* gazelle
* Merge refs/heads/master into apply-testutils-assertions-misc
* shared upd
* end2end tests deps fixed
* Merge branch 'apply-testutils-assertions-misc' of github.com:prysmaticlabs/prysm into apply-testutils-assertions-misc
* Merge refs/heads/master into apply-testutils-assertions-misc
* misc
* all tests are updated
* Merge branch 'apply-testutils-assertions-misc' of github.com:prysmaticlabs/prysm into apply-testutils-assertions-misc
This commit is contained in:
Victor Farazdagi
2020-08-25 18:23:06 +03:00
committed by GitHub
parent 3d9cde3e1c
commit ba07ccb484
97 changed files with 770 additions and 1662 deletions

View File

@@ -1,7 +1,6 @@
package blockchain package blockchain
import ( import (
"bytes"
"context" "context"
"testing" "testing"
"time" "time"
@@ -24,9 +23,7 @@ var _ = ForkFetcher(&Service{})
func TestFinalizedCheckpt_Nil(t *testing.T) { func TestFinalizedCheckpt_Nil(t *testing.T) {
db, sc := testDB.SetupDB(t) db, sc := testDB.SetupDB(t)
c := setupBeaconChain(t, db, sc) c := setupBeaconChain(t, db, sc)
if !bytes.Equal(c.FinalizedCheckpt().Root, params.BeaconConfig().ZeroHash[:]) { assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], c.FinalizedCheckpt().Root, "Incorrect pre chain start value")
t.Error("Incorrect pre chain start value")
}
} }
func TestHeadRoot_Nil(t *testing.T) { func TestHeadRoot_Nil(t *testing.T) {
@@ -34,9 +31,7 @@ func TestHeadRoot_Nil(t *testing.T) {
c := setupBeaconChain(t, db, sc) c := setupBeaconChain(t, db, sc)
headRoot, err := c.HeadRoot(context.Background()) headRoot, err := c.HeadRoot(context.Background())
require.NoError(t, err) require.NoError(t, err)
if !bytes.Equal(headRoot, params.BeaconConfig().ZeroHash[:]) { assert.DeepEqual(t, params.BeaconConfig().ZeroHash[:], headRoot, "Incorrect pre chain start value")
t.Error("Incorrect pre chain start value")
}
} }
func TestFinalizedCheckpt_CanRetrieve(t *testing.T) { func TestFinalizedCheckpt_CanRetrieve(t *testing.T) {
@@ -57,10 +52,7 @@ func TestFinalizedCheckpt_GenesisRootOk(t *testing.T) {
c := setupBeaconChain(t, db, sc) c := setupBeaconChain(t, db, sc)
c.finalizedCheckpt = cp c.finalizedCheckpt = cp
c.genesisRoot = genesisRoot c.genesisRoot = genesisRoot
assert.DeepEqual(t, c.genesisRoot[:], c.FinalizedCheckpt().Root)
if !bytes.Equal(c.FinalizedCheckpt().Root, c.genesisRoot[:]) {
t.Errorf("Got: %v, wanted: %v", c.FinalizedCheckpt().Root, c.genesisRoot[:])
}
} }
func TestCurrentJustifiedCheckpt_CanRetrieve(t *testing.T) { func TestCurrentJustifiedCheckpt_CanRetrieve(t *testing.T) {
@@ -81,10 +73,7 @@ func TestJustifiedCheckpt_GenesisRootOk(t *testing.T) {
c := setupBeaconChain(t, db, sc) c := setupBeaconChain(t, db, sc)
c.justifiedCheckpt = cp c.justifiedCheckpt = cp
c.genesisRoot = genesisRoot c.genesisRoot = genesisRoot
assert.DeepEqual(t, c.genesisRoot[:], c.CurrentJustifiedCheckpt().Root)
if !bytes.Equal(c.CurrentJustifiedCheckpt().Root, c.genesisRoot[:]) {
t.Errorf("Got: %v, wanted: %v", c.CurrentJustifiedCheckpt().Root, c.genesisRoot[:])
}
} }
func TestPreviousJustifiedCheckpt_CanRetrieve(t *testing.T) { func TestPreviousJustifiedCheckpt_CanRetrieve(t *testing.T) {
@@ -93,7 +82,6 @@ func TestPreviousJustifiedCheckpt_CanRetrieve(t *testing.T) {
cp := &ethpb.Checkpoint{Epoch: 7, Root: []byte("foo")} cp := &ethpb.Checkpoint{Epoch: 7, Root: []byte("foo")}
c := setupBeaconChain(t, db, sc) c := setupBeaconChain(t, db, sc)
c.prevJustifiedCheckpt = cp c.prevJustifiedCheckpt = cp
assert.Equal(t, cp.Epoch, c.PreviousJustifiedCheckpt().Epoch, "Unexpected previous justified epoch") assert.Equal(t, cp.Epoch, c.PreviousJustifiedCheckpt().Epoch, "Unexpected previous justified epoch")
} }
@@ -105,18 +93,13 @@ func TestPrevJustifiedCheckpt_GenesisRootOk(t *testing.T) {
c := setupBeaconChain(t, db, sc) c := setupBeaconChain(t, db, sc)
c.prevJustifiedCheckpt = cp c.prevJustifiedCheckpt = cp
c.genesisRoot = genesisRoot c.genesisRoot = genesisRoot
assert.DeepEqual(t, c.genesisRoot[:], c.PreviousJustifiedCheckpt().Root)
if !bytes.Equal(c.PreviousJustifiedCheckpt().Root, c.genesisRoot[:]) {
t.Errorf("Got: %v, wanted: %v", c.PreviousJustifiedCheckpt().Root, c.genesisRoot[:])
}
} }
func TestHeadSlot_CanRetrieve(t *testing.T) { func TestHeadSlot_CanRetrieve(t *testing.T) {
c := &Service{} c := &Service{}
s, err := state.InitializeFromProto(&pb.BeaconState{}) s, err := state.InitializeFromProto(&pb.BeaconState{})
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
c.head = &head{slot: 100, state: s} c.head = &head{slot: 100, state: s}
assert.Equal(t, uint64(100), c.headSlot()) assert.Equal(t, uint64(100), c.headSlot())
} }
@@ -146,9 +129,7 @@ func TestHeadState_CanRetrieve(t *testing.T) {
c.head = &head{state: s} c.head = &head{state: s}
headState, err := c.HeadState(context.Background()) headState, err := c.HeadState(context.Background())
require.NoError(t, err) require.NoError(t, err)
if !proto.Equal(s.InnerStateUnsafe(), headState.InnerStateUnsafe()) { assert.DeepEqual(t, headState.InnerStateUnsafe(), s.InnerStateUnsafe(), "Incorrect head state received")
t.Error("incorrect head state received")
}
} }
func TestGenesisTime_CanRetrieve(t *testing.T) { func TestGenesisTime_CanRetrieve(t *testing.T) {

View File

@@ -59,13 +59,12 @@ func TestStore_OnAttestation(t *testing.T) {
BlkWithValidStateRoot, err := stateutil.BlockRoot(BlkWithValidState.Block) BlkWithValidStateRoot, err := stateutil.BlockRoot(BlkWithValidState.Block)
require.NoError(t, err) require.NoError(t, err)
s = testutil.NewBeaconState() s = testutil.NewBeaconState()
if err := s.SetFork(&pb.Fork{ err = s.SetFork(&pb.Fork{
Epoch: 0, Epoch: 0,
CurrentVersion: params.BeaconConfig().GenesisForkVersion, CurrentVersion: params.BeaconConfig().GenesisForkVersion,
PreviousVersion: params.BeaconConfig().GenesisForkVersion, PreviousVersion: params.BeaconConfig().GenesisForkVersion,
}); err != nil { })
t.Fatal(err) require.NoError(t, err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, s, BlkWithValidStateRoot)) require.NoError(t, service.beaconDB.SaveState(ctx, s, BlkWithValidStateRoot))
tests := []struct { tests := []struct {
@@ -182,13 +181,12 @@ func TestStore_OnAttestationUsingCheckptCache(t *testing.T) {
BlkWithValidStateRoot, err := stateutil.BlockRoot(BlkWithValidState.Block) BlkWithValidStateRoot, err := stateutil.BlockRoot(BlkWithValidState.Block)
require.NoError(t, err) require.NoError(t, err)
s = testutil.NewBeaconState() s = testutil.NewBeaconState()
if err := s.SetFork(&pb.Fork{ err = s.SetFork(&pb.Fork{
Epoch: 0, Epoch: 0,
CurrentVersion: params.BeaconConfig().GenesisForkVersion, CurrentVersion: params.BeaconConfig().GenesisForkVersion,
PreviousVersion: params.BeaconConfig().GenesisForkVersion, PreviousVersion: params.BeaconConfig().GenesisForkVersion,
}); err != nil { })
t.Fatal(err) require.NoError(t, err)
}
require.NoError(t, service.beaconDB.SaveState(ctx, s, BlkWithValidStateRoot)) require.NoError(t, service.beaconDB.SaveState(ctx, s, BlkWithValidStateRoot))
tests := []struct { tests := []struct {
@@ -389,13 +387,8 @@ func TestAttEpoch_MatchPrevEpoch(t *testing.T) {
service, err := NewService(ctx, cfg) service, err := NewService(ctx, cfg)
require.NoError(t, err) require.NoError(t, err)
if err := service.verifyAttTargetEpoch( nowTime := params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().SecondsPerSlot
ctx, require.NoError(t, service.verifyAttTargetEpoch(ctx, 0, nowTime, &ethpb.Checkpoint{}))
0,
params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot,
&ethpb.Checkpoint{}); err != nil {
t.Error(err)
}
} }
func TestAttEpoch_MatchCurrentEpoch(t *testing.T) { func TestAttEpoch_MatchCurrentEpoch(t *testing.T) {
@@ -406,13 +399,8 @@ func TestAttEpoch_MatchCurrentEpoch(t *testing.T) {
service, err := NewService(ctx, cfg) service, err := NewService(ctx, cfg)
require.NoError(t, err) require.NoError(t, err)
if err := service.verifyAttTargetEpoch( nowTime := params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().SecondsPerSlot
ctx, require.NoError(t, service.verifyAttTargetEpoch(ctx, 0, nowTime, &ethpb.Checkpoint{Epoch: 1}))
0,
params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot,
&ethpb.Checkpoint{Epoch: 1}); err != nil {
t.Error(err)
}
} }
func TestAttEpoch_NotMatch(t *testing.T) { func TestAttEpoch_NotMatch(t *testing.T) {
@@ -423,14 +411,9 @@ func TestAttEpoch_NotMatch(t *testing.T) {
service, err := NewService(ctx, cfg) service, err := NewService(ctx, cfg)
require.NoError(t, err) require.NoError(t, err)
if err := service.verifyAttTargetEpoch( nowTime := 2 * params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().SecondsPerSlot
ctx, err = service.verifyAttTargetEpoch(ctx, 0, nowTime, &ethpb.Checkpoint{})
0, assert.ErrorContains(t, "target epoch 0 does not match current epoch 2 or prev epoch 1", err)
2*params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot,
&ethpb.Checkpoint{}); !strings.Contains(err.Error(),
"target epoch 0 does not match current epoch 2 or prev epoch 1") {
t.Error("Did not receive wanted error")
}
} }
func TestVerifyBeaconBlock_NoBlock(t *testing.T) { func TestVerifyBeaconBlock_NoBlock(t *testing.T) {

View File

@@ -683,8 +683,6 @@ func TestUpdateJustifiedInitSync(t *testing.T) {
assert.DeepEqual(t, currentCp, service.prevJustifiedCheckpt, "Incorrect previous justified checkpoint") assert.DeepEqual(t, currentCp, service.prevJustifiedCheckpt, "Incorrect previous justified checkpoint")
assert.DeepEqual(t, newCp, service.CurrentJustifiedCheckpt(), "Incorrect current justified checkpoint in cache") assert.DeepEqual(t, newCp, service.CurrentJustifiedCheckpt(), "Incorrect current justified checkpoint in cache")
cp, err := service.beaconDB.JustifiedCheckpoint(ctx) cp, err := service.beaconDB.JustifiedCheckpoint(ctx)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
assert.DeepEqual(t, newCp, cp, "Incorrect current justified checkpoint in db") assert.DeepEqual(t, newCp, cp, "Incorrect current justified checkpoint in db")
} }

View File

@@ -37,10 +37,10 @@ func TestService_ReceiveBlock(t *testing.T) {
block *ethpb.SignedBeaconBlock block *ethpb.SignedBeaconBlock
} }
tests := []struct { tests := []struct {
name string name string
args args args args
wantErr bool wantedErr string
check func(*testing.T, *Service) check func(*testing.T, *Service)
}{ }{
{ {
name: "applies block with state transition", name: "applies block with state transition",
@@ -143,9 +143,11 @@ func TestService_ReceiveBlock(t *testing.T) {
s.finalizedCheckpt = &ethpb.Checkpoint{Root: gRoot[:]} s.finalizedCheckpt = &ethpb.Checkpoint{Root: gRoot[:]}
root, err := stateutil.BlockRoot(tt.args.block.Block) root, err := stateutil.BlockRoot(tt.args.block.Block)
require.NoError(t, err) require.NoError(t, err)
if err := s.ReceiveBlock(ctx, tt.args.block, root); (err != nil) != tt.wantErr { err = s.ReceiveBlock(ctx, tt.args.block, root)
t.Errorf("ReceiveBlock() error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else { } else {
assert.NoError(t, err)
tt.check(t, s) tt.check(t, s)
} }
}) })
@@ -201,9 +203,7 @@ func TestService_ReceiveBlockInitialSync(t *testing.T) {
genesis, keys := testutil.DeterministicGenesisState(t, 64) genesis, keys := testutil.DeterministicGenesisState(t, 64)
genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock { genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock {
blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot) blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot)
if err != nil { assert.NoError(t, err)
t.Error(err)
}
return blk return blk
} }
@@ -211,10 +211,10 @@ func TestService_ReceiveBlockInitialSync(t *testing.T) {
block *ethpb.SignedBeaconBlock block *ethpb.SignedBeaconBlock
} }
tests := []struct { tests := []struct {
name string name string
args args args args
wantErr bool wantedErr string
check func(*testing.T, *Service) check func(*testing.T, *Service)
}{ }{
{ {
name: "applies block with state transition", name: "applies block with state transition",
@@ -266,9 +266,11 @@ func TestService_ReceiveBlockInitialSync(t *testing.T) {
root, err := stateutil.BlockRoot(tt.args.block.Block) root, err := stateutil.BlockRoot(tt.args.block.Block)
require.NoError(t, err) require.NoError(t, err)
if err := s.ReceiveBlockInitialSync(ctx, tt.args.block, root); (err != nil) != tt.wantErr { err = s.ReceiveBlockInitialSync(ctx, tt.args.block, root)
t.Errorf("ReceiveBlockInitialSync() error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else { } else {
assert.NoError(t, err)
tt.check(t, s) tt.check(t, s)
} }
}) })
@@ -281,9 +283,7 @@ func TestService_ReceiveBlockBatch(t *testing.T) {
genesis, keys := testutil.DeterministicGenesisState(t, 64) genesis, keys := testutil.DeterministicGenesisState(t, 64)
genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock { genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock {
blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot) blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot)
if err != nil { assert.NoError(t, err)
t.Error(err)
}
return blk return blk
} }
@@ -291,10 +291,10 @@ func TestService_ReceiveBlockBatch(t *testing.T) {
block *ethpb.SignedBeaconBlock block *ethpb.SignedBeaconBlock
} }
tests := []struct { tests := []struct {
name string name string
args args args args
wantErr bool wantedErr string
check func(*testing.T, *Service) check func(*testing.T, *Service)
}{ }{
{ {
name: "applies block with state transition", name: "applies block with state transition",
@@ -347,9 +347,11 @@ func TestService_ReceiveBlockBatch(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
blks := []*ethpb.SignedBeaconBlock{tt.args.block} blks := []*ethpb.SignedBeaconBlock{tt.args.block}
roots := [][32]byte{root} roots := [][32]byte{root}
if err := s.ReceiveBlockBatch(ctx, blks, roots); (err != nil) != tt.wantErr { err = s.ReceiveBlockBatch(ctx, blks, roots)
t.Errorf("ReceiveBlockBatch() error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else { } else {
assert.NoError(t, err)
tt.check(t, s) tt.check(t, s)
} }
}) })

View File

@@ -120,9 +120,7 @@ func setupBeaconChain(t *testing.T, beaconDB db.Database, sc *cache.StateSummary
} }
// Safe a state in stategen to purposes of testing a service stop / shutdown. // Safe a state in stategen to purposes of testing a service stop / shutdown.
if err := cfg.StateGen.SaveState(ctx, bytesutil.ToBytes32(bState.FinalizedCheckpoint().Root), bState); err != nil { require.NoError(t, cfg.StateGen.SaveState(ctx, bytesutil.ToBytes32(bState.FinalizedCheckpoint().Root), bState))
t.Fatal(err)
}
chainService, err := NewService(ctx, cfg) chainService, err := NewService(ctx, cfg)
require.NoError(t, err, "Unable to setup chain service") require.NoError(t, err, "Unable to setup chain service")
@@ -245,12 +243,7 @@ func TestChainService_InitializeChainInfo(t *testing.T) {
require.NoError(t, db.SaveState(ctx, headState, headRoot)) require.NoError(t, db.SaveState(ctx, headState, headRoot))
require.NoError(t, db.SaveState(ctx, headState, genesisRoot)) require.NoError(t, db.SaveState(ctx, headState, genesisRoot))
require.NoError(t, db.SaveBlock(ctx, headBlock)) require.NoError(t, db.SaveBlock(ctx, headBlock))
if err := db.SaveFinalizedCheckpoint(ctx, &ethpb.Checkpoint{ require.NoError(t, db.SaveFinalizedCheckpoint(ctx, &ethpb.Checkpoint{Epoch: helpers.SlotToEpoch(finalizedSlot), Root: headRoot[:]}))
Epoch: helpers.SlotToEpoch(finalizedSlot),
Root: headRoot[:],
}); err != nil {
t.Fatal(err)
}
c := &Service{beaconDB: db, stateGen: stategen.New(db, sc)} c := &Service{beaconDB: db, stateGen: stategen.New(db, sc)}
require.NoError(t, c.initializeChainInfo(ctx)) require.NoError(t, c.initializeChainInfo(ctx))
headBlk, err := c.HeadBlock(ctx) headBlk, err := c.HeadBlock(ctx)

View File

@@ -1,7 +1,6 @@
package epoch package epoch
import ( import (
"bytes"
"testing" "testing"
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
@@ -286,9 +285,9 @@ func TestProcessFinalUpdates_CanProcess(t *testing.T) {
assert.Equal(t, newS.Slashings()[ce], newS.Slashings()[ne], "Unexpected slashed balance") assert.Equal(t, newS.Slashings()[ce], newS.Slashings()[ne], "Unexpected slashed balance")
// Verify randao is correctly updated in the right position. // Verify randao is correctly updated in the right position.
if mix, err := newS.RandaoMixAtIndex(ne); err != nil || bytes.Equal(mix, params.BeaconConfig().ZeroHash[:]) { mix, err := newS.RandaoMixAtIndex(ne)
t.Error("latest RANDAO still zero hashes") assert.NoError(t, err)
} assert.DeepNotEqual(t, params.BeaconConfig().ZeroHash[:], mix, "latest RANDAO still zero hashes")
// Verify historical root accumulator was appended. // Verify historical root accumulator was appended.
assert.Equal(t, 1, len(newS.HistoricalRoots()), "Unexpected slashed balance") assert.Equal(t, 1, len(newS.HistoricalRoots()), "Unexpected slashed balance")

View File

@@ -154,9 +154,9 @@ func Test_ValidateAttestationTime(t *testing.T) {
genesisTime time.Time genesisTime time.Time
} }
tests := []struct { tests := []struct {
name string name string
args args args args
wantErr bool wantedErr string
}{ }{
{ {
name: "attestation.slot == current_slot", name: "attestation.slot == current_slot",
@@ -164,7 +164,6 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 15, attSlot: 15,
genesisTime: roughtime.Now().Add(-15 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second), genesisTime: roughtime.Now().Add(-15 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second),
}, },
wantErr: false,
}, },
{ {
name: "attestation.slot == current_slot, received in middle of slot", name: "attestation.slot == current_slot, received in middle of slot",
@@ -174,7 +173,6 @@ func Test_ValidateAttestationTime(t *testing.T) {
-15 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second, -15 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second,
).Add(-(time.Duration(params.BeaconConfig().SecondsPerSlot/2) * time.Second)), ).Add(-(time.Duration(params.BeaconConfig().SecondsPerSlot/2) * time.Second)),
}, },
wantErr: false,
}, },
{ {
name: "attestation.slot == current_slot, received 200ms early", name: "attestation.slot == current_slot, received 200ms early",
@@ -184,7 +182,6 @@ func Test_ValidateAttestationTime(t *testing.T) {
-16 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second, -16 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second,
).Add(-200 * time.Millisecond), ).Add(-200 * time.Millisecond),
}, },
wantErr: false,
}, },
{ {
name: "attestation.slot > current_slot", name: "attestation.slot > current_slot",
@@ -192,7 +189,7 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 16, attSlot: 16,
genesisTime: roughtime.Now().Add(-15 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second), genesisTime: roughtime.Now().Add(-15 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second),
}, },
wantErr: true, wantedErr: "not within attestation propagation range",
}, },
{ {
name: "attestation.slot < current_slot-ATTESTATION_PROPAGATION_SLOT_RANGE", name: "attestation.slot < current_slot-ATTESTATION_PROPAGATION_SLOT_RANGE",
@@ -200,7 +197,7 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 100 - params.BeaconNetworkConfig().AttestationPropagationSlotRange - 1, attSlot: 100 - params.BeaconNetworkConfig().AttestationPropagationSlotRange - 1,
genesisTime: roughtime.Now().Add(-100 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second), genesisTime: roughtime.Now().Add(-100 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second),
}, },
wantErr: true, wantedErr: "not within attestation propagation range",
}, },
{ {
name: "attestation.slot = current_slot-ATTESTATION_PROPAGATION_SLOT_RANGE", name: "attestation.slot = current_slot-ATTESTATION_PROPAGATION_SLOT_RANGE",
@@ -208,7 +205,6 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 100 - params.BeaconNetworkConfig().AttestationPropagationSlotRange, attSlot: 100 - params.BeaconNetworkConfig().AttestationPropagationSlotRange,
genesisTime: roughtime.Now().Add(-100 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second), genesisTime: roughtime.Now().Add(-100 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second),
}, },
wantErr: false,
}, },
{ {
name: "attestation.slot = current_slot-ATTESTATION_PROPAGATION_SLOT_RANGE, received 200ms late", name: "attestation.slot = current_slot-ATTESTATION_PROPAGATION_SLOT_RANGE, received 200ms late",
@@ -218,13 +214,15 @@ func Test_ValidateAttestationTime(t *testing.T) {
-100 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second, -100 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second,
).Add(200 * time.Millisecond), ).Add(200 * time.Millisecond),
}, },
wantErr: false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if err := helpers.ValidateAttestationTime(tt.args.attSlot, tt.args.genesisTime); (err != nil) != tt.wantErr { err := helpers.ValidateAttestationTime(tt.args.attSlot, tt.args.genesisTime)
t.Errorf("validateAggregateAttTime() error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
} }
}) })
} }

View File

@@ -328,14 +328,9 @@ func TestVerifyAttestationBitfieldLengths_OK(t *testing.T) {
require.NoError(t, state.SetSlot(tt.stateSlot)) require.NoError(t, state.SetSlot(tt.stateSlot))
err := VerifyAttestationBitfieldLengths(state, tt.attestation) err := VerifyAttestationBitfieldLengths(state, tt.attestation)
if tt.verificationFailure { if tt.verificationFailure {
if err == nil { assert.NotNil(t, err, "Verification succeeded when it was supposed to fail")
t.Error("verification succeeded when it was supposed to fail") } else {
} assert.NoError(t, err, "%d Failed to verify bitfield: %v", i, err)
continue
}
if err != nil {
t.Errorf("%d Failed to verify bitfield: %v", i, err)
continue
} }
} }
} }

View File

@@ -2,7 +2,6 @@ package helpers
import ( import (
"math" "math"
"reflect"
"testing" "testing"
"time" "time"
@@ -190,10 +189,10 @@ func TestSlotToTime(t *testing.T) {
slot uint64 slot uint64
} }
tests := []struct { tests := []struct {
name string name string
args args args args
want time.Time want time.Time
wantErr bool wantedErr string
}{ }{
{ {
name: "slot_0", name: "slot_0",
@@ -201,8 +200,7 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 0, genesisTimeSec: 0,
slot: 0, slot: 0,
}, },
want: time.Unix(0, 0), want: time.Unix(0, 0),
wantErr: false,
}, },
{ {
name: "slot_1", name: "slot_1",
@@ -210,8 +208,7 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 0, genesisTimeSec: 0,
slot: 1, slot: 1,
}, },
want: time.Unix(int64(1*params.BeaconConfig().SecondsPerSlot), 0), want: time.Unix(int64(1*params.BeaconConfig().SecondsPerSlot), 0),
wantErr: false,
}, },
{ {
name: "slot_12", name: "slot_12",
@@ -219,8 +216,7 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 500, genesisTimeSec: 500,
slot: 12, slot: 12,
}, },
want: time.Unix(500+int64(12*params.BeaconConfig().SecondsPerSlot), 0), want: time.Unix(500+int64(12*params.BeaconConfig().SecondsPerSlot), 0),
wantErr: false,
}, },
{ {
name: "overflow", name: "overflow",
@@ -228,13 +224,17 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 500, genesisTimeSec: 500,
slot: math.MaxUint64, slot: math.MaxUint64,
}, },
wantErr: true, wantedErr: "is in the far distant future",
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if got, err := SlotToTime(tt.args.genesisTimeSec, tt.args.slot); (err != nil) != tt.wantErr && !reflect.DeepEqual(got, tt.want) { got, err := SlotToTime(tt.args.genesisTimeSec, tt.args.slot)
t.Errorf("SlotToTime() = %v, want %v", got, tt.want) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
assert.DeepEqual(t, tt.want, got)
} }
}) })
} }
@@ -247,9 +247,9 @@ func TestVerifySlotTime(t *testing.T) {
timeTolerance time.Duration timeTolerance time.Duration
} }
tests := []struct { tests := []struct {
name string name string
args args args args
wantErr bool wantedErr string
}{ }{
{ {
name: "Past slot", name: "Past slot",
@@ -257,7 +257,6 @@ func TestVerifySlotTime(t *testing.T) {
genesisTime: roughtime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix(), genesisTime: roughtime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix(),
slot: 3, slot: 3,
}, },
wantErr: false,
}, },
{ {
name: "within tolerance", name: "within tolerance",
@@ -265,7 +264,6 @@ func TestVerifySlotTime(t *testing.T) {
genesisTime: roughtime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Add(20 * time.Millisecond).Unix(), genesisTime: roughtime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Add(20 * time.Millisecond).Unix(),
slot: 5, slot: 5,
}, },
wantErr: false,
}, },
{ {
name: "future slot", name: "future slot",
@@ -273,13 +271,16 @@ func TestVerifySlotTime(t *testing.T) {
genesisTime: roughtime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix(), genesisTime: roughtime.Now().Add(-1 * 5 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second).Unix(),
slot: 6, slot: 6,
}, },
wantErr: true, wantedErr: "could not process slot from the future",
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if err := VerifySlotTime(uint64(tt.args.genesisTime), tt.args.slot, tt.args.timeTolerance); (err != nil) != tt.wantErr { err := VerifySlotTime(uint64(tt.args.genesisTime), tt.args.slot, tt.args.timeTolerance)
t.Errorf("VerifySlotTime() error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
} }
}) })
} }

View File

@@ -415,10 +415,10 @@ func TestActiveValidatorIndices(t *testing.T) {
epoch uint64 epoch uint64
} }
tests := []struct { tests := []struct {
name string name string
args args args args
want []uint64 want []uint64
wantErr bool wantedErr string
}{ }{
{ {
name: "all_active_epoch_10", name: "all_active_epoch_10",
@@ -558,8 +558,8 @@ func TestActiveValidatorIndices(t *testing.T) {
s, err := beaconstate.InitializeFromProto(tt.args.state) s, err := beaconstate.InitializeFromProto(tt.args.state)
require.NoError(t, err) require.NoError(t, err)
got, err := ActiveValidatorIndices(s, tt.args.epoch) got, err := ActiveValidatorIndices(s, tt.args.epoch)
if (err != nil) != tt.wantErr { if tt.wantedErr != "" {
t.Errorf("ActiveValidatorIndices() error = %v, wantErr %v", err, tt.wantErr) assert.ErrorContains(t, tt.wantedErr, err)
return return
} }
assert.DeepEqual(t, tt.want, got, "ActiveValidatorIndices()") assert.DeepEqual(t, tt.want, got, "ActiveValidatorIndices()")
@@ -576,10 +576,10 @@ func TestComputeProposerIndex(t *testing.T) {
seed [32]byte seed [32]byte
} }
tests := []struct { tests := []struct {
name string name string
args args args args
want uint64 want uint64
wantErr bool wantedErr string
}{ }{
{ {
name: "all_active_indices", name: "all_active_indices",
@@ -624,7 +624,7 @@ func TestComputeProposerIndex(t *testing.T) {
indices: []uint64{}, indices: []uint64{},
seed: seed, seed: seed,
}, },
wantErr: true, wantedErr: "empty active indices list",
}, },
{ {
name: "active_indices_out_of_range", name: "active_indices_out_of_range",
@@ -639,7 +639,7 @@ func TestComputeProposerIndex(t *testing.T) {
indices: []uint64{100}, indices: []uint64{100},
seed: seed, seed: seed,
}, },
wantErr: true, wantedErr: "active index out of range",
}, },
{ {
name: "second_half_active", name: "second_half_active",
@@ -681,13 +681,10 @@ func TestComputeProposerIndex(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
bState := &pb.BeaconState{Validators: tt.args.validators} bState := &pb.BeaconState{Validators: tt.args.validators}
stTrie, err := beaconstate.InitializeFromProtoUnsafe(bState) stTrie, err := beaconstate.InitializeFromProtoUnsafe(bState)
if err != nil { require.NoError(t, err)
t.Error(err)
return
}
got, err := ComputeProposerIndex(stTrie, tt.args.indices, tt.args.seed) got, err := ComputeProposerIndex(stTrie, tt.args.indices, tt.args.seed)
if (err != nil) != tt.wantErr { if tt.wantedErr != "" {
t.Errorf("ComputeProposerIndex() error = %v, wantErr %v", err, tt.wantErr) assert.ErrorContains(t, tt.wantedErr, err)
return return
} }
assert.Equal(t, tt.want, got, "ComputeProposerIndex()") assert.Equal(t, tt.want, got, "ComputeProposerIndex()")

View File

@@ -101,9 +101,8 @@ func BenchmarkHashTreeRoot_FullState(b *testing.B) {
b.N = 50 b.N = 50
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if _, err := ssz.HashTreeRoot(beaconState); err != nil { _, err := ssz.HashTreeRoot(beaconState)
b.Fatal(err) require.NoError(b, err)
}
} }
} }

View File

@@ -21,21 +21,19 @@ func Test_deleteValueForIndices(t *testing.T) {
inputIndices map[string][]byte inputIndices map[string][]byte
root []byte root []byte
outputIndices map[string][]byte outputIndices map[string][]byte
wantErr bool wantedErr string
}{ }{
{ {
name: "empty input, no root", name: "empty input, no root",
inputIndices: map[string][]byte{}, inputIndices: map[string][]byte{},
root: []byte{}, root: []byte{},
outputIndices: map[string][]byte{}, outputIndices: map[string][]byte{},
wantErr: false,
}, },
{ {
name: "empty input, root does not exist", name: "empty input, root does not exist",
inputIndices: map[string][]byte{}, inputIndices: map[string][]byte{},
root: bytesutil.PadTo([]byte("not found"), 32), root: bytesutil.PadTo([]byte("not found"), 32),
outputIndices: map[string][]byte{}, outputIndices: map[string][]byte{},
wantErr: false,
}, },
{ {
name: "non empty input, root does not exist", name: "non empty input, root does not exist",
@@ -46,7 +44,6 @@ func Test_deleteValueForIndices(t *testing.T) {
outputIndices: map[string][]byte{ outputIndices: map[string][]byte{
"blocks": bytesutil.PadTo([]byte{0xde, 0xad, 0xbe, 0xef}, 64), "blocks": bytesutil.PadTo([]byte{0xde, 0xad, 0xbe, 0xef}, 64),
}, },
wantErr: false,
}, },
{ {
name: "removes value for a single bucket", name: "removes value for a single bucket",
@@ -57,7 +54,6 @@ func Test_deleteValueForIndices(t *testing.T) {
outputIndices: map[string][]byte{ outputIndices: map[string][]byte{
"blocks": {0xad, 0xbe, 0xef}, "blocks": {0xad, 0xbe, 0xef},
}, },
wantErr: false,
}, },
{ {
name: "removes multi-byte value for a single bucket (non-aligned)", name: "removes multi-byte value for a single bucket (non-aligned)",
@@ -68,7 +64,6 @@ func Test_deleteValueForIndices(t *testing.T) {
outputIndices: map[string][]byte{ outputIndices: map[string][]byte{
"blocks": {0xde, 0xad, 0xbe, 0xef}, "blocks": {0xde, 0xad, 0xbe, 0xef},
}, },
wantErr: false,
}, },
{ {
name: "removes multi-byte value for a single bucket (non-aligned)", name: "removes multi-byte value for a single bucket (non-aligned)",
@@ -79,7 +74,6 @@ func Test_deleteValueForIndices(t *testing.T) {
outputIndices: map[string][]byte{ outputIndices: map[string][]byte{
"blocks": {0xde, 0xad, 0xff, 0x01}, "blocks": {0xde, 0xad, 0xff, 0x01},
}, },
wantErr: false,
}, },
{ {
name: "removes value from multiple buckets", name: "removes value from multiple buckets",
@@ -96,7 +90,6 @@ func Test_deleteValueForIndices(t *testing.T) {
"check-point": nil, "check-point": nil,
"powchain": {0xba, 0xad, 0xb0, 0x00, 0xff}, "powchain": {0xba, 0xad, 0xb0, 0x00, 0xff},
}, },
wantErr: false,
}, },
{ {
name: "root as subsequence of two values (preserve)", name: "root as subsequence of two values (preserve)",
@@ -127,9 +120,12 @@ func Test_deleteValueForIndices(t *testing.T) {
bkt := tx.Bucket([]byte(k)) bkt := tx.Bucket([]byte(k))
require.NoError(t, bkt.Put(idx, tt.inputIndices[k])) require.NoError(t, bkt.Put(idx, tt.inputIndices[k]))
} }
if err := deleteValueForIndices(context.Background(), tt.inputIndices, tt.root, tx); (err != nil) != tt.wantErr { err := deleteValueForIndices(context.Background(), tt.inputIndices, tt.root, tx)
t.Errorf("deleteValueForIndices() error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
return nil
} }
assert.NoError(t, err)
// Check updated indices. // Check updated indices.
for k, idx := range tt.inputIndices { for k, idx := range tt.inputIndices {
bkt := tx.Bucket([]byte(k)) bkt := tx.Bucket([]byte(k))

View File

@@ -51,6 +51,7 @@ go_test(
deps = [ deps = [
"//beacon-chain/core/feed/state:go_default_library", "//beacon-chain/core/feed/state:go_default_library",
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_sirupsen_logrus//hooks/test:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library", "@com_github_urfave_cli_v2//:go_default_library",

View File

@@ -9,6 +9,7 @@ import (
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state" statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
logTest "github.com/sirupsen/logrus/hooks/test" logTest "github.com/sirupsen/logrus/hooks/test"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
@@ -22,9 +23,7 @@ func TestNodeClose_OK(t *testing.T) {
hook := logTest.NewGlobal() hook := logTest.NewGlobal()
tmp := fmt.Sprintf("%s/datadirtest2", testutil.TempDir()) tmp := fmt.Sprintf("%s/datadirtest2", testutil.TempDir())
if err := os.RemoveAll(tmp); err != nil { require.NoError(t, os.RemoveAll(tmp))
t.Log(err)
}
app := cli.App{} app := cli.App{}
set := flag.NewFlagSet("test", 0) set := flag.NewFlagSet("test", 0)
@@ -37,28 +36,19 @@ func TestNodeClose_OK(t *testing.T) {
context := cli.NewContext(&app, set, nil) context := cli.NewContext(&app, set, nil)
node, err := NewBeaconNode(context) node, err := NewBeaconNode(context)
if err != nil { require.NoError(t, err)
t.Fatalf("Failed to create BeaconNode: %v", err)
}
node.Close() node.Close()
require.LogsContain(t, hook, "Stopping beacon node") require.LogsContain(t, hook, "Stopping beacon node")
require.NoError(t, os.RemoveAll(tmp))
if err := os.RemoveAll(tmp); err != nil {
t.Log(err)
}
} }
func TestBootStrapNodeFile(t *testing.T) { func TestBootStrapNodeFile(t *testing.T) {
file, err := ioutil.TempFile(testutil.TempDir(), "bootstrapFile") file, err := ioutil.TempFile(testutil.TempDir(), "bootstrapFile")
if err != nil { require.NoError(t, err)
t.Fatalf("Error in TempFile call: %v", err)
}
defer func() { defer func() {
if err := os.Remove(file.Name()); err != nil { assert.NoError(t, os.Remove(file.Name()))
t.Log(err)
}
}() }()
sampleNode0 := "- enr:-Ku4QMKVC_MowDsmEa20d5uGjrChI0h8_KsKXDmgVQbIbngZV0i" + sampleNode0 := "- enr:-Ku4QMKVC_MowDsmEa20d5uGjrChI0h8_KsKXDmgVQbIbngZV0i" +
@@ -68,15 +58,10 @@ func TestBootStrapNodeFile(t *testing.T) {
sampleNode1 := "- enr:-TESTNODE2" sampleNode1 := "- enr:-TESTNODE2"
sampleNode2 := "- enr:-TESTNODE3" sampleNode2 := "- enr:-TESTNODE3"
err = ioutil.WriteFile(file.Name(), []byte(sampleNode0+"\n"+sampleNode1+"\n"+sampleNode2), 0644) err = ioutil.WriteFile(file.Name(), []byte(sampleNode0+"\n"+sampleNode1+"\n"+sampleNode2), 0644)
if err != nil { require.NoError(t, err, "Error in WriteFile call")
t.Fatalf("Error in WriteFile call: %v", err)
}
nodeList, err := readbootNodes(file.Name()) nodeList, err := readbootNodes(file.Name())
if err != nil { require.NoError(t, err, "Error in readbootNodes call")
t.Fatalf("Error in readbootNodes call: %v", err) assert.Equal(t, sampleNode0[2:], nodeList[0], "Unexpected nodes")
} assert.Equal(t, sampleNode1[2:], nodeList[1], "Unexpected nodes")
if nodeList[0] != sampleNode0[2:] || nodeList[1] != sampleNode1[2:] || nodeList[2] != sampleNode2[2:] { assert.Equal(t, sampleNode2[2:], nodeList[2], "Unexpected nodes")
// nodeList's YAML parsing will have removed the leading "- "
t.Fatalf("TestBootStrapNodeFile failed. Nodes do not match")
}
} }

View File

@@ -1,7 +1,6 @@
package kv package kv
import ( import (
"reflect"
"sort" "sort"
"testing" "testing"
@@ -27,19 +26,11 @@ func TestKV_Aggregated_AggregateUnaggregatedAttestations(t *testing.T) {
att7 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b1100}, Signature: sig1.Marshal()} att7 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b1100}, Signature: sig1.Marshal()}
att8 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b1001}, Signature: sig2.Marshal()} att8 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b1001}, Signature: sig2.Marshal()}
atts := []*ethpb.Attestation{att1, att2, att3, att4, att5, att6, att7, att8} atts := []*ethpb.Attestation{att1, att2, att3, att4, att5, att6, att7, att8}
if err := cache.SaveUnaggregatedAttestations(atts); err != nil { require.NoError(t, cache.SaveUnaggregatedAttestations(atts))
t.Fatal(err) require.NoError(t, cache.AggregateUnaggregatedAttestations())
}
if err := cache.AggregateUnaggregatedAttestations(); err != nil {
t.Fatal(err)
}
if len(cache.AggregatedAttestationsBySlotIndex(1, 0)) != 1 { require.Equal(t, 1, len(cache.AggregatedAttestationsBySlotIndex(1, 0)), "Did not aggregate correctly")
t.Fatal("Did not aggregate correctly") require.Equal(t, 1, len(cache.AggregatedAttestationsBySlotIndex(2, 0)), "Did not aggregate correctly")
}
if len(cache.AggregatedAttestationsBySlotIndex(2, 0)) != 1 {
t.Fatal("Did not aggregate correctly")
}
} }
func TestKV_Aggregated_SaveAggregatedAttestation(t *testing.T) { func TestKV_Aggregated_SaveAggregatedAttestation(t *testing.T) {
@@ -103,25 +94,16 @@ func TestKV_Aggregated_SaveAggregatedAttestation(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
cache.seenAtt.Set(string(r[:]), []bitfield.Bitlist{{0xff}}, c.DefaultExpiration) cache.seenAtt.Set(string(r[:]), []bitfield.Bitlist{{0xff}}, c.DefaultExpiration)
if len(cache.unAggregatedAtt) != 0 { assert.Equal(t, 0, len(cache.unAggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
err := cache.SaveAggregatedAttestation(tt.att) err := cache.SaveAggregatedAttestation(tt.att)
if tt.wantErrString != "" && (err == nil || err.Error() != tt.wantErrString) { if tt.wantErrString != "" {
t.Errorf("Did not receive wanted error, want: %q, got: %v", tt.wantErrString, err) assert.ErrorContains(t, tt.wantErrString, err)
return } else {
} assert.NoError(t, err)
if tt.wantErrString == "" && err != nil {
t.Error(err)
return
}
if len(cache.aggregatedAtt) != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, len(cache.aggregatedAtt))
}
if cache.AggregatedAttestationCount() != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, cache.AggregatedAttestationCount())
} }
assert.Equal(t, tt.count, len(cache.aggregatedAtt), "Wrong attestation count")
assert.Equal(t, tt.count, cache.AggregatedAttestationCount(), "Wrong attestation count")
}) })
} }
} }
@@ -148,20 +130,15 @@ func TestKV_Aggregated_SaveAggregatedAttestations(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
if len(cache.aggregatedAtt) != 0 { assert.Equal(t, 0, len(cache.aggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
err := cache.SaveAggregatedAttestations(tt.atts) err := cache.SaveAggregatedAttestations(tt.atts)
if tt.wantErrString == "" && err != nil { if tt.wantErrString != "" {
t.Error(err) assert.ErrorContains(t, tt.wantErrString, err)
return } else {
} assert.NoError(t, err)
if len(cache.aggregatedAtt) != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, len(cache.aggregatedAtt))
}
if cache.AggregatedAttestationCount() != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, cache.AggregatedAttestationCount())
} }
assert.Equal(t, tt.count, len(cache.aggregatedAtt), "Wrong attestation count")
assert.Equal(t, tt.count, cache.AggregatedAttestationCount(), "Wrong attestation count")
}) })
} }
} }
@@ -175,9 +152,7 @@ func TestKV_Aggregated_AggregatedAttestations(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3} atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts { for _, att := range atts {
if err := cache.SaveAggregatedAttestation(att); err != nil { require.NoError(t, cache.SaveAggregatedAttestation(att))
t.Fatal(err)
}
} }
returned := cache.AggregatedAttestations() returned := cache.AggregatedAttestations()
@@ -190,23 +165,16 @@ func TestKV_Aggregated_AggregatedAttestations(t *testing.T) {
func TestKV_Aggregated_DeleteAggregatedAttestation(t *testing.T) { func TestKV_Aggregated_DeleteAggregatedAttestation(t *testing.T) {
t.Run("nil attestation", func(t *testing.T) { t.Run("nil attestation", func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
if err := cache.DeleteAggregatedAttestation(nil); err != nil { assert.NoError(t, cache.DeleteAggregatedAttestation(nil))
t.Error(err)
}
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b10101}} att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b10101}}
if err := cache.DeleteAggregatedAttestation(att); err != nil { assert.NoError(t, cache.DeleteAggregatedAttestation(att))
t.Error(err)
}
}) })
t.Run("non aggregated attestation", func(t *testing.T) { t.Run("non aggregated attestation", func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1001}, Data: &ethpb.AttestationData{Slot: 2}} att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1001}, Data: &ethpb.AttestationData{Slot: 2}}
err := cache.DeleteAggregatedAttestation(att) err := cache.DeleteAggregatedAttestation(att)
wantErr := "attestation is not aggregated" assert.ErrorContains(t, "attestation is not aggregated", err)
if err == nil || err.Error() != wantErr {
t.Errorf("Did not receive wanted error, want: %q, got: %v", wantErr, err)
}
}) })
t.Run("invalid hash", func(t *testing.T) { t.Run("invalid hash", func(t *testing.T) {
@@ -220,17 +188,13 @@ func TestKV_Aggregated_DeleteAggregatedAttestation(t *testing.T) {
} }
err := cache.DeleteAggregatedAttestation(att) err := cache.DeleteAggregatedAttestation(att)
wantErr := "could not tree hash attestation data: incorrect fixed bytes marshalling" wantErr := "could not tree hash attestation data: incorrect fixed bytes marshalling"
if err == nil || err.Error() != wantErr { assert.ErrorContains(t, wantErr, err)
t.Errorf("Did not receive wanted error, want: %q, got: %v", wantErr, err)
}
}) })
t.Run("nonexistent attestation", func(t *testing.T) { t.Run("nonexistent attestation", func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1111}, Data: &ethpb.AttestationData{Slot: 2}} att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1111}, Data: &ethpb.AttestationData{Slot: 2}}
if err := cache.DeleteAggregatedAttestation(att); err != nil { assert.NoError(t, cache.DeleteAggregatedAttestation(att))
t.Error(err)
}
}) })
t.Run("non-filtered deletion", func(t *testing.T) { t.Run("non-filtered deletion", func(t *testing.T) {
@@ -240,16 +204,9 @@ func TestKV_Aggregated_DeleteAggregatedAttestation(t *testing.T) {
att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b1101}} att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b1101}}
att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b10101}} att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b10101}}
atts := []*ethpb.Attestation{att1, att2, att3, att4} atts := []*ethpb.Attestation{att1, att2, att3, att4}
if err := cache.SaveAggregatedAttestations(atts); err != nil { require.NoError(t, cache.SaveAggregatedAttestations(atts))
t.Fatal(err) require.NoError(t, cache.DeleteAggregatedAttestation(att1))
} require.NoError(t, cache.DeleteAggregatedAttestation(att3))
if err := cache.DeleteAggregatedAttestation(att1); err != nil {
t.Fatal(err)
}
if err := cache.DeleteAggregatedAttestation(att3); err != nil {
t.Fatal(err)
}
returned := cache.AggregatedAttestations() returned := cache.AggregatedAttestations()
wanted := []*ethpb.Attestation{att2} wanted := []*ethpb.Attestation{att2}
@@ -263,16 +220,10 @@ func TestKV_Aggregated_DeleteAggregatedAttestation(t *testing.T) {
att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b110100}} att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b110100}}
att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b110101}} att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b110101}}
atts := []*ethpb.Attestation{att1, att2, att3, att4} atts := []*ethpb.Attestation{att1, att2, att3, att4}
if err := cache.SaveAggregatedAttestations(atts); err != nil { require.NoError(t, cache.SaveAggregatedAttestations(atts))
t.Fatal(err)
}
if cache.AggregatedAttestationCount() != 2 { assert.Equal(t, 2, cache.AggregatedAttestationCount(), "Unexpected number of atts")
t.Error("Unexpected number of atts") require.NoError(t, cache.DeleteAggregatedAttestation(att4))
}
if err := cache.DeleteAggregatedAttestation(att4); err != nil {
t.Fatal(err)
}
returned := cache.AggregatedAttestations() returned := cache.AggregatedAttestations()
wanted := []*ethpb.Attestation{att1, att2} wanted := []*ethpb.Attestation{att1, att2}
@@ -456,27 +407,19 @@ func TestKV_Aggregated_HasAggregatedAttestation(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
if err := cache.SaveAggregatedAttestations(tt.existing); err != nil { require.NoError(t, cache.SaveAggregatedAttestations(tt.existing))
t.Error(err)
}
result, err := cache.HasAggregatedAttestation(tt.input) result, err := cache.HasAggregatedAttestation(tt.input)
require.NoError(t, err) require.NoError(t, err)
if result != tt.want { assert.Equal(t, tt.want, result)
t.Errorf("Result = %v, wanted = %v", result, tt.want)
}
// Same test for block attestations // Same test for block attestations
cache = NewAttCaches() cache = NewAttCaches()
if err := cache.SaveBlockAttestations(tt.existing); err != nil { assert.NoError(t, cache.SaveBlockAttestations(tt.existing))
t.Error(err)
}
result, err = cache.HasAggregatedAttestation(tt.input) result, err = cache.HasAggregatedAttestation(tt.input)
require.NoError(t, err) require.NoError(t, err)
if result != tt.want { assert.Equal(t, tt.want, result)
t.Errorf("Result = %v, wanted = %v", result, tt.want)
}
}) })
} }
} }
@@ -489,15 +432,12 @@ func TestKV_Aggregated_DuplicateAggregatedAttestations(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2} atts := []*ethpb.Attestation{att1, att2}
for _, att := range atts { for _, att := range atts {
if err := cache.SaveAggregatedAttestation(att); err != nil { require.NoError(t, cache.SaveAggregatedAttestation(att))
t.Fatal(err)
}
} }
returned := cache.AggregatedAttestations() returned := cache.AggregatedAttestations()
// It should have only returned att2. // It should have only returned att2.
if !reflect.DeepEqual(att2, returned[0]) || len(returned) != 1 { assert.DeepEqual(t, att2, returned[0], "Did not receive correct aggregated atts")
t.Error("Did not receive correct aggregated atts") assert.Equal(t, 1, len(returned), "Did not receive correct aggregated atts")
}
} }

View File

@@ -5,6 +5,7 @@ import (
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations/kv" "github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations/kv"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
) )
func BenchmarkAttCaches(b *testing.B) { func BenchmarkAttCaches(b *testing.B) {
@@ -13,11 +14,7 @@ func BenchmarkAttCaches(b *testing.B) {
att := &ethpb.Attestation{} att := &ethpb.Attestation{}
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if err := ac.SaveUnaggregatedAttestation(att); err != nil { assert.NoError(b, ac.SaveUnaggregatedAttestation(att))
b.Error(err) assert.NoError(b, ac.DeleteAggregatedAttestation(att))
}
if err := ac.DeleteAggregatedAttestation(att); err != nil {
b.Error(err)
}
} }
} }

View File

@@ -7,6 +7,7 @@ import (
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestKV_BlockAttestation_CanSaveRetrieve(t *testing.T) { func TestKV_BlockAttestation_CanSaveRetrieve(t *testing.T) {
@@ -18,9 +19,7 @@ func TestKV_BlockAttestation_CanSaveRetrieve(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3} atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts { for _, att := range atts {
if err := cache.SaveBlockAttestation(att); err != nil { require.NoError(t, cache.SaveBlockAttestation(att))
t.Fatal(err)
}
} }
returned := cache.BlockAttestations() returned := cache.BlockAttestations()
@@ -41,17 +40,11 @@ func TestKV_BlockAttestation_CanDelete(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3} atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts { for _, att := range atts {
if err := cache.SaveBlockAttestation(att); err != nil { require.NoError(t, cache.SaveBlockAttestation(att))
t.Fatal(err)
}
} }
if err := cache.DeleteBlockAttestation(att1); err != nil { require.NoError(t, cache.DeleteBlockAttestation(att1))
t.Fatal(err) require.NoError(t, cache.DeleteBlockAttestation(att3))
}
if err := cache.DeleteBlockAttestation(att3); err != nil {
t.Fatal(err)
}
returned := cache.BlockAttestations() returned := cache.BlockAttestations()
wanted := []*ethpb.Attestation{att2} wanted := []*ethpb.Attestation{att2}

View File

@@ -7,6 +7,7 @@ import (
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield" "github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestKV_Forkchoice_CanSaveRetrieve(t *testing.T) { func TestKV_Forkchoice_CanSaveRetrieve(t *testing.T) {
@@ -18,9 +19,7 @@ func TestKV_Forkchoice_CanSaveRetrieve(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3} atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts { for _, att := range atts {
if err := cache.SaveForkchoiceAttestation(att); err != nil { require.NoError(t, cache.SaveForkchoiceAttestation(att))
t.Fatal(err)
}
} }
returned := cache.ForkchoiceAttestations() returned := cache.ForkchoiceAttestations()
@@ -41,17 +40,11 @@ func TestKV_Forkchoice_CanDelete(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3} atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts { for _, att := range atts {
if err := cache.SaveForkchoiceAttestation(att); err != nil { require.NoError(t, cache.SaveForkchoiceAttestation(att))
t.Fatal(err)
}
} }
if err := cache.DeleteForkchoiceAttestation(att1); err != nil { require.NoError(t, cache.DeleteForkchoiceAttestation(att1))
t.Fatal(err) require.NoError(t, cache.DeleteForkchoiceAttestation(att3))
}
if err := cache.DeleteForkchoiceAttestation(att3); err != nil {
t.Fatal(err)
}
returned := cache.ForkchoiceAttestations() returned := cache.ForkchoiceAttestations()
wanted := []*ethpb.Attestation{att2} wanted := []*ethpb.Attestation{att2}

View File

@@ -65,25 +65,16 @@ func TestKV_Unaggregated_SaveUnaggregatedAttestation(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
cache.seenAtt.Set(string(r[:]), []bitfield.Bitlist{{0xff}}, c.DefaultExpiration) cache.seenAtt.Set(string(r[:]), []bitfield.Bitlist{{0xff}}, c.DefaultExpiration)
if len(cache.unAggregatedAtt) != 0 { assert.Equal(t, 0, len(cache.unAggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
err := cache.SaveUnaggregatedAttestation(tt.att) err := cache.SaveUnaggregatedAttestation(tt.att)
if tt.wantErrString != "" && (err == nil || err.Error() != tt.wantErrString) { if tt.wantErrString != "" {
t.Errorf("Did not receive wanted error, want: %q, got: %v", tt.wantErrString, err) assert.ErrorContains(t, tt.wantErrString, err)
return } else {
} assert.NoError(t, err)
if tt.wantErrString == "" && err != nil {
t.Error(err)
return
}
if len(cache.unAggregatedAtt) != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, len(cache.unAggregatedAtt))
}
if cache.UnaggregatedAttestationCount() != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, cache.UnaggregatedAttestationCount())
} }
assert.Equal(t, tt.count, len(cache.unAggregatedAtt), "Wrong attestation count")
assert.Equal(t, tt.count, cache.UnaggregatedAttestationCount(), "Wrong attestation count")
}) })
} }
} }
@@ -119,23 +110,16 @@ func TestKV_Unaggregated_SaveUnaggregatedAttestations(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
if len(cache.unAggregatedAtt) != 0 { assert.Equal(t, 0, len(cache.unAggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
err := cache.SaveUnaggregatedAttestations(tt.atts) err := cache.SaveUnaggregatedAttestations(tt.atts)
if tt.wantErrString != "" && (err == nil || err.Error() != tt.wantErrString) { if tt.wantErrString != "" {
t.Errorf("Did not receive wanted error, want: %q, got: %v", tt.wantErrString, err) assert.ErrorContains(t, tt.wantErrString, err)
} } else {
if tt.wantErrString == "" && err != nil { assert.NoError(t, err)
t.Error(err)
}
if len(cache.unAggregatedAtt) != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, len(cache.unAggregatedAtt))
}
if cache.UnaggregatedAttestationCount() != tt.count {
t.Errorf("Wrong attestation count, want: %d, got: %d", tt.count, cache.UnaggregatedAttestationCount())
} }
assert.Equal(t, tt.count, len(cache.unAggregatedAtt), "Wrong attestation count")
assert.Equal(t, tt.count, cache.UnaggregatedAttestationCount(), "Wrong attestation count")
}) })
} }
} }
@@ -143,19 +127,14 @@ func TestKV_Unaggregated_SaveUnaggregatedAttestations(t *testing.T) {
func TestKV_Unaggregated_DeleteUnaggregatedAttestation(t *testing.T) { func TestKV_Unaggregated_DeleteUnaggregatedAttestation(t *testing.T) {
t.Run("nil attestation", func(t *testing.T) { t.Run("nil attestation", func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
if err := cache.DeleteUnaggregatedAttestation(nil); err != nil { assert.NoError(t, cache.DeleteUnaggregatedAttestation(nil))
t.Error(err)
}
}) })
t.Run("aggregated attestation", func(t *testing.T) { t.Run("aggregated attestation", func(t *testing.T) {
cache := NewAttCaches() cache := NewAttCaches()
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1111}, Data: &ethpb.AttestationData{Slot: 2}} att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1111}, Data: &ethpb.AttestationData{Slot: 2}}
err := cache.DeleteUnaggregatedAttestation(att) err := cache.DeleteUnaggregatedAttestation(att)
wantErr := "attestation is aggregated" assert.ErrorContains(t, "attestation is aggregated", err)
if err == nil || err.Error() != wantErr {
t.Errorf("Did not receive wanted error, want: %q, got: %v", wantErr, err)
}
}) })
t.Run("successful deletion", func(t *testing.T) { t.Run("successful deletion", func(t *testing.T) {
@@ -164,13 +143,9 @@ func TestKV_Unaggregated_DeleteUnaggregatedAttestation(t *testing.T) {
att2 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b110}} att2 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b110}}
att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b110}} att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b110}}
atts := []*ethpb.Attestation{att1, att2, att3} atts := []*ethpb.Attestation{att1, att2, att3}
if err := cache.SaveUnaggregatedAttestations(atts); err != nil { require.NoError(t, cache.SaveUnaggregatedAttestations(atts))
t.Fatal(err)
}
for _, att := range atts { for _, att := range atts {
if err := cache.DeleteUnaggregatedAttestation(att); err != nil { assert.NoError(t, cache.DeleteUnaggregatedAttestation(att))
t.Error(err)
}
} }
returned, err := cache.UnaggregatedAttestations() returned, err := cache.UnaggregatedAttestations()
require.NoError(t, err) require.NoError(t, err)
@@ -187,9 +162,7 @@ func TestKV_Unaggregated_UnaggregatedAttestationsBySlotIndex(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3} atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts { for _, att := range atts {
if err := cache.SaveUnaggregatedAttestation(att); err != nil { require.NoError(t, cache.SaveUnaggregatedAttestation(att))
t.Fatal(err)
}
} }
returned := cache.UnaggregatedAttestationsBySlotIndex(1, 1) returned := cache.UnaggregatedAttestationsBySlotIndex(1, 1)

View File

@@ -83,19 +83,10 @@ func TestBatchAttestations_Multiple(t *testing.T) {
Source: &ethpb.Checkpoint{Root: mockRoot[:]}, Source: &ethpb.Checkpoint{Root: mockRoot[:]},
Target: &ethpb.Checkpoint{Root: mockRoot[:]}}, AggregationBits: bitfield.Bitlist{0b100011}, Signature: sig.Marshal()}, // Duplicated Target: &ethpb.Checkpoint{Root: mockRoot[:]}}, AggregationBits: bitfield.Bitlist{0b100011}, Signature: sig.Marshal()}, // Duplicated
} }
if err := s.pool.SaveUnaggregatedAttestations(unaggregatedAtts); err != nil { require.NoError(t, s.pool.SaveUnaggregatedAttestations(unaggregatedAtts))
t.Fatal(err) require.NoError(t, s.pool.SaveAggregatedAttestations(aggregatedAtts))
} require.NoError(t, s.pool.SaveBlockAttestations(blockAtts))
if err := s.pool.SaveAggregatedAttestations(aggregatedAtts); err != nil { require.NoError(t, s.batchForkChoiceAtts(context.Background()))
t.Fatal(err)
}
if err := s.pool.SaveBlockAttestations(blockAtts); err != nil {
t.Fatal(err)
}
if err := s.batchForkChoiceAtts(context.Background()); err != nil {
t.Fatal(err)
}
wanted, err := attaggregation.Aggregate([]*ethpb.Attestation{aggregatedAtts[0], blockAtts[0]}) wanted, err := attaggregation.Aggregate([]*ethpb.Attestation{aggregatedAtts[0], blockAtts[0]})
require.NoError(t, err) require.NoError(t, err)
@@ -106,9 +97,7 @@ func TestBatchAttestations_Multiple(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
wanted = append(wanted, aggregated...) wanted = append(wanted, aggregated...)
if err := s.pool.AggregateUnaggregatedAttestations(); err != nil { require.NoError(t, s.pool.AggregateUnaggregatedAttestations())
return
}
received := s.pool.ForkchoiceAttestations() received := s.pool.ForkchoiceAttestations()
sort.Slice(received, func(i, j int) bool { sort.Slice(received, func(i, j int) bool {
@@ -147,21 +136,10 @@ func TestBatchAttestations_Single(t *testing.T) {
{Data: d, AggregationBits: bitfield.Bitlist{0b100010}, Signature: sig.Marshal()}, {Data: d, AggregationBits: bitfield.Bitlist{0b100010}, Signature: sig.Marshal()},
{Data: d, AggregationBits: bitfield.Bitlist{0b110010}, Signature: sig.Marshal()}, // Duplicated {Data: d, AggregationBits: bitfield.Bitlist{0b110010}, Signature: sig.Marshal()}, // Duplicated
} }
if err := s.pool.SaveUnaggregatedAttestations(unaggregatedAtts); err != nil { require.NoError(t, s.pool.SaveUnaggregatedAttestations(unaggregatedAtts))
t.Fatal(err) require.NoError(t, s.pool.SaveAggregatedAttestations(aggregatedAtts))
} require.NoError(t, s.pool.SaveBlockAttestations(blockAtts))
require.NoError(t, s.batchForkChoiceAtts(context.Background()))
if err := s.pool.SaveAggregatedAttestations(aggregatedAtts); err != nil {
t.Fatal(err)
}
if err := s.pool.SaveBlockAttestations(blockAtts); err != nil {
t.Fatal(err)
}
if err := s.batchForkChoiceAtts(context.Background()); err != nil {
t.Fatal(err)
}
wanted, err := attaggregation.Aggregate(append(aggregatedAtts, unaggregatedAtts...)) wanted, err := attaggregation.Aggregate(append(aggregatedAtts, unaggregatedAtts...))
require.NoError(t, err) require.NoError(t, err)
@@ -189,9 +167,7 @@ func TestAggregateAndSaveForkChoiceAtts_Single(t *testing.T) {
atts := []*ethpb.Attestation{ atts := []*ethpb.Attestation{
{Data: d, AggregationBits: bitfield.Bitlist{0b101}, Signature: sig.Marshal()}, {Data: d, AggregationBits: bitfield.Bitlist{0b101}, Signature: sig.Marshal()},
{Data: d, AggregationBits: bitfield.Bitlist{0b110}, Signature: sig.Marshal()}} {Data: d, AggregationBits: bitfield.Bitlist{0b110}, Signature: sig.Marshal()}}
if err := s.aggregateAndSaveForkChoiceAtts(atts); err != nil { require.NoError(t, s.aggregateAndSaveForkChoiceAtts(atts))
t.Fatal(err)
}
wanted, err := attaggregation.Aggregate(atts) wanted, err := attaggregation.Aggregate(atts)
require.NoError(t, err) require.NoError(t, err)
@@ -211,37 +187,27 @@ func TestAggregateAndSaveForkChoiceAtts_Multiple(t *testing.T) {
Target: &ethpb.Checkpoint{Root: mockRoot[:]}, Target: &ethpb.Checkpoint{Root: mockRoot[:]},
} }
d1, ok := proto.Clone(d).(*ethpb.AttestationData) d1, ok := proto.Clone(d).(*ethpb.AttestationData)
if !ok { require.Equal(t, true, ok, "Entity is not of type *ethpb.AttestationData")
t.Fatal("Entity is not of type *ethpb.AttestationData")
}
d1.Slot = 1 d1.Slot = 1
d2, ok := proto.Clone(d).(*ethpb.AttestationData) d2, ok := proto.Clone(d).(*ethpb.AttestationData)
if !ok { require.Equal(t, true, ok, "Entity is not of type *ethpb.AttestationData")
t.Fatal("Entity is not of type *ethpb.AttestationData")
}
d2.Slot = 2 d2.Slot = 2
atts1 := []*ethpb.Attestation{ atts1 := []*ethpb.Attestation{
{Data: d, AggregationBits: bitfield.Bitlist{0b101}, Signature: sig.Marshal()}, {Data: d, AggregationBits: bitfield.Bitlist{0b101}, Signature: sig.Marshal()},
{Data: d, AggregationBits: bitfield.Bitlist{0b110}, Signature: sig.Marshal()}, {Data: d, AggregationBits: bitfield.Bitlist{0b110}, Signature: sig.Marshal()},
} }
if err := s.aggregateAndSaveForkChoiceAtts(atts1); err != nil { require.NoError(t, s.aggregateAndSaveForkChoiceAtts(atts1))
t.Fatal(err)
}
atts2 := []*ethpb.Attestation{ atts2 := []*ethpb.Attestation{
{Data: d1, AggregationBits: bitfield.Bitlist{0b10110}, Signature: sig.Marshal()}, {Data: d1, AggregationBits: bitfield.Bitlist{0b10110}, Signature: sig.Marshal()},
{Data: d1, AggregationBits: bitfield.Bitlist{0b11100}, Signature: sig.Marshal()}, {Data: d1, AggregationBits: bitfield.Bitlist{0b11100}, Signature: sig.Marshal()},
{Data: d1, AggregationBits: bitfield.Bitlist{0b11000}, Signature: sig.Marshal()}, {Data: d1, AggregationBits: bitfield.Bitlist{0b11000}, Signature: sig.Marshal()},
} }
if err := s.aggregateAndSaveForkChoiceAtts(atts2); err != nil { require.NoError(t, s.aggregateAndSaveForkChoiceAtts(atts2))
t.Fatal(err)
}
att3 := []*ethpb.Attestation{ att3 := []*ethpb.Attestation{
{Data: d2, AggregationBits: bitfield.Bitlist{0b1100}, Signature: sig.Marshal()}, {Data: d2, AggregationBits: bitfield.Bitlist{0b1100}, Signature: sig.Marshal()},
} }
if err := s.aggregateAndSaveForkChoiceAtts(att3); err != nil { require.NoError(t, s.aggregateAndSaveForkChoiceAtts(att3))
t.Fatal(err)
}
wanted, err := attaggregation.Aggregate(atts1) wanted, err := attaggregation.Aggregate(atts1)
require.NoError(t, err) require.NoError(t, err)
@@ -265,23 +231,17 @@ func TestSeenAttestations_PresentInCache(t *testing.T) {
att1 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x13} /* 0b00010011 */} att1 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x13} /* 0b00010011 */}
got, err := s.seen(att1) got, err := s.seen(att1)
require.NoError(t, err) require.NoError(t, err)
if got { assert.Equal(t, false, got)
t.Error("Wanted false, got true")
}
att2 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x17} /* 0b00010111 */} att2 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x17} /* 0b00010111 */}
got, err = s.seen(att2) got, err = s.seen(att2)
require.NoError(t, err) require.NoError(t, err)
if got { assert.Equal(t, false, got)
t.Error("Wanted false, got true")
}
att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x17} /* 0b00010111 */} att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x17} /* 0b00010111 */}
got, err = s.seen(att3) got, err = s.seen(att3)
require.NoError(t, err) require.NoError(t, err)
if !got { assert.Equal(t, true, got)
t.Error("Wanted true, got false")
}
} }
func TestService_seen(t *testing.T) { func TestService_seen(t *testing.T) {

View File

@@ -28,23 +28,15 @@ func TestPruneExpired_Ticker(t *testing.T) {
{Data: &ethpb.AttestationData{Slot: 0}, AggregationBits: bitfield.Bitlist{0b1000, 0b1}}, {Data: &ethpb.AttestationData{Slot: 0}, AggregationBits: bitfield.Bitlist{0b1000, 0b1}},
{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1000, 0b1}}, {Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1000, 0b1}},
} }
if err := s.pool.SaveUnaggregatedAttestations(atts); err != nil { require.NoError(t, s.pool.SaveUnaggregatedAttestations(atts))
t.Fatal(err) require.Equal(t, 2, s.pool.UnaggregatedAttestationCount(), "Unexpected number of attestations")
}
if s.pool.UnaggregatedAttestationCount() != 2 {
t.Fatalf("Unexpected number of attestations: %d", s.pool.UnaggregatedAttestationCount())
}
atts = []*ethpb.Attestation{ atts = []*ethpb.Attestation{
{Data: &ethpb.AttestationData{Slot: 0}, AggregationBits: bitfield.Bitlist{0b1101, 0b1}}, {Data: &ethpb.AttestationData{Slot: 0}, AggregationBits: bitfield.Bitlist{0b1101, 0b1}},
{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1101, 0b1}}, {Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1101, 0b1}},
} }
if err := s.pool.SaveAggregatedAttestations(atts); err != nil { require.NoError(t, s.pool.SaveAggregatedAttestations(atts))
t.Fatal(err)
}
assert.Equal(t, 2, s.pool.AggregatedAttestationCount()) assert.Equal(t, 2, s.pool.AggregatedAttestationCount())
if err := s.pool.SaveBlockAttestations(atts); err != nil { require.NoError(t, s.pool.SaveBlockAttestations(atts))
t.Fatal(err)
}
// Rewind back one epoch worth of time. // Rewind back one epoch worth of time.
s.genesisTime = uint64(roughtime.Now().Unix()) - params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot s.genesisTime = uint64(roughtime.Now().Unix()) - params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot
@@ -92,12 +84,8 @@ func TestPruneExpired_PruneExpiredAtts(t *testing.T) {
att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1101}} att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1101}}
att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1110}} att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1110}}
atts := []*ethpb.Attestation{att1, att2, att3, att4} atts := []*ethpb.Attestation{att1, att2, att3, att4}
if err := s.pool.SaveAggregatedAttestations(atts); err != nil { require.NoError(t, s.pool.SaveAggregatedAttestations(atts))
t.Fatal(err) require.NoError(t, s.pool.SaveBlockAttestations(atts))
}
if err := s.pool.SaveBlockAttestations(atts); err != nil {
t.Fatal(err)
}
// Rewind back one epoch worth of time. // Rewind back one epoch worth of time.
s.genesisTime = uint64(roughtime.Now().Unix()) - params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot s.genesisTime = uint64(roughtime.Now().Unix()) - params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot
@@ -122,10 +110,6 @@ func TestPruneExpired_Expired(t *testing.T) {
// Rewind back one epoch worth of time. // Rewind back one epoch worth of time.
s.genesisTime = uint64(roughtime.Now().Unix()) - params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot s.genesisTime = uint64(roughtime.Now().Unix()) - params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot
if !s.expired(0) { assert.Equal(t, true, s.expired(0), "Should be expired")
t.Error("Should expired") assert.Equal(t, false, s.expired(1), "Should not be expired")
}
if s.expired(1) {
t.Error("Should not expired")
}
} }

View File

@@ -5,27 +5,19 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestStop_OK(t *testing.T) { func TestStop_OK(t *testing.T) {
s, err := NewService(context.Background(), &Config{}) s, err := NewService(context.Background(), &Config{})
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, s.Stop(), "Unable to stop attestation pool service")
if err := s.Stop(); err != nil { assert.ErrorContains(t, context.Canceled.Error(), s.ctx.Err(), "Context was not canceled")
t.Fatalf("Unable to stop attestation pool service: %v", err)
}
if s.ctx.Err() != context.Canceled {
t.Error("context was not canceled")
}
} }
func TestStatus_Error(t *testing.T) { func TestStatus_Error(t *testing.T) {
err := errors.New("bad bad bad") err := errors.New("bad bad bad")
s := &Service{err: err} s := &Service{err: err}
assert.ErrorContains(t, s.err.Error(), s.Status())
if err := s.Status(); err != s.err {
t.Errorf("Wanted: %v, got: %v", s.err, s.Status())
}
} }

View File

@@ -44,7 +44,6 @@ go_test(
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library", "//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
], ],
) )

View File

@@ -2,14 +2,12 @@ package slashings
import ( import (
"context" "context"
"reflect"
"testing" "testing"
"github.com/prysmaticlabs/prysm/beacon-chain/state" "github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/shared/bls" "github.com/prysmaticlabs/prysm/shared/bls"
"github.com/prysmaticlabs/prysm/shared/testutil/assert" "github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
@@ -90,35 +88,25 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
} }
slashings[i] = sl slashings[i] = sl
} }
if err := beaconState.SetSlot(helpers.StartSlot(1)); err != nil { require.NoError(t, beaconState.SetSlot(helpers.StartSlot(1)))
t.Fatal(err)
}
// We mark the following validators with some preconditions. // We mark the following validators with some preconditions.
exitedVal, err := beaconState.ValidatorAtIndex(uint64(2)) exitedVal, err := beaconState.ValidatorAtIndex(uint64(2))
require.NoError(t, err) require.NoError(t, err)
exitedVal.WithdrawableEpoch = 0 exitedVal.WithdrawableEpoch = 0
if err := beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal))
t.Fatal(err)
}
futureWithdrawVal, err := beaconState.ValidatorAtIndex(uint64(4)) futureWithdrawVal, err := beaconState.ValidatorAtIndex(uint64(4))
require.NoError(t, err) require.NoError(t, err)
futureWithdrawVal.WithdrawableEpoch = 17 futureWithdrawVal.WithdrawableEpoch = 17
if err := beaconState.UpdateValidatorAtIndex(uint64(4), futureWithdrawVal); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(4), futureWithdrawVal))
t.Fatal(err)
}
slashedVal, err := beaconState.ValidatorAtIndex(uint64(5)) slashedVal, err := beaconState.ValidatorAtIndex(uint64(5))
require.NoError(t, err) require.NoError(t, err)
slashedVal.Slashed = true slashedVal.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal))
t.Fatal(err)
}
slashedVal2, err := beaconState.ValidatorAtIndex(uint64(21)) slashedVal2, err := beaconState.ValidatorAtIndex(uint64(21))
require.NoError(t, err) require.NoError(t, err)
slashedVal2.Slashed = true slashedVal2.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(uint64(21), slashedVal2); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(21), slashedVal2))
t.Fatal(err)
}
aggSlashing1 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 0, 1, 2) aggSlashing1 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 0, 1, 2)
aggSlashing2 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 5, 9, 13) aggSlashing2 := validAttesterSlashingForValIdx(t, beaconState, privKeys, 5, 9, 13)
@@ -292,22 +280,17 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
var err error var err error
for i := 0; i < len(tt.args.slashings); i++ { for i := 0; i < len(tt.args.slashings); i++ {
err = p.InsertAttesterSlashing(context.Background(), beaconState, tt.args.slashings[i]) err = p.InsertAttesterSlashing(context.Background(), beaconState, tt.args.slashings[i])
if (err != nil) != tt.fields.wantErr[i] { if tt.fields.wantErr[i] {
t.Fatalf("Unexpected expect error at %d: %v", i, err) assert.NotNil(t, err)
} else {
assert.NoError(t, err)
} }
} }
assert.Equal(t, len(tt.want), len(p.pendingAttesterSlashing)) assert.Equal(t, len(tt.want), len(p.pendingAttesterSlashing))
for i := range p.pendingAttesterSlashing { for i := range p.pendingAttesterSlashing {
assert.Equal(t, tt.want[i].validatorToSlash, p.pendingAttesterSlashing[i].validatorToSlash) assert.Equal(t, tt.want[i].validatorToSlash, p.pendingAttesterSlashing[i].validatorToSlash)
if !proto.Equal(p.pendingAttesterSlashing[i].attesterSlashing, tt.want[i].attesterSlashing) { assert.DeepEqual(t, tt.want[i].attesterSlashing, p.pendingAttesterSlashing[i].attesterSlashing, "At index %d", i)
t.Errorf(
"Pending attester slashing at index %d does not match expected. Got=%v wanted=%v",
i,
p.pendingAttesterSlashing[i],
tt.want[i],
)
}
} }
}) })
} }
@@ -338,20 +321,9 @@ func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) {
p := &Pool{ p := &Pool{
pendingAttesterSlashing: make([]*PendingAttesterSlashing, 0), pendingAttesterSlashing: make([]*PendingAttesterSlashing, 0),
} }
if err := p.InsertAttesterSlashing( require.NoError(t, p.InsertAttesterSlashing(context.Background(), beaconState, slashings[0]))
context.Background(), err := p.InsertAttesterSlashing(context.Background(), beaconState, slashings[1])
beaconState, require.ErrorContains(t, "could not verify attester slashing", err, "Expected error when inserting slashing with bad sig")
slashings[0],
); err != nil {
t.Fatal(err)
}
if err := p.InsertAttesterSlashing(
context.Background(),
beaconState,
slashings[1],
); err == nil {
t.Error("Expected error when inserting slashing with bad sig, got nil")
}
assert.Equal(t, 1, len(p.pendingAttesterSlashing)) assert.Equal(t, 1, len(p.pendingAttesterSlashing))
} }
@@ -526,11 +498,7 @@ func TestPool_PendingAttesterSlashings(t *testing.T) {
p := &Pool{ p := &Pool{
pendingAttesterSlashing: tt.fields.pending, pendingAttesterSlashing: tt.fields.pending,
} }
if got := p.PendingAttesterSlashings( assert.DeepEqual(t, tt.want, p.PendingAttesterSlashings(context.Background(), beaconState))
context.Background(), beaconState,
); !reflect.DeepEqual(tt.want, got) {
t.Errorf("Unexpected return from PendingAttesterSlashings, wanted %v, received %v", tt.want, got)
}
}) })
} }
} }
@@ -547,21 +515,15 @@ func TestPool_PendingAttesterSlashings_Slashed(t *testing.T) {
val, err := beaconState.ValidatorAtIndex(0) val, err := beaconState.ValidatorAtIndex(0)
require.NoError(t, err) require.NoError(t, err)
val.Slashed = true val.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(0, val); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(0, val))
t.Fatal(err)
}
val, err = beaconState.ValidatorAtIndex(3) val, err = beaconState.ValidatorAtIndex(3)
require.NoError(t, err) require.NoError(t, err)
val.Slashed = true val.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(3, val); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(3, val))
t.Fatal(err)
}
val, err = beaconState.ValidatorAtIndex(5) val, err = beaconState.ValidatorAtIndex(5)
require.NoError(t, err) require.NoError(t, err)
val.Slashed = true val.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(5, val); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(5, val))
t.Fatal(err)
}
pendingSlashings := make([]*PendingAttesterSlashing, 20) pendingSlashings := make([]*PendingAttesterSlashing, 20)
slashings := make([]*ethpb.AttesterSlashing, 20) slashings := make([]*ethpb.AttesterSlashing, 20)
for i := 0; i < len(pendingSlashings); i++ { for i := 0; i < len(pendingSlashings); i++ {
@@ -596,9 +558,7 @@ func TestPool_PendingAttesterSlashings_Slashed(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
p := &Pool{pendingAttesterSlashing: tt.fields.pending} p := &Pool{pendingAttesterSlashing: tt.fields.pending}
if got := p.PendingAttesterSlashings(context.Background(), beaconState); !reflect.DeepEqual(tt.want, got) { assert.DeepEqual(t, tt.want, p.PendingAttesterSlashings(context.Background(), beaconState))
t.Errorf("Unexpected return from PendingAttesterSlashings, \nwanted %v, \nreceived %v", tt.want, got)
}
}) })
} }
} }
@@ -626,10 +586,5 @@ func TestPool_PendingAttesterSlashings_NoDuplicates(t *testing.T) {
p := &Pool{ p := &Pool{
pendingAttesterSlashing: pendingSlashings, pendingAttesterSlashing: pendingSlashings,
} }
want := slashings[0:2] assert.DeepEqual(t, slashings[0:2], p.PendingAttesterSlashings(context.Background(), beaconState))
if got := p.PendingAttesterSlashings(
context.Background(), beaconState,
); !reflect.DeepEqual(want, got) {
t.Errorf("Unexpected return from PendingAttesterSlashings, wanted %v, received %v", want, got)
}
} }

View File

@@ -2,11 +2,8 @@ package slashings
import ( import (
"context" "context"
"reflect"
"strings"
"testing" "testing"
"github.com/gogo/protobuf/proto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
@@ -28,10 +25,9 @@ func proposerSlashingForValIdx(valIdx uint64) *ethpb.ProposerSlashing {
func TestPool_InsertProposerSlashing(t *testing.T) { func TestPool_InsertProposerSlashing(t *testing.T) {
type fields struct { type fields struct {
wantErr bool wantedErr string
err string pending []*ethpb.ProposerSlashing
pending []*ethpb.ProposerSlashing included map[uint64]bool
included map[uint64]bool
} }
type args struct { type args struct {
slashings []*ethpb.ProposerSlashing slashings []*ethpb.ProposerSlashing
@@ -45,9 +41,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
slashings[i] = sl slashings[i] = sl
} }
if err := beaconState.SetSlot(helpers.StartSlot(1)); err != nil { require.NoError(t, beaconState.SetSlot(helpers.StartSlot(1)))
t.Fatal(err)
}
// We mark the following validators with some preconditions. // We mark the following validators with some preconditions.
exitedVal, err := beaconState.ValidatorAtIndex(uint64(2)) exitedVal, err := beaconState.ValidatorAtIndex(uint64(2))
@@ -59,15 +53,9 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
slashedVal, err := beaconState.ValidatorAtIndex(uint64(5)) slashedVal, err := beaconState.ValidatorAtIndex(uint64(5))
require.NoError(t, err) require.NoError(t, err)
slashedVal.Slashed = true slashedVal.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(2), exitedVal))
t.Fatal(err) require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(4), futureExitedVal))
} require.NoError(t, beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal))
if err := beaconState.UpdateValidatorAtIndex(uint64(4), futureExitedVal); err != nil {
t.Fatal(err)
}
if err := beaconState.UpdateValidatorAtIndex(uint64(5), slashedVal); err != nil {
t.Fatal(err)
}
tests := []struct { tests := []struct {
name string name string
@@ -89,10 +77,9 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
{ {
name: "Duplicate identical slashing", name: "Duplicate identical slashing",
fields: fields{ fields: fields{
pending: slashings[0:1], pending: slashings[0:1],
included: make(map[uint64]bool), included: make(map[uint64]bool),
wantErr: true, wantedErr: "slashing object already exists in pending proposer slashings",
err: "slashing object already exists in pending proposer slashings",
}, },
args: args{ args: args{
slashings: slashings[0:1], slashings: slashings[0:1],
@@ -102,10 +89,9 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
{ {
name: "Slashing for exited validator", name: "Slashing for exited validator",
fields: fields{ fields: fields{
pending: []*ethpb.ProposerSlashing{}, pending: []*ethpb.ProposerSlashing{},
included: make(map[uint64]bool), included: make(map[uint64]bool),
wantErr: true, wantedErr: "is not slashable",
err: "is not slashable",
}, },
args: args{ args: args{
slashings: slashings[2:3], slashings: slashings[2:3],
@@ -126,10 +112,9 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
{ {
name: "Slashing for slashed validator", name: "Slashing for slashed validator",
fields: fields{ fields: fields{
pending: []*ethpb.ProposerSlashing{}, pending: []*ethpb.ProposerSlashing{},
included: make(map[uint64]bool), included: make(map[uint64]bool),
wantErr: true, wantedErr: "not slashable",
err: "not slashable",
}, },
args: args{ args: args{
slashings: slashings[5:6], slashings: slashings[5:6],
@@ -143,8 +128,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
included: map[uint64]bool{ included: map[uint64]bool{
1: true, 1: true,
}, },
wantErr: true, wantedErr: "cannot be slashed",
err: "cannot be slashed",
}, },
args: args{ args: args{
slashings: slashings[1:2], slashings: slashings[1:2],
@@ -180,18 +164,15 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
for i := 0; i < len(tt.args.slashings); i++ { for i := 0; i < len(tt.args.slashings); i++ {
err = p.InsertProposerSlashing(context.Background(), beaconState, tt.args.slashings[i]) err = p.InsertProposerSlashing(context.Background(), beaconState, tt.args.slashings[i])
} }
if err != nil && tt.fields.wantErr && !strings.Contains(err.Error(), tt.fields.err) { if tt.fields.wantedErr != "" {
t.Fatalf("Wanted err: %v, received %v", tt.fields.err, err) require.ErrorContains(t, tt.fields.wantedErr, err)
} } else {
if !tt.fields.wantErr && err != nil { require.NoError(t, err)
t.Fatalf("Did not expect error: %v", err)
} }
assert.Equal(t, len(tt.want), len(p.pendingProposerSlashing)) assert.Equal(t, len(tt.want), len(p.pendingProposerSlashing))
for i := range p.pendingAttesterSlashing { for i := range p.pendingAttesterSlashing {
assert.Equal(t, p.pendingProposerSlashing[i].Header_1.Header.ProposerIndex, tt.want[i].Header_1.Header.ProposerIndex) assert.Equal(t, p.pendingProposerSlashing[i].Header_1.Header.ProposerIndex, tt.want[i].Header_1.Header.ProposerIndex)
if !proto.Equal(p.pendingProposerSlashing[i], tt.want[i]) { assert.DeepEqual(t, tt.want[i], p.pendingProposerSlashing[i], "Proposer slashing at index %d does not match expected", i)
t.Errorf("Proposer slashing at index %d does not match expected. Got=%v wanted=%v", i, p.pendingProposerSlashing[i], tt.want[i])
}
} }
}) })
} }
@@ -217,20 +198,9 @@ func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) {
pendingProposerSlashing: make([]*ethpb.ProposerSlashing, 0), pendingProposerSlashing: make([]*ethpb.ProposerSlashing, 0),
} }
// We only want a single slashing to remain. // We only want a single slashing to remain.
if err := p.InsertProposerSlashing( require.NoError(t, p.InsertProposerSlashing(context.Background(), beaconState, slashings[0]))
context.Background(), err := p.InsertProposerSlashing(context.Background(), beaconState, slashings[1])
beaconState, require.ErrorContains(t, "could not verify proposer slashing", err, "Expected slashing with bad signature to fail")
slashings[0],
); err != nil {
t.Fatal(err)
}
if err := p.InsertProposerSlashing(
context.Background(),
beaconState,
slashings[1],
); err == nil {
t.Error("Expected slashing with bad signature to fail, received nil")
}
assert.Equal(t, 1, len(p.pendingProposerSlashing)) assert.Equal(t, 1, len(p.pendingProposerSlashing))
} }
@@ -344,14 +314,7 @@ func TestPool_MarkIncludedProposerSlashing(t *testing.T) {
p.MarkIncludedProposerSlashing(tt.args.slashing) p.MarkIncludedProposerSlashing(tt.args.slashing)
assert.Equal(t, len(tt.want.pending), len(p.pendingProposerSlashing)) assert.Equal(t, len(tt.want.pending), len(p.pendingProposerSlashing))
for i := range p.pendingProposerSlashing { for i := range p.pendingProposerSlashing {
if !proto.Equal(p.pendingProposerSlashing[i], tt.want.pending[i]) { assert.DeepEqual(t, tt.want.pending[i], p.pendingProposerSlashing[i], "Unexpected pending proposer slashing at index %d", i)
t.Errorf(
"Pending proposer slashing at index %d does not match expected. Got=%v wanted=%v",
i,
p.pendingProposerSlashing[i],
tt.want.pending[i],
)
}
} }
assert.DeepEqual(t, tt.want.included, p.included) assert.DeepEqual(t, tt.want.included, p.included)
}) })
@@ -401,11 +364,7 @@ func TestPool_PendingProposerSlashings(t *testing.T) {
p := &Pool{ p := &Pool{
pendingProposerSlashing: tt.fields.pending, pendingProposerSlashing: tt.fields.pending,
} }
if got := p.PendingProposerSlashings( assert.DeepEqual(t, tt.want, p.PendingProposerSlashings(context.Background(), beaconState))
context.Background(), beaconState,
); !reflect.DeepEqual(tt.want, got) {
t.Errorf("Unexpected return from PendingProposerSlashings, wanted %v, received %v", tt.want, got)
}
}) })
} }
} }
@@ -418,15 +377,11 @@ func TestPool_PendingProposerSlashings_Slashed(t *testing.T) {
val, err := beaconState.ValidatorAtIndex(0) val, err := beaconState.ValidatorAtIndex(0)
require.NoError(t, err) require.NoError(t, err)
val.Slashed = true val.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(0, val); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(0, val))
t.Fatal(err)
}
val, err = beaconState.ValidatorAtIndex(5) val, err = beaconState.ValidatorAtIndex(5)
require.NoError(t, err) require.NoError(t, err)
val.Slashed = true val.Slashed = true
if err := beaconState.UpdateValidatorAtIndex(5, val); err != nil { require.NoError(t, beaconState.UpdateValidatorAtIndex(5, val))
t.Fatal(err)
}
slashings := make([]*ethpb.ProposerSlashing, 32) slashings := make([]*ethpb.ProposerSlashing, 32)
for i := 0; i < len(slashings); i++ { for i := 0; i < len(slashings); i++ {
sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], uint64(i)) sl, err := testutil.GenerateProposerSlashingForValidator(beaconState, privKeys[i], uint64(i))
@@ -453,12 +408,7 @@ func TestPool_PendingProposerSlashings_Slashed(t *testing.T) {
p := &Pool{ p := &Pool{
pendingProposerSlashing: tt.fields.pending, pendingProposerSlashing: tt.fields.pending,
} }
assert.DeepEqual(t, tt.want, p.PendingProposerSlashings(context.Background(), beaconState))
if got := p.PendingProposerSlashings(
context.Background(), beaconState,
); !reflect.DeepEqual(tt.want, got) {
t.Errorf("Unexpected return from PendingProposerSlashings, \nwanted %v, \nreceived %v", tt.want, got)
}
}) })
} }
} }

View File

@@ -20,9 +20,7 @@ func TestRelayAddrs_OnlyFactory(t *testing.T) {
assert.Equal(t, 2, len(result), "Unexpected number of addresses") assert.Equal(t, 2, len(result), "Unexpected number of addresses")
expected := "/ip4/127.0.0.1/tcp/6660/p2p/QmQ7zhY7nGY66yK1n8hLGevfVyjbtvHSgtZuXkCH9oTrgi/p2p-circuit/ip4/127.0.0.1/tcp/33201/p2p/QmaXZhW44pwQxBSeLkE5FNeLz8tGTTEsRciFg1DNWXXrWG" expected := "/ip4/127.0.0.1/tcp/6660/p2p/QmQ7zhY7nGY66yK1n8hLGevfVyjbtvHSgtZuXkCH9oTrgi/p2p-circuit/ip4/127.0.0.1/tcp/33201/p2p/QmaXZhW44pwQxBSeLkE5FNeLz8tGTTEsRciFg1DNWXXrWG"
if result[1].String() != expected { assert.Equal(t, expected, result[1].String(), "Address at index 1 (%s) is not the expected p2p-circuit address", result[1].String())
t.Errorf("Address at index 1 (%s) is not the expected p2p-circuit address", result[1].String())
}
} }
func TestRelayAddrs_UseNonRelayAddrs(t *testing.T) { func TestRelayAddrs_UseNonRelayAddrs(t *testing.T) {
@@ -37,9 +35,7 @@ func TestRelayAddrs_UseNonRelayAddrs(t *testing.T) {
addrs := make([]ma.Multiaddr, len(expected)) addrs := make([]ma.Multiaddr, len(expected))
for i, addr := range expected { for i, addr := range expected {
a, err := ma.NewMultiaddr(addr) a, err := ma.NewMultiaddr(addr)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
addrs[i] = a addrs[i] = a
} }

View File

@@ -32,9 +32,7 @@ func init() {
func createAddrAndPrivKey(t *testing.T) (net.IP, *ecdsa.PrivateKey) { func createAddrAndPrivKey(t *testing.T) (net.IP, *ecdsa.PrivateKey) {
ip, err := iputils.ExternalIPv4() ip, err := iputils.ExternalIPv4()
if err != nil { require.NoError(t, err, "Could not get ip")
t.Fatalf("Could not get ip: %v", err)
}
ipAddr := net.ParseIP(ip) ipAddr := net.ParseIP(ip)
temp := testutil.TempDir() temp := testutil.TempDir()
randNum := rand.Int() randNum := rand.Int()

View File

@@ -87,9 +87,7 @@ func TestStartDiscv5_DifferentForkDigests(t *testing.T) {
cfg.TCPPort = 14001 cfg.TCPPort = 14001
cfg.MaxPeers = 30 cfg.MaxPeers = 30
s, err = NewService(cfg) s, err = NewService(cfg)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
s.genesisTime = genesisTime s.genesisTime = genesisTime
s.genesisValidatorsRoot = make([]byte, 32) s.genesisValidatorsRoot = make([]byte, 32)
s.dv5Listener = lastListener s.dv5Listener = lastListener

View File

@@ -11,6 +11,7 @@ import (
"github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/crypto"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
@@ -18,9 +19,7 @@ func TestPrivateKeyLoading(t *testing.T) {
file, err := ioutil.TempFile(testutil.TempDir(), "key") file, err := ioutil.TempFile(testutil.TempDir(), "key")
require.NoError(t, err) require.NoError(t, err)
defer func() { defer func() {
if err := os.Remove(file.Name()); err != nil { assert.NoError(t, os.Remove(file.Name()))
t.Log(err)
}
}() }()
key, _, err := crypto.GenerateSecp256k1Key(rand.Reader) key, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
require.NoError(t, err, "Could not generate key") require.NoError(t, err, "Could not generate key")

View File

@@ -64,13 +64,9 @@ func createHost(t *testing.T, port int) (host.Host, *ecdsa.PrivateKey, net.IP) {
ipAddr, pkey := createAddrAndPrivKey(t) ipAddr, pkey := createAddrAndPrivKey(t)
ipAddr = net.ParseIP("127.0.0.1") ipAddr = net.ParseIP("127.0.0.1")
listen, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr, port)) listen, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr, port))
if err != nil { require.NoError(t, err, "Failed to p2p listen")
t.Fatalf("Failed to p2p listen: %v", err)
}
h, err := libp2p.New(context.Background(), []libp2p.Option{privKeyOption(pkey), libp2p.ListenAddrs(listen)}...) h, err := libp2p.New(context.Background(), []libp2p.Option{privKeyOption(pkey), libp2p.ListenAddrs(listen)}...)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
return h, pkey, ipAddr return h, pkey, ipAddr
} }

View File

@@ -179,9 +179,7 @@ func TestUnpackDepositLogData_OK(t *testing.T) {
testAcc.Backend.Commit() testAcc.Backend.Commit()
if err := web3Service.initDataFromContract(); err != nil { require.NoError(t, web3Service.initDataFromContract(), "Could not init from contract")
t.Fatalf("Could not init from contract: %v", err)
}
testutil.ResetCache() testutil.ResetCache()
deposits, _, err := testutil.DeterministicDepositsAndKeys(1) deposits, _, err := testutil.DeterministicDepositsAndKeys(1)
@@ -239,9 +237,7 @@ func TestProcessETH2GenesisLog_8DuplicatePubkeys(t *testing.T) {
params.OverrideBeaconConfig(bConfig) params.OverrideBeaconConfig(bConfig)
testAcc.Backend.Commit() testAcc.Backend.Commit()
if err := testAcc.Backend.AdjustTime(time.Duration(int64(time.Now().Nanosecond()))); err != nil { require.NoError(t, testAcc.Backend.AdjustTime(time.Duration(int64(time.Now().Nanosecond()))))
t.Fatal(err)
}
testutil.ResetCache() testutil.ResetCache()
deposits, _, err := testutil.DeterministicDepositsAndKeys(1) deposits, _, err := testutil.DeterministicDepositsAndKeys(1)
@@ -311,9 +307,7 @@ func TestProcessETH2GenesisLog(t *testing.T) {
params.OverrideBeaconConfig(bConfig) params.OverrideBeaconConfig(bConfig)
testAcc.Backend.Commit() testAcc.Backend.Commit()
if err := testAcc.Backend.AdjustTime(time.Duration(int64(time.Now().Nanosecond()))); err != nil { require.NoError(t, testAcc.Backend.AdjustTime(time.Duration(int64(time.Now().Nanosecond()))))
t.Fatal(err)
}
testutil.ResetCache() testutil.ResetCache()
deposits, _, err := testutil.DeterministicDepositsAndKeys(uint64(depositsReqForChainStart)) deposits, _, err := testutil.DeterministicDepositsAndKeys(uint64(depositsReqForChainStart))
@@ -498,9 +492,7 @@ func TestWeb3ServiceProcessDepositLog_RequestMissedDeposits(t *testing.T) {
params.OverrideBeaconConfig(bConfig) params.OverrideBeaconConfig(bConfig)
testAcc.Backend.Commit() testAcc.Backend.Commit()
if err := testAcc.Backend.AdjustTime(time.Duration(int64(time.Now().Nanosecond()))); err != nil { require.NoError(t, testAcc.Backend.AdjustTime(time.Duration(int64(time.Now().Nanosecond()))))
t.Fatal(err)
}
depositsWanted := 10 depositsWanted := 10
testutil.ResetCache() testutil.ResetCache()
deposits, _, err := testutil.DeterministicDepositsAndKeys(uint64(depositsWanted)) deposits, _, err := testutil.DeterministicDepositsAndKeys(uint64(depositsWanted))
@@ -543,9 +535,7 @@ func TestWeb3ServiceProcessDepositLog_RequestMissedDeposits(t *testing.T) {
genSt, err := state.EmptyGenesisState() genSt, err := state.EmptyGenesisState()
require.NoError(t, err) require.NoError(t, err)
web3Service.preGenesisState = genSt web3Service.preGenesisState = genSt
if err := web3Service.preGenesisState.SetEth1Data(&ethpb.Eth1Data{}); err != nil { require.NoError(t, web3Service.preGenesisState.SetEth1Data(&ethpb.Eth1Data{}))
t.Fatal(err)
}
web3Service.chainStartData.ChainstartDeposits = []*ethpb.Deposit{} web3Service.chainStartData.ChainstartDeposits = []*ethpb.Deposit{}
web3Service.depositTrie, err = trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth)) web3Service.depositTrie, err = trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth))
require.NoError(t, err) require.NoError(t, err)

View File

@@ -123,9 +123,7 @@ func TestServer_ListAttestations_Genesis(t *testing.T) {
}, },
}) })
require.NoError(t, err) require.NoError(t, err)
if !proto.Equal(wanted, res) { require.DeepEqual(t, wanted, res)
t.Errorf("Wanted %v, received %v", wanted, res)
}
// Should throw an error if there is more than 1 block // Should throw an error if there is more than 1 block
// for the genesis slot. // for the genesis slot.
@@ -870,12 +868,8 @@ func TestServer_StreamIndexedAttestations_ContextCanceled(t *testing.T) {
mockStream := mock.NewMockBeaconChain_StreamIndexedAttestationsServer(ctrl) mockStream := mock.NewMockBeaconChain_StreamIndexedAttestationsServer(ctrl)
mockStream.EXPECT().Context().Return(ctx).AnyTimes() mockStream.EXPECT().Context().Return(ctx).AnyTimes()
go func(tt *testing.T) { go func(tt *testing.T) {
if err := server.StreamIndexedAttestations( err := server.StreamIndexedAttestations(&ptypes.Empty{}, mockStream)
&ptypes.Empty{}, assert.ErrorContains(t, "Context canceled", err)
mockStream,
); err != nil && !strings.Contains(err.Error(), "Context canceled") {
tt.Errorf("Expected context canceled error got: %v", err)
}
<-exitRoutine <-exitRoutine
}(t) }(t)
cancel() cancel()

View File

@@ -584,9 +584,7 @@ func TestServer_StreamBlocks_OnHeadUpdated(t *testing.T) {
ctx := context.Background() ctx := context.Background()
beaconState, privs := testutil.DeterministicGenesisState(t, 32) beaconState, privs := testutil.DeterministicGenesisState(t, 32)
b, err := testutil.GenerateFullBlock(beaconState, privs, testutil.DefaultBlockGenConfig(), 1) b, err := testutil.GenerateFullBlock(beaconState, privs, testutil.DefaultBlockGenConfig(), 1)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
chainService := &chainMock.ChainService{State: beaconState} chainService := &chainMock.ChainService{State: beaconState}
server := &Server{ server := &Server{
Ctx: ctx, Ctx: ctx,

View File

@@ -40,9 +40,7 @@ func TestServer_GetValidatorActiveSetChanges_CannotRequestFutureEpoch(t *testing
db, _ := dbTest.SetupDB(t) db, _ := dbTest.SetupDB(t)
ctx := context.Background() ctx := context.Background()
st := testutil.NewBeaconState() st := testutil.NewBeaconState()
if err := st.SetSlot(0); err != nil { require.NoError(t, st.SetSlot(0))
t.Fatal(err)
}
bs := &Server{ bs := &Server{
GenesisTimeFetcher: &mock.ChainService{}, GenesisTimeFetcher: &mock.ChainService{},
HeadFetcher: &mock.ChainService{ HeadFetcher: &mock.ChainService{
@@ -198,8 +196,8 @@ func TestServer_ListValidatorBalances_PaginationOutOfRange(t *testing.T) {
req := &ethpb.ListValidatorBalancesRequest{PageToken: strconv.Itoa(1), PageSize: 100, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}} req := &ethpb.ListValidatorBalancesRequest{PageToken: strconv.Itoa(1), PageSize: 100, QueryFilter: &ethpb.ListValidatorBalancesRequest_Epoch{Epoch: 0}}
wanted := fmt.Sprintf("page start %d >= list %d", req.PageSize, len(st.Balances())) wanted := fmt.Sprintf("page start %d >= list %d", req.PageSize, len(st.Balances()))
if _, err := bs.ListValidatorBalances(context.Background(), req); err != nil && !strings.Contains(err.Error(), wanted) { if _, err := bs.ListValidatorBalances(context.Background(), req); err != nil {
t.Errorf("Expected error %v, received %v", wanted, err) assert.ErrorContains(t, wanted, err)
} }
} }
@@ -1013,10 +1011,9 @@ func TestServer_GetValidator(t *testing.T) {
} }
tests := []struct { tests := []struct {
req *ethpb.GetValidatorRequest req *ethpb.GetValidatorRequest
res *ethpb.Validator res *ethpb.Validator
wantErr bool wantedErr string
err string
}{ }{
{ {
req: &ethpb.GetValidatorRequest{ req: &ethpb.GetValidatorRequest{
@@ -1024,8 +1021,7 @@ func TestServer_GetValidator(t *testing.T) {
Index: 0, Index: 0,
}, },
}, },
res: validators[0], res: validators[0],
wantErr: false,
}, },
{ {
req: &ethpb.GetValidatorRequest{ req: &ethpb.GetValidatorRequest{
@@ -1033,8 +1029,7 @@ func TestServer_GetValidator(t *testing.T) {
Index: uint64(count - 1), Index: uint64(count - 1),
}, },
}, },
res: validators[count-1], res: validators[count-1],
wantErr: false,
}, },
{ {
req: &ethpb.GetValidatorRequest{ req: &ethpb.GetValidatorRequest{
@@ -1042,8 +1037,7 @@ func TestServer_GetValidator(t *testing.T) {
PublicKey: pubKey(5), PublicKey: pubKey(5),
}, },
}, },
res: validators[5], res: validators[5],
wantErr: false,
}, },
{ {
req: &ethpb.GetValidatorRequest{ req: &ethpb.GetValidatorRequest{
@@ -1051,9 +1045,8 @@ func TestServer_GetValidator(t *testing.T) {
PublicKey: []byte("bad-keyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), PublicKey: []byte("bad-keyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"),
}, },
}, },
res: nil, res: nil,
wantErr: true, wantedErr: "No validator matched filter criteria",
err: "No validator matched filter criteria",
}, },
{ {
req: &ethpb.GetValidatorRequest{ req: &ethpb.GetValidatorRequest{
@@ -1061,20 +1054,17 @@ func TestServer_GetValidator(t *testing.T) {
Index: uint64(len(validators)), Index: uint64(len(validators)),
}, },
}, },
res: nil, res: nil,
wantErr: true, wantedErr: fmt.Sprintf("there are only %d validators", len(validators)),
err: fmt.Sprintf("there are only %d validators", len(validators)),
}, },
} }
for _, test := range tests { for _, test := range tests {
res, err := bs.GetValidator(context.Background(), test.req) res, err := bs.GetValidator(context.Background(), test.req)
if test.wantErr && err != nil { if test.wantedErr != "" {
if !strings.Contains(err.Error(), test.err) { require.ErrorContains(t, test.wantedErr, err)
t.Fatalf("Wanted %v, received %v", test.err, err) } else {
} require.NoError(t, err)
} else if err != nil {
t.Fatal(err)
} }
assert.DeepEqual(t, test.res, res) assert.DeepEqual(t, test.res, res)
} }
@@ -1431,7 +1421,7 @@ func TestServer_GetValidatorParticipation_DoesntExist(t *testing.T) {
QueryFilter: &ethpb.GetValidatorParticipationRequest_Epoch{Epoch: 0}, QueryFilter: &ethpb.GetValidatorParticipationRequest_Epoch{Epoch: 0},
}) })
if err != nil && !strings.Contains(err.Error(), wanted) { if err != nil && !strings.Contains(err.Error(), wanted) {
t.Errorf("Expected error %v, received %v", wanted, err) assert.ErrorContains(t, wanted, err)
} }
} }

View File

@@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"strings"
"testing" "testing"
"time" "time"
@@ -72,8 +71,8 @@ func TestGetDuties_NextEpoch_CantFindValidatorIdx(t *testing.T) {
PublicKeys: [][]byte{pubKey}, PublicKeys: [][]byte{pubKey},
} }
want := fmt.Sprintf("validator %#x does not exist", req.PublicKeys[0]) want := fmt.Sprintf("validator %#x does not exist", req.PublicKeys[0])
if _, err := vs.GetDuties(ctx, req); err != nil && !strings.Contains(err.Error(), want) { if _, err := vs.GetDuties(ctx, req); err != nil {
t.Errorf("Expected %v, received %v", want, err) assert.ErrorContains(t, want, err)
} }
} }

View File

@@ -173,20 +173,16 @@ func TestGetBlock_AddsUnaggregatedAtts(t *testing.T) {
// Generate some more random attestations with a larger spread so that we can capture at least // Generate some more random attestations with a larger spread so that we can capture at least
// one unaggregated attestation. // one unaggregated attestation.
if atts, err := testutil.GenerateAttestations(beaconState, privKeys, 300, 1, true); err != nil { atts, err = testutil.GenerateAttestations(beaconState, privKeys, 300, 1, true)
t.Fatal(err) require.NoError(t, err)
} else { found := false
found := false for _, a := range atts {
for _, a := range atts { if !helpers.IsAggregated(a) {
if !helpers.IsAggregated(a) { found = true
found = true require.NoError(t, proposerServer.AttPool.SaveUnaggregatedAttestation(a))
require.NoError(t, proposerServer.AttPool.SaveUnaggregatedAttestation(a))
}
}
if !found {
t.Fatal("No unaggregated attestations were generated")
} }
} }
require.Equal(t, true, found, "No unaggregated attestations were generated")
randaoReveal, err := testutil.RandaoReveal(beaconState, 0, privKeys) randaoReveal, err := testutil.RandaoReveal(beaconState, 0, privKeys)
assert.NoError(t, err) assert.NoError(t, err)

View File

@@ -28,9 +28,7 @@ func TestValidatorStatus_DepositedEth1(t *testing.T) {
db, _ := dbutil.SetupDB(t) db, _ := dbutil.SetupDB(t)
ctx := context.Background() ctx := context.Background()
deposits, _, err := testutil.DeterministicDepositsAndKeys(1) deposits, _, err := testutil.DeterministicDepositsAndKeys(1)
if err != nil { require.NoError(t, err, "Could not generate deposits and keys")
t.Fatalf("Could not generate deposits and keys: %v", err)
}
deposit := deposits[0] deposit := deposits[0]
pubKey1 := deposit.Data.PublicKey pubKey1 := deposit.Data.PublicKey
depositTrie, err := trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth)) depositTrie, err := trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth))
@@ -940,9 +938,7 @@ func TestValidatorStatus_Invalid(t *testing.T) {
db, _ := dbutil.SetupDB(t) db, _ := dbutil.SetupDB(t)
ctx := context.Background() ctx := context.Background()
deposits, _, err := testutil.DeterministicDepositsAndKeys(1) deposits, _, err := testutil.DeterministicDepositsAndKeys(1)
if err != nil { require.NoError(t, err, "Could not generate deposits and keys")
t.Fatalf("Could not generate deposits and keys: %v", err)
}
deposit := deposits[0] deposit := deposits[0]
pubKey1 := deposit.Data.PublicKey pubKey1 := deposit.Data.PublicKey
deposit.Data.Signature = deposit.Data.Signature[1:] deposit.Data.Signature = deposit.Data.Signature[1:]

View File

@@ -35,27 +35,23 @@ func TestInitializeFromProto(t *testing.T) {
Slot: 4, Slot: 4,
Validators: nil, Validators: nil,
}, },
error: "",
}, },
{ {
name: "empty state", name: "empty state",
state: &pbp2p.BeaconState{}, state: &pbp2p.BeaconState{},
error: "",
}, },
{ {
name: "full state", name: "full state",
state: testState.InnerStateUnsafe(), state: testState.InnerStateUnsafe(),
error: "",
}, },
} }
for _, tt := range initTests { for _, tt := range initTests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
_, err := state.InitializeFromProto(tt.state) _, err := state.InitializeFromProto(tt.state)
if err != nil && err.Error() != tt.error { if tt.error != "" {
t.Errorf("Unexpected error, expected %v, recevied %v", tt.error, err) assert.ErrorContains(t, tt.error, err)
} } else {
if err == nil && tt.error != "" { assert.NoError(t, err)
t.Errorf("Expected error, expected %v, recevied %v", tt.error, err)
} }
}) })
} }
@@ -81,27 +77,23 @@ func TestInitializeFromProtoUnsafe(t *testing.T) {
Slot: 4, Slot: 4,
Validators: nil, Validators: nil,
}, },
error: "",
}, },
{ {
name: "empty state", name: "empty state",
state: &pbp2p.BeaconState{}, state: &pbp2p.BeaconState{},
error: "",
}, },
{ {
name: "full state", name: "full state",
state: testState.InnerStateUnsafe(), state: testState.InnerStateUnsafe(),
error: "",
}, },
} }
for _, tt := range initTests { for _, tt := range initTests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
_, err := state.InitializeFromProtoUnsafe(tt.state) _, err := state.InitializeFromProtoUnsafe(tt.state)
if err != nil && err.Error() != tt.error { if tt.error != "" {
t.Errorf("Unexpected error, expected %v, recevied %v", tt.error, err) assert.ErrorContains(t, tt.error, err)
} } else {
if err == nil && tt.error != "" { assert.NoError(t, err)
t.Errorf("Expected error, expected %v, recevied %v", tt.error, err)
} }
}) })
} }
@@ -255,13 +247,8 @@ func TestBeaconState_AppendValidator_DoesntMutateCopy(t *testing.T) {
originalCount := st1.NumValidators() originalCount := st1.NumValidators()
val := &eth.Validator{Slashed: true} val := &eth.Validator{Slashed: true}
if err := st0.AppendValidator(val); err != nil { assert.NoError(t, st0.AppendValidator(val))
t.Error(err) assert.Equal(t, originalCount, st1.NumValidators(), "st1 NumValidators mutated")
} _, ok := st1.ValidatorIndexByPubkey(bytesutil.ToBytes48(val.PublicKey))
if count := st1.NumValidators(); count != originalCount { assert.Equal(t, false, ok, "Expected no validator index to be present in st1 for the newly inserted pubkey")
t.Errorf("st1 NumValidators mutated. Wanted %d, got %d", originalCount, count)
}
if _, ok := st1.ValidatorIndexByPubkey(bytesutil.ToBytes48(val.PublicKey)); ok {
t.Error("Expected no validator index to be present in st1 for the newly inserted pubkey")
}
} }

View File

@@ -64,13 +64,7 @@ func TestLoadStateByRoot_CanGet(t *testing.T) {
require.NoError(t, service.beaconDB.SaveGenesisBlockRoot(ctx, blkRoot)) require.NoError(t, service.beaconDB.SaveGenesisBlockRoot(ctx, blkRoot))
require.NoError(t, service.beaconDB.SaveBlock(ctx, blk)) require.NoError(t, service.beaconDB.SaveBlock(ctx, blk))
require.NoError(t, service.beaconDB.SaveState(ctx, beaconState, blkRoot)) require.NoError(t, service.beaconDB.SaveState(ctx, beaconState, blkRoot))
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: blkRoot[:], Slot: 100}))
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Root: blkRoot[:],
Slot: 100,
}); err != nil {
t.Fatal(err)
}
loadedState, err := service.StateByRoot(ctx, blkRoot) loadedState, err := service.StateByRoot(ctx, blkRoot)
require.NoError(t, err) require.NoError(t, err)

View File

@@ -34,12 +34,7 @@ func TestStateByRoot_ColdState(t *testing.T) {
require.NoError(t, service.beaconDB.SaveBlock(ctx, b)) require.NoError(t, service.beaconDB.SaveBlock(ctx, b))
require.NoError(t, service.beaconDB.SaveGenesisBlockRoot(ctx, bRoot)) require.NoError(t, service.beaconDB.SaveGenesisBlockRoot(ctx, bRoot))
r := [32]byte{'a'} r := [32]byte{'a'}
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{ require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: r[:], Slot: 1}))
Root: r[:],
Slot: 1,
}); err != nil {
t.Fatal(err)
}
loadedState, err := service.StateByRoot(ctx, r) loadedState, err := service.StateByRoot(ctx, r)
require.NoError(t, err) require.NoError(t, err)
if !proto.Equal(loadedState.InnerStateUnsafe(), beaconState.InnerStateUnsafe()) { if !proto.Equal(loadedState.InnerStateUnsafe(), beaconState.InnerStateUnsafe()) {
@@ -81,12 +76,7 @@ func TestStateByRoot_HotStateUsingEpochBoundaryCacheWithReplay(t *testing.T) {
require.NoError(t, service.beaconDB.SaveBlock(ctx, targetBlock)) require.NoError(t, service.beaconDB.SaveBlock(ctx, targetBlock))
targetRoot, err := stateutil.BlockRoot(targetBlock.Block) targetRoot, err := stateutil.BlockRoot(targetBlock.Block)
require.NoError(t, err) require.NoError(t, err)
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{ require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: targetSlot, Root: targetRoot[:]}))
Slot: targetSlot,
Root: targetRoot[:],
}); err != nil {
t.Fatal(err)
}
loadedState, err := service.StateByRoot(ctx, targetRoot) loadedState, err := service.StateByRoot(ctx, targetRoot)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, targetSlot, loadedState.Slot(), "Did not correctly load state") assert.Equal(t, targetSlot, loadedState.Slot(), "Did not correctly load state")
@@ -164,12 +154,7 @@ func TestStateByRootInitialSync_CanProcessUpTo(t *testing.T) {
targetRoot, err := stateutil.BlockRoot(targetBlk.Block) targetRoot, err := stateutil.BlockRoot(targetBlk.Block)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, service.beaconDB.SaveBlock(ctx, targetBlk)) require.NoError(t, service.beaconDB.SaveBlock(ctx, targetBlk))
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{ require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: targetSlot, Root: targetRoot[:]}))
Slot: targetSlot,
Root: targetRoot[:],
}); err != nil {
t.Fatal(err)
}
loadedState, err := service.StateByRootInitialSync(ctx, targetRoot) loadedState, err := service.StateByRootInitialSync(ctx, targetRoot)
require.NoError(t, err) require.NoError(t, err)
@@ -194,12 +179,7 @@ func TestStateBySlot_ColdState(t *testing.T) {
require.NoError(t, db.SaveGenesisBlockRoot(ctx, bRoot)) require.NoError(t, db.SaveGenesisBlockRoot(ctx, bRoot))
r := [32]byte{} r := [32]byte{}
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{ require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: service.slotsPerArchivedPoint, Root: r[:]}))
Slot: service.slotsPerArchivedPoint,
Root: r[:],
}); err != nil {
t.Fatal(err)
}
slot := uint64(20) slot := uint64(20)
loadedState, err := service.StateBySlot(ctx, slot) loadedState, err := service.StateBySlot(ctx, slot)

View File

@@ -112,12 +112,7 @@ func TestLoadHoteStateByRoot_EpochBoundaryStateCanProcess(t *testing.T) {
require.NoError(t, service.beaconDB.SaveBlock(ctx, blk)) require.NoError(t, service.beaconDB.SaveBlock(ctx, blk))
blkRoot, err := stateutil.BlockRoot(blk.Block) blkRoot, err := stateutil.BlockRoot(blk.Block)
require.NoError(t, err) require.NoError(t, err)
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{ require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: 10, Root: blkRoot[:]}))
Slot: 10,
Root: blkRoot[:],
}); err != nil {
t.Fatal(err)
}
// This tests where hot state was not cached and needs processing. // This tests where hot state was not cached and needs processing.
loadedState, err := service.loadHotStateByRoot(ctx, blkRoot) loadedState, err := service.loadHotStateByRoot(ctx, blkRoot)
@@ -136,12 +131,7 @@ func TestLoadHoteStateByRoot_FromDBBoundaryCase(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, service.epochBoundaryStateCache.put(blkRoot, beaconState)) require.NoError(t, service.epochBoundaryStateCache.put(blkRoot, beaconState))
targetSlot := uint64(0) targetSlot := uint64(0)
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{ require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: targetSlot, Root: blkRoot[:]}))
Slot: targetSlot,
Root: blkRoot[:],
}); err != nil {
t.Fatal(err)
}
// This tests where hot state was not cached but doesn't need processing // This tests where hot state was not cached but doesn't need processing
// because it on the epoch boundary slot. // because it on the epoch boundary slot.

View File

@@ -75,12 +75,7 @@ func TestMigrateToCold_RegeneratePath(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, service.beaconDB.SaveBlock(ctx, blk)) require.NoError(t, service.beaconDB.SaveBlock(ctx, blk))
require.NoError(t, service.beaconDB.SaveGenesisBlockRoot(ctx, fRoot)) require.NoError(t, service.beaconDB.SaveGenesisBlockRoot(ctx, fRoot))
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{ require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: 1, Root: fRoot[:]}))
Slot: 1,
Root: fRoot[:],
}); err != nil {
t.Fatal(err)
}
service.finalizedInfo = &finalizedInfo{ service.finalizedInfo = &finalizedInfo{
slot: 1, slot: 1,
root: fRoot, root: fRoot,

View File

@@ -83,25 +83,15 @@ func TestState_ForceCheckpoint_SavesStateToDatabase(t *testing.T) {
svc := New(db, ssc) svc := New(db, ssc)
beaconState, _ := testutil.DeterministicGenesisState(t, 32) beaconState, _ := testutil.DeterministicGenesisState(t, 32)
if err := beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch); err != nil { require.NoError(t, beaconState.SetSlot(params.BeaconConfig().SlotsPerEpoch))
t.Fatal(err)
}
r := [32]byte{'a'} r := [32]byte{'a'}
svc.hotStateCache.Put(r, beaconState) svc.hotStateCache.Put(r, beaconState)
if db.HasState(ctx, r) { require.Equal(t, false, db.HasState(ctx, r), "Database has state stored already")
t.Fatal("Database has state stored already") assert.NoError(t, svc.ForceCheckpoint(ctx, r[:]))
} assert.Equal(t, true, db.HasState(ctx, r), "Did not save checkpoint to database")
if err := svc.ForceCheckpoint(ctx, r[:]); err != nil {
t.Error(err)
}
if !db.HasState(ctx, r) {
t.Error("Did not save checkpoint to database")
}
// Should not panic with genesis finalized root. // Should not panic with genesis finalized root.
if err := svc.ForceCheckpoint(ctx, params.BeaconConfig().ZeroHash[:]); err != nil { assert.NoError(t, svc.ForceCheckpoint(ctx, params.BeaconConfig().ZeroHash[:]))
t.Error(err)
}
} }

View File

@@ -19,9 +19,8 @@ func TestRegularSync_generateErrorResponse(t *testing.T) {
buf := bytes.NewBuffer(data) buf := bytes.NewBuffer(data)
b := make([]byte, 1) b := make([]byte, 1)
if _, err := buf.Read(b); err != nil { _, err = buf.Read(b)
t.Fatal(err) require.NoError(t, err)
}
assert.Equal(t, responseCodeServerError, b[0], "The first byte was not the status code") assert.Equal(t, responseCodeServerError, b[0], "The first byte was not the status code")
msg := &pb.ErrorResponse{} msg := &pb.ErrorResponse{}
require.NoError(t, r.p2p.Encoding().DecodeWithMaxLength(buf, msg)) require.NoError(t, r.p2p.Encoding().DecodeWithMaxLength(buf, msg))

View File

@@ -581,12 +581,10 @@ func TestBlocksFetcher_selectFailOverPeer(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
got, err := fetcher.selectFailOverPeer(tt.args.excludedPID, tt.args.peers) got, err := fetcher.selectFailOverPeer(tt.args.excludedPID, tt.args.peers)
if err != nil && err != tt.wantErr { if tt.wantErr != nil {
t.Errorf("selectFailOverPeer() error = %v, wantErr %v", err, tt.wantErr) assert.ErrorContains(t, tt.wantErr.Error(), err)
return } else {
} assert.Equal(t, tt.want, got)
if got != tt.want {
t.Errorf("selectFailOverPeer() got = %v, want %v", got, tt.want)
} }
}) })
} }
@@ -995,8 +993,8 @@ func TestBlocksFetcher_RequestBlocksRateLimitingLocks(t *testing.T) {
}) })
} }
_, err := fetcher.requestBlocks(ctx, req, p2.PeerID()) _, err := fetcher.requestBlocks(ctx, req, p2.PeerID())
if err != nil && err != errFetcherCtxIsDone { if err != nil {
t.Error(err) assert.ErrorContains(t, errFetcherCtxIsDone.Error(), err)
} }
} }
}() }()

View File

@@ -170,9 +170,7 @@ func connectPeer(t *testing.T, host *p2pt.TestP2P, datum *peerData, peerStatus *
p := p2pt.NewTestP2P(t) p := p2pt.NewTestP2P(t)
p.SetStreamHandler(topic, func(stream network.Stream) { p.SetStreamHandler(topic, func(stream network.Stream) {
defer func() { defer func() {
if err := stream.Close(); err != nil { assert.NoError(t, stream.Close())
t.Log(err)
}
}() }()
req := &p2ppb.BeaconBlocksByRangeRequest{} req := &p2ppb.BeaconBlocksByRangeRequest{}
@@ -182,12 +180,10 @@ func connectPeer(t *testing.T, host *p2pt.TestP2P, datum *peerData, peerStatus *
// Expected failure range // Expected failure range
if len(sliceutil.IntersectionUint64(datum.failureSlots, requestedBlocks)) > 0 { if len(sliceutil.IntersectionUint64(datum.failureSlots, requestedBlocks)) > 0 {
if _, err := stream.Write([]byte{0x01}); err != nil { _, err := stream.Write([]byte{0x01})
t.Error(err) assert.NoError(t, err)
} _, err = p.Encoding().EncodeWithMaxLength(stream, "bad")
if _, err := p.Encoding().EncodeWithMaxLength(stream, "bad"); err != nil { assert.NoError(t, err)
t.Error(err)
}
return return
} }

View File

@@ -54,10 +54,10 @@ func TestService_beaconBlockSubscriber(t *testing.T) {
msg proto.Message msg proto.Message
} }
tests := []struct { tests := []struct {
name string name string
args args args args
wantErr bool wantedErr string
check func(*testing.T, *Service) check func(*testing.T, *Service)
}{ }{
{ {
name: "invalid block does not remove attestations", name: "invalid block does not remove attestations",
@@ -69,7 +69,7 @@ func TestService_beaconBlockSubscriber(t *testing.T) {
}, },
}, },
}, },
wantErr: true, wantedErr: "nil inner state",
check: func(t *testing.T, s *Service) { check: func(t *testing.T, s *Service) {
if s.attPool.AggregatedAttestationCount() == 0 { if s.attPool.AggregatedAttestationCount() == 0 {
t.Error("Expected at least 1 aggregated attestation in the pool") t.Error("Expected at least 1 aggregated attestation in the pool")
@@ -99,10 +99,12 @@ func TestService_beaconBlockSubscriber(t *testing.T) {
} }
} }
// Perform method under test call. // Perform method under test call.
if err := s.beaconBlockSubscriber(context.Background(), tt.args.msg); (err != nil) != tt.wantErr { err := s.beaconBlockSubscriber(context.Background(), tt.args.msg)
t.Errorf("beaconBlockSubscriber(ctx, msg) error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
} }
// Perform any test check.
if tt.check != nil { if tt.check != nil {
tt.check(t, s) tt.check(t, s)
} }

View File

@@ -35,6 +35,8 @@ go_test(
deps = [ deps = [
"//shared/interop:go_default_library", "//shared/interop:go_default_library",
"//shared/params:go_default_library", "//shared/params:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"//shared/trieutil:go_default_library", "//shared/trieutil:go_default_library",
"@com_github_ethereum_go_ethereum//:go_default_library", "@com_github_ethereum_go_ethereum//:go_default_library",
"@com_github_ethereum_go_ethereum//accounts/abi/bind:go_default_library", "@com_github_ethereum_go_ethereum//accounts/abi/bind:go_default_library",

View File

@@ -3,7 +3,6 @@ package depositcontract_test
import ( import (
"context" "context"
"encoding/binary" "encoding/binary"
"log"
"math/big" "math/big"
"testing" "testing"
@@ -11,76 +10,56 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
depositcontract "github.com/prysmaticlabs/prysm/contracts/deposit-contract" depositcontract "github.com/prysmaticlabs/prysm/contracts/deposit-contract"
"github.com/prysmaticlabs/prysm/shared/interop" "github.com/prysmaticlabs/prysm/shared/interop"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestSetupRegistrationContract_OK(t *testing.T) { func TestSetupRegistrationContract_OK(t *testing.T) {
_, err := depositcontract.Setup() _, err := depositcontract.Setup()
if err != nil { assert.NoError(t, err, "Can not deploy validator registration contract")
log.Fatalf("Can not deploy validator registration contract: %v", err)
}
} }
// negative test case, deposit with less than 1 ETH which is less than the top off amount. // negative test case, deposit with less than 1 ETH which is less than the top off amount.
func TestRegister_Below1ETH(t *testing.T) { func TestRegister_Below1ETH(t *testing.T) {
testAccount, err := depositcontract.Setup() testAccount, err := depositcontract.Setup()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
// Generate deposit data // Generate deposit data
privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 1) privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 1)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys) depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
var depositDataRoot [32]byte var depositDataRoot [32]byte
copy(depositDataRoot[:], depositDataRoots[0]) copy(depositDataRoot[:], depositDataRoots[0])
testAccount.TxOpts.Value = depositcontract.LessThan1Eth() testAccount.TxOpts.Value = depositcontract.LessThan1Eth()
_, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot) _, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot)
if err == nil { assert.ErrorContains(t, "execution reverted", err, "Validator registration should have failed with insufficient deposit")
t.Error("Validator registration should have failed with insufficient deposit")
}
} }
// normal test case, test depositing 32 ETH and verify HashChainValue event is correctly emitted. // normal test case, test depositing 32 ETH and verify HashChainValue event is correctly emitted.
func TestValidatorRegister_OK(t *testing.T) { func TestValidatorRegister_OK(t *testing.T) {
testAccount, err := depositcontract.Setup() testAccount, err := depositcontract.Setup()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
testAccount.TxOpts.Value = depositcontract.Amount32Eth() testAccount.TxOpts.Value = depositcontract.Amount32Eth()
// Generate deposit data // Generate deposit data
privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 1) privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 1)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys) depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
var depositDataRoot [32]byte var depositDataRoot [32]byte
copy(depositDataRoot[:], depositDataRoots[0]) copy(depositDataRoot[:], depositDataRoots[0])
_, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot) _, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot)
testAccount.Backend.Commit() testAccount.Backend.Commit()
if err != nil { require.NoError(t, err, "Validator registration failed")
t.Errorf("Validator registration failed: %v", err)
}
_, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot) _, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot)
testAccount.Backend.Commit() testAccount.Backend.Commit()
if err != nil { assert.NoError(t, err, "Validator registration failed")
t.Errorf("Validator registration failed: %v", err)
}
_, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot) _, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot)
testAccount.Backend.Commit() testAccount.Backend.Commit()
if err != nil { assert.NoError(t, err, "Validator registration failed")
t.Errorf("Validator registration failed: %v", err)
}
query := ethereum.FilterQuery{ query := ethereum.FilterQuery{
Addresses: []common.Address{ Addresses: []common.Address{
@@ -89,81 +68,52 @@ func TestValidatorRegister_OK(t *testing.T) {
} }
logs, err := testAccount.Backend.FilterLogs(context.Background(), query) logs, err := testAccount.Backend.FilterLogs(context.Background(), query)
if err != nil { assert.NoError(t, err, "Unable to get logs of deposit contract")
t.Fatalf("Unable to get logs of deposit contract: %v", err)
}
merkleTreeIndex := make([]uint64, 5) merkleTreeIndex := make([]uint64, 5)
for i, log := range logs { for i, log := range logs {
_, _, _, _, idx, err := depositcontract.UnpackDepositLogData(log.Data) _, _, _, _, idx, err := depositcontract.UnpackDepositLogData(log.Data)
if err != nil { require.NoError(t, err, "Unable to unpack log data")
t.Fatalf("Unable to unpack log data: %v", err)
}
merkleTreeIndex[i] = binary.LittleEndian.Uint64(idx[:]) merkleTreeIndex[i] = binary.LittleEndian.Uint64(idx[:])
} }
if merkleTreeIndex[0] != 0 { assert.Equal(t, uint64(0), merkleTreeIndex[0], "Deposit event total desposit count miss matched")
t.Errorf("Deposit event total desposit count miss matched. Want: %d, Got: %d", 1, merkleTreeIndex[0]) assert.Equal(t, uint64(1), merkleTreeIndex[1], "Deposit event total desposit count miss matched")
} assert.Equal(t, uint64(2), merkleTreeIndex[2], "Deposit event total desposit count miss matched")
if merkleTreeIndex[1] != 1 {
t.Errorf("Deposit event total desposit count miss matched. Want: %d, Got: %d", 2, merkleTreeIndex[1])
}
if merkleTreeIndex[2] != 2 {
t.Errorf("Deposit event total desposit count miss matched. Want: %v, Got: %v", 3, merkleTreeIndex[2])
}
} }
func TestDrain(t *testing.T) { func TestDrain(t *testing.T) {
testAccount, err := depositcontract.Setup() testAccount, err := depositcontract.Setup()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
testAccount.TxOpts.Value = depositcontract.Amount32Eth() testAccount.TxOpts.Value = depositcontract.Amount32Eth()
// Generate deposit data // Generate deposit data
privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 1) privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 1)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys) depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
var depositDataRoot [32]byte var depositDataRoot [32]byte
copy(depositDataRoot[:], depositDataRoots[0]) copy(depositDataRoot[:], depositDataRoots[0])
_, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot) _, err = testAccount.Contract.Deposit(testAccount.TxOpts, pubKeys[0].Marshal(), depositDataItems[0].WithdrawalCredentials, depositDataItems[0].Signature, depositDataRoot)
testAccount.Backend.Commit() testAccount.Backend.Commit()
if err != nil { require.NoError(t, err, "Validator registration failed")
t.Errorf("Validator registration failed: %v", err)
}
testAccount.Backend.Commit() testAccount.Backend.Commit()
ctx := context.Background() ctx := context.Background()
bal, err := testAccount.Backend.BalanceAt(ctx, testAccount.ContractAddr, nil) bal, err := testAccount.Backend.BalanceAt(ctx, testAccount.ContractAddr, nil)
if err != nil { require.NoError(t, err)
t.Fatal(err) require.Equal(t, 0, bal.Cmp(depositcontract.Amount32Eth()), "Deposit did not work")
}
if bal.Cmp(depositcontract.Amount32Eth()) != 0 {
t.Fatal("deposit didnt work")
}
testAccount.TxOpts.Value = big.NewInt(0) testAccount.TxOpts.Value = big.NewInt(0)
if _, err := testAccount.Contract.Drain(testAccount.TxOpts); err != nil { _, err = testAccount.Contract.Drain(testAccount.TxOpts)
t.Fatal(err) require.NoError(t, err)
}
testAccount.Backend.Commit() testAccount.Backend.Commit()
bal, err = testAccount.Backend.BalanceAt(ctx, testAccount.ContractAddr, nil) bal, err = testAccount.Backend.BalanceAt(ctx, testAccount.ContractAddr, nil)
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, 0, big.NewInt(0).Cmp(bal), "Drain did not drain balance")
}
if big.NewInt(0).Cmp(bal) != 0 {
t.Errorf("Drain did not drain balance: %v", bal)
}
} }

View File

@@ -9,37 +9,27 @@ import (
depositcontract "github.com/prysmaticlabs/prysm/contracts/deposit-contract" depositcontract "github.com/prysmaticlabs/prysm/contracts/deposit-contract"
"github.com/prysmaticlabs/prysm/shared/interop" "github.com/prysmaticlabs/prysm/shared/interop"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/shared/trieutil" "github.com/prysmaticlabs/prysm/shared/trieutil"
) )
func TestDepositTrieRoot_OK(t *testing.T) { func TestDepositTrieRoot_OK(t *testing.T) {
testAcc, err := depositcontract.Setup() testAcc, err := depositcontract.Setup()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
localTrie, err := trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth)) localTrie, err := trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
depRoot, err := testAcc.Contract.GetDepositRoot(&bind.CallOpts{}) depRoot, err := testAcc.Contract.GetDepositRoot(&bind.CallOpts{})
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
if depRoot != localTrie.HashTreeRoot() { assert.Equal(t, depRoot, localTrie.HashTreeRoot(), "Local deposit trie root and contract deposit trie root are not equal")
t.Errorf("Local deposit trie root and contract deposit trie root are not equal. Expected %#x , Got %#x", depRoot, localTrie.Root())
}
privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 101) privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 101)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys) depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
testAcc.TxOpts.Value = depositcontract.Amount32Eth() testAcc.TxOpts.Value = depositcontract.Amount32Eth()
@@ -48,55 +38,36 @@ func TestDepositTrieRoot_OK(t *testing.T) {
dataRoot := [32]byte{} dataRoot := [32]byte{}
copy(dataRoot[:], depositDataRoots[i]) copy(dataRoot[:], depositDataRoots[i])
if _, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot); err != nil { _, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot)
t.Fatalf("Could not deposit to deposit contract %v", err) require.NoError(t, err, "Could not deposit to deposit contract")
}
testAcc.Backend.Commit() testAcc.Backend.Commit()
item, err := ssz.HashTreeRoot(data) item, err := ssz.HashTreeRoot(data)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
localTrie.Insert(item[:], i) localTrie.Insert(item[:], i)
depRoot, err = testAcc.Contract.GetDepositRoot(&bind.CallOpts{}) depRoot, err = testAcc.Contract.GetDepositRoot(&bind.CallOpts{})
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, depRoot, localTrie.HashTreeRoot(), "Local deposit trie root and contract deposit trie root are not equal for index %d", i)
}
if depRoot != localTrie.HashTreeRoot() {
t.Errorf("Local deposit trie root and contract deposit trie root are not equal for index %d. Expected %#x , Got %#x", i, depRoot, localTrie.Root())
}
} }
} }
func TestDepositTrieRoot_Fail(t *testing.T) { func TestDepositTrieRoot_Fail(t *testing.T) {
testAcc, err := depositcontract.Setup() testAcc, err := depositcontract.Setup()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
localTrie, err := trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth)) localTrie, err := trieutil.NewTrie(int(params.BeaconConfig().DepositContractTreeDepth))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
depRoot, err := testAcc.Contract.GetDepositRoot(&bind.CallOpts{}) depRoot, err := testAcc.Contract.GetDepositRoot(&bind.CallOpts{})
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
if depRoot != localTrie.HashTreeRoot() { assert.Equal(t, depRoot, localTrie.HashTreeRoot(), "Local deposit trie root and contract deposit trie root are not equal")
t.Errorf("Local deposit trie root and contract deposit trie root are not equal. Expected %#x , Got %#x", depRoot, localTrie.Root())
}
privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 101) privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0 /*startIndex*/, 101)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys) depositDataItems, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
testAcc.TxOpts.Value = depositcontract.Amount32Eth() testAcc.TxOpts.Value = depositcontract.Amount32Eth()
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
@@ -104,28 +75,21 @@ func TestDepositTrieRoot_Fail(t *testing.T) {
dataRoot := [32]byte{} dataRoot := [32]byte{}
copy(dataRoot[:], depositDataRoots[i]) copy(dataRoot[:], depositDataRoots[i])
if _, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot); err != nil { _, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot)
t.Fatalf("Could not deposit to deposit contract %v", err) require.NoError(t, err, "Could not deposit to deposit contract")
}
// Change an element in the data when storing locally // Change an element in the data when storing locally
copy(data.PublicKey, strconv.Itoa(i+10)) copy(data.PublicKey, strconv.Itoa(i+10))
testAcc.Backend.Commit() testAcc.Backend.Commit()
item, err := ssz.HashTreeRoot(data) item, err := ssz.HashTreeRoot(data)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
localTrie.Insert(item[:], i) localTrie.Insert(item[:], i)
depRoot, err = testAcc.Contract.GetDepositRoot(&bind.CallOpts{}) depRoot, err = testAcc.Contract.GetDepositRoot(&bind.CallOpts{})
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
if depRoot == localTrie.HashTreeRoot() { assert.NotEqual(t, depRoot, localTrie.HashTreeRoot(), "Local deposit trie root and contract deposit trie root are equal for index %d", i)
t.Errorf("Local deposit trie root and contract deposit trie root are equal for index %d when they were expected to be not equal", i)
}
} }
} }

View File

@@ -39,5 +39,7 @@ go_test(
"@com_github_gogo_protobuf//types:go_default_library", "@com_github_gogo_protobuf//types:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library", "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
"@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
], ],
) )

View File

@@ -22,6 +22,8 @@ import (
"github.com/prysmaticlabs/prysm/endtoend/types" "github.com/prysmaticlabs/prysm/endtoend/types"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/slotutil" "github.com/prysmaticlabs/prysm/shared/slotutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"google.golang.org/grpc" "google.golang.org/grpc"
) )
@@ -46,9 +48,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
if config.UsePprof { if config.UsePprof {
defer func() { defer func() {
for i := 0; i < e2e.TestParams.BeaconNodeCount; i++ { for i := 0; i < e2e.TestParams.BeaconNodeCount; i++ {
if err := helpers.WritePprofFiles(e2e.TestParams.LogPath, i); err != nil { assert.NoError(t, helpers.WritePprofFiles(e2e.TestParams.LogPath, i))
t.Error(err)
}
} }
}() }()
} }
@@ -56,13 +56,9 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
// Sleep depending on the count of validators, as generating the genesis state could take some time. // Sleep depending on the count of validators, as generating the genesis state could take some time.
time.Sleep(time.Duration(params.BeaconConfig().GenesisDelay) * time.Second) time.Sleep(time.Duration(params.BeaconConfig().GenesisDelay) * time.Second)
beaconLogFile, err := os.Open(path.Join(e2e.TestParams.LogPath, fmt.Sprintf(e2e.BeaconNodeLogFileName, 0))) beaconLogFile, err := os.Open(path.Join(e2e.TestParams.LogPath, fmt.Sprintf(e2e.BeaconNodeLogFileName, 0)))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
t.Run("chain started", func(t *testing.T) { t.Run("chain started", func(t *testing.T) {
if err := helpers.WaitForTextInFile(beaconLogFile, "Chain started within the last epoch"); err != nil { require.NoError(t, helpers.WaitForTextInFile(beaconLogFile, "Chain started within the last epoch"), "Chain did not start")
t.Fatalf("failed to find chain start in logs, this means the chain did not start: %v", err)
}
}) })
// Failing early in case chain doesn't start. // Failing early in case chain doesn't start.
@@ -81,9 +77,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
conns := make([]*grpc.ClientConn, e2e.TestParams.BeaconNodeCount) conns := make([]*grpc.ClientConn, e2e.TestParams.BeaconNodeCount)
for i := 0; i < len(conns); i++ { for i := 0; i < len(conns); i++ {
conn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", e2e.TestParams.BeaconNodeRPCPort+i), grpc.WithInsecure()) conn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", e2e.TestParams.BeaconNodeRPCPort+i), grpc.WithInsecure())
if err != nil { require.NoError(t, err, "Failed to dial")
t.Fatalf("Failed to dial: %v", err)
}
conns[i] = conn conns[i] = conn
defer func() { defer func() {
if err := conn.Close(); err != nil { if err := conn.Close(); err != nil {
@@ -93,9 +87,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
} }
nodeClient := eth.NewNodeClient(conns[0]) nodeClient := eth.NewNodeClient(conns[0])
genesis, err := nodeClient.GetGenesis(context.Background(), &ptypes.Empty{}) genesis, err := nodeClient.GetGenesis(context.Background(), &ptypes.Empty{})
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
epochSeconds := params.BeaconConfig().SecondsPerSlot * params.BeaconConfig().SlotsPerEpoch epochSeconds := params.BeaconConfig().SecondsPerSlot * params.BeaconConfig().SlotsPerEpoch
epochSecondsHalf := time.Duration(int64(epochSeconds*1000)/2) * time.Millisecond epochSecondsHalf := time.Duration(int64(epochSeconds*1000)/2) * time.Millisecond
@@ -113,9 +105,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
continue continue
} }
t.Run(fmt.Sprintf(evaluator.Name, currentEpoch), func(t *testing.T) { t.Run(fmt.Sprintf(evaluator.Name, currentEpoch), func(t *testing.T) {
if err := evaluator.Evaluation(conns...); err != nil { assert.NoError(t, evaluator.Evaluation(conns...), "Evaluation failed for epoch %d: %v", currentEpoch, err)
t.Errorf("evaluation failed for epoch %d: %v", currentEpoch, err)
}
}) })
} }
@@ -135,9 +125,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
index := e2e.TestParams.BeaconNodeCount index := e2e.TestParams.BeaconNodeCount
components.StartNewBeaconNode(t, config, index, bootnodeENR) components.StartNewBeaconNode(t, config, index, bootnodeENR)
syncConn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", e2e.TestParams.BeaconNodeRPCPort+index), grpc.WithInsecure()) syncConn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", e2e.TestParams.BeaconNodeRPCPort+index), grpc.WithInsecure())
if err != nil { require.NoError(t, err, "Failed to dial")
t.Fatalf("Failed to dial: %v", err)
}
conns = append(conns, syncConn) conns = append(conns, syncConn)
// Sleep a second for every 4 blocks that need to be synced for the newly started node. // Sleep a second for every 4 blocks that need to be synced for the newly started node.
@@ -146,14 +134,10 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
time.Sleep(time.Until(waitForSync)) time.Sleep(time.Until(waitForSync))
syncLogFile, err := os.Open(path.Join(e2e.TestParams.LogPath, fmt.Sprintf(e2e.BeaconNodeLogFileName, index))) syncLogFile, err := os.Open(path.Join(e2e.TestParams.LogPath, fmt.Sprintf(e2e.BeaconNodeLogFileName, index)))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
defer helpers.LogErrorOutput(t, syncLogFile, "beacon chain node", index) defer helpers.LogErrorOutput(t, syncLogFile, "beacon chain node", index)
t.Run("sync completed", func(t *testing.T) { t.Run("sync completed", func(t *testing.T) {
if err := helpers.WaitForTextInFile(syncLogFile, "Synced up to"); err != nil { assert.NoError(t, helpers.WaitForTextInFile(syncLogFile, "Synced up to"), "Failed to sync")
t.Errorf("Failed to sync: %v", err)
}
}) })
if t.Failed() { if t.Failed() {
return return
@@ -164,9 +148,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
syncEvaluators := []types.Evaluator{ev.FinishedSyncing, ev.AllNodesHaveSameHead} syncEvaluators := []types.Evaluator{ev.FinishedSyncing, ev.AllNodesHaveSameHead}
for _, evaluator := range syncEvaluators { for _, evaluator := range syncEvaluators {
t.Run(evaluator.Name, func(t *testing.T) { t.Run(evaluator.Name, func(t *testing.T) {
if err := evaluator.Evaluation(conns...); err != nil { assert.NoError(t, evaluator.Evaluation(conns...), "Evaluation failed for sync node")
t.Errorf("evaluation failed for sync node: %v", err)
}
}) })
} }
} }

View File

@@ -11,14 +11,13 @@ import (
"github.com/prysmaticlabs/prysm/endtoend/types" "github.com/prysmaticlabs/prysm/endtoend/types"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestEndToEnd_MinimalConfig(t *testing.T) { func TestEndToEnd_MinimalConfig(t *testing.T) {
testutil.ResetCache() testutil.ResetCache()
params.UseE2EConfig() params.UseE2EConfig()
if err := e2eParams.Init(e2eParams.StandardBeaconCount); err != nil { require.NoError(t, e2eParams.Init(e2eParams.StandardBeaconCount))
t.Fatal(err)
}
// Run for 10 epochs if not in long-running to confirm long-running has no issues. // Run for 10 epochs if not in long-running to confirm long-running has no issues.
epochsToRun := 10 epochsToRun := 10
@@ -26,9 +25,7 @@ func TestEndToEnd_MinimalConfig(t *testing.T) {
epochStr, longRunning := os.LookupEnv("E2E_EPOCHS") epochStr, longRunning := os.LookupEnv("E2E_EPOCHS")
if longRunning { if longRunning {
epochsToRun, err = strconv.Atoi(epochStr) epochsToRun, err = strconv.Atoi(epochStr)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
} }
minimalConfig := &types.E2EConfig{ minimalConfig := &types.E2EConfig{

View File

@@ -8,14 +8,13 @@ import (
"github.com/prysmaticlabs/prysm/endtoend/types" "github.com/prysmaticlabs/prysm/endtoend/types"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestEndToEnd_Slashing_MinimalConfig(t *testing.T) { func TestEndToEnd_Slashing_MinimalConfig(t *testing.T) {
testutil.ResetCache() testutil.ResetCache()
params.UseE2EConfig() params.UseE2EConfig()
if err := e2eParams.Init(e2eParams.StandardBeaconCount); err != nil { require.NoError(t, e2eParams.Init(e2eParams.StandardBeaconCount))
t.Fatal(err)
}
minimalConfig := &types.E2EConfig{ minimalConfig := &types.E2EConfig{
BeaconFlags: []string{}, BeaconFlags: []string{},

View File

@@ -52,6 +52,7 @@ go_test(
"//shared/bytesutil:go_default_library", "//shared/bytesutil:go_default_library",
"//shared/params/spectest:go_default_library", "//shared/params/spectest:go_default_library",
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_ferranbt_fastssz//:go_default_library", "@com_github_ferranbt_fastssz//:go_default_library",
"@com_github_ghodss_yaml//:go_default_library", "@com_github_ghodss_yaml//:go_default_library",
@@ -85,6 +86,7 @@ go_test(
"//shared/bytesutil:go_default_library", "//shared/bytesutil:go_default_library",
"//shared/params/spectest:go_default_library", "//shared/params/spectest:go_default_library",
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_ferranbt_fastssz//:go_default_library", "@com_github_ferranbt_fastssz//:go_default_library",
"@com_github_ghodss_yaml//:go_default_library", "@com_github_ghodss_yaml//:go_default_library",
@@ -113,6 +115,7 @@ go_test(
"//shared/bytesutil:go_default_library", "//shared/bytesutil:go_default_library",
"//shared/params/spectest:go_default_library", "//shared/params/spectest:go_default_library",
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_ferranbt_fastssz//:go_default_library", "@com_github_ferranbt_fastssz//:go_default_library",
"@com_github_ghodss_yaml//:go_default_library", "@com_github_ghodss_yaml//:go_default_library",

View File

@@ -9,6 +9,8 @@ import (
"github.com/prysmaticlabs/go-ssz" "github.com/prysmaticlabs/go-ssz"
sszspectest "github.com/prysmaticlabs/go-ssz/spectests" sszspectest "github.com/prysmaticlabs/go-ssz/spectests"
"github.com/prysmaticlabs/prysm/shared/bytesutil" "github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
// Regression tests for investigating discrepancies between ssz signing root of // Regression tests for investigating discrepancies between ssz signing root of
@@ -69,29 +71,17 @@ func TestBlockHeaderSigningRoot(t *testing.T) {
for i, tt := range tests { for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
root1, err := ssz.HashTreeRoot(tt.header1) root1, err := ssz.HashTreeRoot(tt.header1)
if err != nil { assert.NoError(t, err)
t.Error(err)
}
root2, err := ssz.HashTreeRoot(tt.header2) root2, err := ssz.HashTreeRoot(tt.header2)
if err != nil { assert.NoError(t, err)
t.Error(err) assert.Equal(t, root1, root2)
} assert.Equal(t, tt.expectedRoot, root1)
if root1 != root2 {
t.Errorf("Root1 = %#x, root2 = %#x. These should be equal!", root1, root2)
}
if root1 != tt.expectedRoot {
t.Errorf("Root1 = %#x, wanted %#x", root1, tt.expectedRoot)
}
}) })
} }
} }
func hexDecodeOrDie(t *testing.T, h string) []byte { func hexDecodeOrDie(t *testing.T, h string) []byte {
b, err := hex.DecodeString(h) b, err := hex.DecodeString(h)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
return b return b
} }

View File

@@ -1,7 +1,6 @@
package testing package testing
import ( import (
"bytes"
"context" "context"
"encoding/hex" "encoding/hex"
"errors" "errors"
@@ -25,9 +24,7 @@ type SSZRoots struct {
} }
func runSSZStaticTests(t *testing.T, config string) { func runSSZStaticTests(t *testing.T, config string) {
if err := spectest.SetConfig(t, config); err != nil { require.NoError(t, spectest.SetConfig(t, config))
t.Fatal(err)
}
testFolders, _ := testutil.TestFolders(t, config, "ssz_static") testFolders, _ := testutil.TestFolders(t, config, "ssz_static")
for _, folder := range testFolders { for _, folder := range testFolders {
@@ -37,22 +34,14 @@ func runSSZStaticTests(t *testing.T, config string) {
for _, innerFolder := range innerTestFolders { for _, innerFolder := range innerTestFolders {
t.Run(path.Join(folder.Name(), innerFolder.Name()), func(t *testing.T) { t.Run(path.Join(folder.Name(), innerFolder.Name()), func(t *testing.T) {
serializedBytes, err := testutil.BazelFileBytes(innerTestsFolderPath, innerFolder.Name(), "serialized.ssz") serializedBytes, err := testutil.BazelFileBytes(innerTestsFolderPath, innerFolder.Name(), "serialized.ssz")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
object, err := UnmarshalledSSZ(t, serializedBytes, folder.Name()) object, err := UnmarshalledSSZ(t, serializedBytes, folder.Name())
if err != nil { require.NoError(t, err, "Could not unmarshall serialized SSZ")
t.Fatalf("Could not unmarshall serialized SSZ: %v", err)
}
rootsYamlFile, err := testutil.BazelFileBytes(innerTestsFolderPath, innerFolder.Name(), "roots.yaml") rootsYamlFile, err := testutil.BazelFileBytes(innerTestsFolderPath, innerFolder.Name(), "roots.yaml")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
rootsYaml := &SSZRoots{} rootsYaml := &SSZRoots{}
if err := testutil.UnmarshalYaml(rootsYamlFile, rootsYaml); err != nil { require.NoError(t, testutil.UnmarshalYaml(rootsYamlFile, rootsYaml), "Failed to Unmarshal")
t.Fatalf("Failed to Unmarshal: %v", err)
}
// Custom hash tree root for beacon state. // Custom hash tree root for beacon state.
var htr func(interface{}) ([32]byte, error) var htr func(interface{}) ([32]byte, error)
@@ -67,39 +56,19 @@ func runSSZStaticTests(t *testing.T, config string) {
} }
root, err := htr(object) root, err := htr(object)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
rootBytes, err := hex.DecodeString(rootsYaml.Root[2:]) rootBytes, err := hex.DecodeString(rootsYaml.Root[2:])
if err != nil { require.NoError(t, err)
t.Fatal(err) require.DeepEqual(t, rootBytes, root[:], "Did not receive expected hash tree root")
}
if !bytes.Equal(root[:], rootBytes) {
t.Fatalf(
"Did not receive expected hash tree root, received: %#x, expected: %#x",
root[:],
rootBytes,
)
}
if rootsYaml.SigningRoot == "" { if rootsYaml.SigningRoot == "" {
return return
} }
signingRoot, err := ssz.HashTreeRoot(object) signingRoot, err := ssz.HashTreeRoot(object)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
signingRootBytes, err := hex.DecodeString(rootsYaml.SigningRoot[2:]) signingRootBytes, err := hex.DecodeString(rootsYaml.SigningRoot[2:])
if err != nil { require.NoError(t, err)
t.Fatal(err) require.DeepEqual(t, signingRootBytes, signingRoot[:], "Did not receive expected signing root")
}
if !bytes.Equal(signingRoot[:], signingRootBytes) {
t.Fatalf(
"Did not receive expected signing root, received: %#x, expected: %#x",
signingRoot[:],
signingRootBytes,
)
}
}) })
} }
} }

View File

@@ -8,6 +8,8 @@ import (
"testing" "testing"
pb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" pb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestSSZTagSize(t *testing.T) { func TestSSZTagSize(t *testing.T) {
@@ -16,36 +18,20 @@ func TestSSZTagSize(t *testing.T) {
rootSize := 32 rootSize := 32
sizes, err := sszTagSizes(pb.Attestation{}, "Signature") sizes, err := sszTagSizes(pb.Attestation{}, "Signature")
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, sigSize, sizes[0], "Unexpected signature size")
}
if sizes[0] != sigSize {
t.Errorf("wanted signature size: %d, got: %d", sigSize, sizes[0])
}
sizes, err = sszTagSizes(pb.SignedBeaconBlock{}, "Signature") sizes, err = sszTagSizes(pb.SignedBeaconBlock{}, "Signature")
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, sigSize, sizes[0], "Unexpected signature size")
}
if sizes[0] != sigSize {
t.Errorf("wanted signature size: %d, got: %d", sigSize, sizes[0])
}
sizes, err = sszTagSizes(pb.Checkpoint{}, "Root") sizes, err = sszTagSizes(pb.Checkpoint{}, "Root")
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, rootSize, sizes[0], "Unexpected signature size")
}
if sizes[0] != rootSize {
t.Errorf("wanted signature size: %d, got: %d", rootSize, sizes[0])
}
sizes, err = sszTagSizes(pb.Validator{}, "PublicKey") sizes, err = sszTagSizes(pb.Validator{}, "PublicKey")
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, pubKeySize, sizes[0], "Unexpected signature size")
}
if sizes[0] != pubKeySize {
t.Errorf("wanted signature size: %d, got: %d", pubKeySize, sizes[0])
}
} }
func sszTagSizes(i interface{}, fName string) ([]int, error) { func sszTagSizes(i interface{}, fName string) ([]int, error) {

View File

@@ -14,5 +14,8 @@ go_test(
size = "small", size = "small",
srcs = ["service_registry_test.go"], srcs = ["service_registry_test.go"],
embed = [":go_default_library"], embed = [":go_default_library"],
deps = ["//shared/testutil/require:go_default_library"], deps = [
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
],
) )

View File

@@ -1,7 +1,6 @@
package attestations package attestations
import ( import (
"errors"
"testing" "testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
@@ -15,29 +14,24 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
atts []*ethpb.Attestation atts []*ethpb.Attestation
} }
tests := []struct { tests := []struct {
name string name string
args args args args
want *aggregation.MaxCoverProblem want *aggregation.MaxCoverProblem
wantErr bool wantedErr string
expectedErr error
}{ }{
{ {
name: "nil attestations", name: "nil attestations",
args: args{ args: args{
atts: nil, atts: nil,
}, },
want: nil, wantedErr: ErrInvalidAttestationCount.Error(),
wantErr: true,
expectedErr: ErrInvalidAttestationCount,
}, },
{ {
name: "no attestations", name: "no attestations",
args: args{ args: args{
atts: []*ethpb.Attestation{}, atts: []*ethpb.Attestation{},
}, },
want: nil, wantedErr: ErrInvalidAttestationCount.Error(),
wantErr: true,
expectedErr: ErrInvalidAttestationCount,
}, },
{ {
name: "attestations of different bitlist length", name: "attestations of different bitlist length",
@@ -47,9 +41,7 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
{AggregationBits: bitfield.NewBitlist(128)}, {AggregationBits: bitfield.NewBitlist(128)},
}, },
}, },
want: nil, wantedErr: aggregation.ErrBitsDifferentLen.Error(),
wantErr: true,
expectedErr: aggregation.ErrBitsDifferentLen,
}, },
{ {
name: "single attestation", name: "single attestation",
@@ -63,7 +55,6 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
aggregation.NewMaxCoverCandidate(0, &bitfield.Bitlist{0b00001010, 0b1}), aggregation.NewMaxCoverCandidate(0, &bitfield.Bitlist{0b00001010, 0b1}),
}, },
}, },
wantErr: false,
}, },
{ {
name: "multiple attestations", name: "multiple attestations",
@@ -85,17 +76,17 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
aggregation.NewMaxCoverCandidate(4, &bitfield.Bitlist{0b00000001, 0b1}), aggregation.NewMaxCoverCandidate(4, &bitfield.Bitlist{0b00000001, 0b1}),
}, },
}, },
wantErr: false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
got, err := NewMaxCover(tt.args.atts) got, err := NewMaxCover(tt.args.atts)
if (err != nil) != tt.wantErr || !errors.Is(err, tt.expectedErr) { if tt.wantedErr != "" {
t.Errorf("NewMaxCoverProblem() unexpected error, got: %v, want: %v", err, tt.expectedErr) assert.ErrorContains(t, tt.wantedErr, err)
return } else {
assert.NoError(t, err)
assert.DeepEqual(t, tt.want, got)
} }
assert.DeepEqual(t, tt.want, got)
}) })
} }
} }

View File

@@ -1,7 +1,6 @@
package aggregation package aggregation
import ( import (
"errors"
"reflect" "reflect"
"sort" "sort"
"testing" "testing"
@@ -551,17 +550,15 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
allowDuplicates bool allowDuplicates bool
} }
tests := []struct { tests := []struct {
name string name string
args args args args
want *Aggregation want *Aggregation
wantErr bool wantedErr string
expectedErr error
}{ }{
{ {
name: "nil problem", name: "nil problem",
args: args{}, args: args{},
wantErr: true, wantedErr: ErrInvalidMaxCoverProblem.Error(),
expectedErr: ErrInvalidMaxCoverProblem,
}, },
{ {
name: "different bitlengths", name: "different bitlengths",
@@ -570,8 +567,7 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
{2, &bitfield.Bitlist{0b00000001, 0b11100000, 0b1}, 0, false}, {2, &bitfield.Bitlist{0b00000001, 0b11100000, 0b1}, 0, false},
{3, &bitfield.Bitlist{0b00000110, 0b00000000, 0b1}, 0, false}, {3, &bitfield.Bitlist{0b00000110, 0b00000000, 0b1}, 0, false},
}}, }},
wantErr: true, wantedErr: ErrInvalidMaxCoverProblem.Error(),
expectedErr: ErrInvalidMaxCoverProblem,
}, },
{ {
name: "k=0", name: "k=0",
@@ -580,7 +576,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0000000, 0b1}, Coverage: bitfield.Bitlist{0b0000000, 0b1},
Keys: []int{}, Keys: []int{},
}, },
wantErr: false,
}, },
{ {
name: "k=1", name: "k=1",
@@ -589,7 +584,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011011, 0b1}, Coverage: bitfield.Bitlist{0b0011011, 0b1},
Keys: []int{1}, Keys: []int{1},
}, },
wantErr: false,
}, },
{ {
name: "k=2", name: "k=2",
@@ -598,7 +592,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1}, Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0}, Keys: []int{1, 0},
}, },
wantErr: false,
}, },
{ {
name: "k=3", name: "k=3",
@@ -607,7 +600,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1}, Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0}, Keys: []int{1, 0},
}, },
wantErr: false,
}, },
{ {
name: "k=5", name: "k=5",
@@ -616,7 +608,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1}, Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0}, Keys: []int{1, 0},
}, },
wantErr: false,
}, },
{ {
name: "k=50", name: "k=50",
@@ -625,7 +616,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1}, Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0}, Keys: []int{1, 0},
}, },
wantErr: false,
}, },
{ {
name: "suboptimal", // Greedy algorithm selects: 0, 2, 3, while 1,4,5 is optimal. name: "suboptimal", // Greedy algorithm selects: 0, 2, 3, while 1,4,5 is optimal.
@@ -641,7 +631,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b00000111, 0b11111111, 0b1}, Coverage: bitfield.Bitlist{0b00000111, 0b11111111, 0b1},
Keys: []int{0, 2, 3}, Keys: []int{0, 2, 3},
}, },
wantErr: false,
}, },
{ {
name: "allow overlaps", name: "allow overlaps",
@@ -658,7 +647,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b00001111, 0xff, 0b11111110, 0b1}, Coverage: bitfield.Bitlist{0b00001111, 0xff, 0b11111110, 0b1},
Keys: []int{0, 3, 1, 2, 6}, Keys: []int{0, 3, 1, 2, 6},
}, },
wantErr: false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@@ -667,11 +655,12 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Candidates: tt.args.candidates, Candidates: tt.args.candidates,
} }
got, err := mc.Cover(tt.args.k, tt.args.allowOverlaps, tt.args.allowDuplicates) got, err := mc.Cover(tt.args.k, tt.args.allowOverlaps, tt.args.allowDuplicates)
if (err != nil) != tt.wantErr || !errors.Is(err, tt.expectedErr) { if tt.wantedErr != "" {
t.Errorf("newMaxCoverProblem() unexpected error, got: %v, want: %v", err, tt.expectedErr) assert.ErrorContains(t, tt.wantedErr, err)
return } else {
assert.NoError(t, err)
assert.DeepEqual(t, tt.want, got)
} }
assert.DeepEqual(t, tt.want, got)
}) })
} }
} }

View File

@@ -2,7 +2,6 @@ package attestationutil_test
import ( import (
"context" "context"
"strings"
"testing" "testing"
eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1" eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
@@ -49,9 +48,9 @@ func TestAttestingIndices(t *testing.T) {
func TestIsValidAttestationIndices(t *testing.T) { func TestIsValidAttestationIndices(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
att *eth.IndexedAttestation att *eth.IndexedAttestation
want string wantedErr string
}{ }{
{ {
name: "Indices should be non-empty", name: "Indices should be non-empty",
@@ -62,7 +61,7 @@ func TestIsValidAttestationIndices(t *testing.T) {
}, },
Signature: nil, Signature: nil,
}, },
want: "expected non-empty", wantedErr: "expected non-empty",
}, },
{ {
name: "Greater than max validators per committee", name: "Greater than max validators per committee",
@@ -73,7 +72,7 @@ func TestIsValidAttestationIndices(t *testing.T) {
}, },
Signature: nil, Signature: nil,
}, },
want: "indices count exceeds", wantedErr: "indices count exceeds",
}, },
{ {
name: "Needs to be sorted", name: "Needs to be sorted",
@@ -84,7 +83,7 @@ func TestIsValidAttestationIndices(t *testing.T) {
}, },
Signature: nil, Signature: nil,
}, },
want: "not uniquely sorted", wantedErr: "not uniquely sorted",
}, },
{ {
name: "Valid indices", name: "Valid indices",
@@ -100,11 +99,10 @@ func TestIsValidAttestationIndices(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
err := attestationutil.IsValidAttestationIndices(context.Background(), tt.att) err := attestationutil.IsValidAttestationIndices(context.Background(), tt.att)
if tt.want == "" && err != nil { if tt.wantedErr != "" {
t.Fatal(err) assert.ErrorContains(t, tt.wantedErr, err)
} } else {
if tt.want != "" && !strings.Contains(err.Error(), tt.want) { assert.NoError(t, err)
t.Errorf("IsValidAttestationIndices() got = %v, want %v", err, tt.want)
} }
}) })
} }

View File

@@ -6,6 +6,7 @@ import (
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/bls/herumi" "github.com/prysmaticlabs/prysm/shared/bls/herumi"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
) )
func TestPublicKeyFromBytes(t *testing.T) { func TestPublicKeyFromBytes(t *testing.T) {
@@ -48,17 +49,10 @@ func TestPublicKeyFromBytes(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
res, err := herumi.PublicKeyFromBytes(test.input) res, err := herumi.PublicKeyFromBytes(test.input)
if test.err != nil { if test.err != nil {
if err == nil { assert.ErrorContains(t, test.err.Error(), err)
t.Errorf("No error returned: expected %v", test.err)
} else if test.err.Error() != err.Error() {
t.Errorf("Unexpected error returned: expected %v, received %v", test.err, err)
}
} else { } else {
if err != nil { assert.NoError(t, err)
t.Errorf("Unexpected error returned: %v", err) assert.DeepEqual(t, test.input, res.Marshal())
} else if !bytes.Equal(res.Marshal(), test.input) {
t.Errorf("Unexpected result: expected %x, received %x", test.input, res.Marshal())
}
} }
}) })
} }

View File

@@ -1,7 +1,6 @@
package herumi_test package herumi_test
import ( import (
"bytes"
"errors" "errors"
"testing" "testing"
@@ -61,17 +60,10 @@ func TestSecretKeyFromBytes(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
res, err := herumi.SecretKeyFromBytes(test.input) res, err := herumi.SecretKeyFromBytes(test.input)
if test.err != nil { if test.err != nil {
if err == nil { assert.ErrorContains(t, test.err.Error(), err)
t.Errorf("No error returned: expected %v", test.err)
} else if test.err.Error() != err.Error() {
t.Errorf("Unexpected error returned: expected %v, received %v", test.err, err)
}
} else { } else {
if err != nil { assert.NoError(t, err)
t.Errorf("Unexpected error returned: %v", err) assert.DeepEqual(t, test.input, res.Marshal())
} else if !bytes.Equal(res.Marshal(), test.input) {
t.Errorf("Unexpected result: expected %x, received %x", test.input, res.Marshal())
}
} }
}) })
} }
@@ -81,7 +73,6 @@ func TestSerialize(t *testing.T) {
rk := herumi.RandKey() rk := herumi.RandKey()
b := rk.Marshal() b := rk.Marshal()
if _, err := herumi.SecretKeyFromBytes(b); err != nil { _, err := herumi.SecretKeyFromBytes(b)
t.Error(err) assert.NoError(t, err)
}
} }

View File

@@ -1,7 +1,6 @@
package herumi_test package herumi_test
import ( import (
"bytes"
"errors" "errors"
"testing" "testing"
@@ -65,9 +64,9 @@ func TestMultipleSignatureVerification(t *testing.T) {
sigs = append(sigs, sig) sigs = append(sigs, sig)
msgs = append(msgs, msg) msgs = append(msgs, msg)
} }
if verify, err := herumi.VerifyMultipleSignatures(sigs, msgs, pubkeys); !verify || err != nil { verify, err := herumi.VerifyMultipleSignatures(sigs, msgs, pubkeys)
t.Errorf("Signature did not verify: %v and err %v", verify, err) assert.NoError(t, err)
} assert.Equal(t, true, verify, "Signature did not verify")
} }
func TestMultipleSignatureVerification_FailsCorrectly(t *testing.T) { func TestMultipleSignatureVerification_FailsCorrectly(t *testing.T) {
@@ -128,9 +127,9 @@ func TestMultipleSignatureVerification_FailsCorrectly(t *testing.T) {
t.Error("Signature did not verify") t.Error("Signature did not verify")
} }
// This method would be expected to fail. // This method would be expected to fail.
if verify, err := herumi.VerifyMultipleSignatures(sigs, msgs, pubkeys); verify || err != nil { verify, err := herumi.VerifyMultipleSignatures(sigs, msgs, pubkeys)
t.Errorf("Signature verified when it was not supposed to: %v and err %v", verify, err) assert.NoError(t, err)
} assert.Equal(t, false, verify, "Signature verified when it was not supposed to")
} }
func TestFastAggregateVerify_ReturnsFalseOnEmptyPubKeyList(t *testing.T) { func TestFastAggregateVerify_ReturnsFalseOnEmptyPubKeyList(t *testing.T) {
@@ -184,17 +183,10 @@ func TestSignatureFromBytes(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
res, err := herumi.SignatureFromBytes(test.input) res, err := herumi.SignatureFromBytes(test.input)
if test.err != nil { if test.err != nil {
if err == nil { assert.ErrorContains(t, test.err.Error(), err)
t.Errorf("No error returned: expected %v", test.err)
} else if test.err.Error() != err.Error() {
t.Errorf("Unexpected error returned: expected %v, received %v", test.err, err)
}
} else { } else {
if err != nil { assert.NoError(t, err)
t.Errorf("Unexpected error returned: %v", err) assert.DeepEqual(t, test.input, res.Marshal())
} else if !bytes.Equal(res.Marshal(), test.input) {
t.Errorf("Unexpected result: expected %x, received %x", test.input, res.Marshal())
}
} }
}) })
} }

View File

@@ -66,11 +66,10 @@ func TestEnterPassword(t *testing.T) {
} }
pw, err := EnterPassword(true, m) pw, err := EnterPassword(true, m)
assert.Equal(t, tc.expectedPw, pw) assert.Equal(t, tc.expectedPw, pw)
if err == nil && tc.expectedErr != nil { if tc.expectedErr != nil {
t.Errorf("got nil err, expected %v err", tc.expectedErr.Error()) assert.ErrorContains(t, tc.expectedErr.Error(), err)
} } else {
if err != nil && tc.expectedErr != nil && errors.Cause(err).Error() != tc.expectedErr.Error() { assert.NoError(t, err)
t.Errorf("got %v, wanted %v", errors.Cause(err), tc.expectedErr.Error())
} }
}) })
} }

View File

@@ -23,5 +23,8 @@ go_test(
"subscription_test.go", "subscription_test.go",
], ],
embed = [":go_default_library"], embed = [":go_default_library"],
deps = ["//shared/testutil/require:go_default_library"], deps = [
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
],
) )

View File

@@ -22,6 +22,8 @@ import (
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
) )
func TestFeedPanics(t *testing.T) { func TestFeedPanics(t *testing.T) {
@@ -29,38 +31,28 @@ func TestFeedPanics(t *testing.T) {
var f Feed var f Feed
f.Send(2) f.Send(2)
want := feedTypeError{op: "Send", got: reflect.TypeOf(uint64(0)), want: reflect.TypeOf(0)} want := feedTypeError{op: "Send", got: reflect.TypeOf(uint64(0)), want: reflect.TypeOf(0)}
if err := checkPanic(want, func() { f.Send(uint64(2)) }); err != nil { assert.NoError(t, checkPanic(want, func() { f.Send(uint64(2)) }))
t.Error(err)
}
} }
{ {
var f Feed var f Feed
ch := make(chan int) ch := make(chan int)
f.Subscribe(ch) f.Subscribe(ch)
want := feedTypeError{op: "Send", got: reflect.TypeOf(uint64(0)), want: reflect.TypeOf(0)} want := feedTypeError{op: "Send", got: reflect.TypeOf(uint64(0)), want: reflect.TypeOf(0)}
if err := checkPanic(want, func() { f.Send(uint64(2)) }); err != nil { assert.NoError(t, checkPanic(want, func() { f.Send(uint64(2)) }))
t.Error(err)
}
} }
{ {
var f Feed var f Feed
f.Send(2) f.Send(2)
want := feedTypeError{op: "Subscribe", got: reflect.TypeOf(make(chan uint64)), want: reflect.TypeOf(make(chan<- int))} want := feedTypeError{op: "Subscribe", got: reflect.TypeOf(make(chan uint64)), want: reflect.TypeOf(make(chan<- int))}
if err := checkPanic(want, func() { f.Subscribe(make(chan uint64)) }); err != nil { assert.NoError(t, checkPanic(want, func() { f.Subscribe(make(chan uint64)) }))
t.Error(err)
}
} }
{ {
var f Feed var f Feed
if err := checkPanic(errBadChannel, func() { f.Subscribe(make(<-chan int)) }); err != nil { assert.NoError(t, checkPanic(errBadChannel, func() { f.Subscribe(make(<-chan int)) }))
t.Error(err)
}
} }
{ {
var f Feed var f Feed
if err := checkPanic(errBadChannel, func() { f.Subscribe(0) }); err != nil { assert.NoError(t, checkPanic(errBadChannel, func() { f.Subscribe(0) }))
t.Error(err)
}
} }
} }
@@ -283,22 +275,14 @@ func TestFeedUnsubscribeFromInbox(t *testing.T) {
sub2 = feed.Subscribe(ch1) sub2 = feed.Subscribe(ch1)
sub3 = feed.Subscribe(ch2) sub3 = feed.Subscribe(ch2)
) )
if len(feed.inbox) != 3 { assert.Equal(t, 3, len(feed.inbox))
t.Errorf("inbox length != 3 after subscribe") assert.Equal(t, 1, len(feed.sendCases), "sendCases is non-empty after unsubscribe")
}
if len(feed.sendCases) != 1 {
t.Errorf("sendCases is non-empty after unsubscribe")
}
sub1.Unsubscribe() sub1.Unsubscribe()
sub2.Unsubscribe() sub2.Unsubscribe()
sub3.Unsubscribe() sub3.Unsubscribe()
if len(feed.inbox) != 0 { assert.Equal(t, 0, len(feed.inbox), "Inbox is non-empty after unsubscribe")
t.Errorf("inbox is non-empty after unsubscribe") assert.Equal(t, 1, len(feed.sendCases), "sendCases is non-empty after unsubscribe")
}
if len(feed.sendCases) != 1 {
t.Errorf("sendCases is non-empty after unsubscribe")
}
} }
func BenchmarkFeedSend1000(b *testing.B) { func BenchmarkFeedSend1000(b *testing.B) {

View File

@@ -108,8 +108,6 @@ func setupTempKeystoreDir(t *testing.T) (string, func()) {
tempDir := path.Join(testutil.TempDir(), fmt.Sprintf("%d", randPath), "keystore") tempDir := path.Join(testutil.TempDir(), fmt.Sprintf("%d", randPath), "keystore")
return tempDir, func() { return tempDir, func() {
if err := os.RemoveAll(tempDir); err != nil { assert.NoError(t, os.RemoveAll(tempDir))
t.Logf("unable to remove temporary files: %v", err)
}
} }
} }

View File

@@ -17,6 +17,7 @@ go_test(
], ],
embed = [":go_default_library"], embed = [":go_default_library"],
deps = [ deps = [
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library",
], ],

View File

@@ -6,6 +6,7 @@ import (
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/mputil" "github.com/prysmaticlabs/prysm/shared/mputil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
@@ -53,12 +54,7 @@ func TestDouble(t *testing.T) {
return extent, nil return extent, nil
}) })
if test.err != nil { if test.err != nil {
if err == nil { assert.ErrorContains(t, test.err.Error(), err)
t.Fatalf("Missing expected error %v", test.err)
}
if test.err.Error() != err.Error() {
t.Fatalf("Unexpected error value: expected \"%v\", found \"%v\"", test.err, err)
}
} else { } else {
require.NoError(t, err) require.NoError(t, err)
for _, result := range workerResults { for _, result := range workerResults {
@@ -66,9 +62,7 @@ func TestDouble(t *testing.T) {
} }
for i := 0; i < test.inValues; i++ { for i := 0; i < test.inValues; i++ {
if outValues[i] != inValues[i]*2 { require.Equal(t, inValues[i]*2, outValues[i], "Outvalue at %d mismatch", i)
t.Fatalf("Outvalue at %d mismatch: expected %d, found %d", i, inValues[i]*2, outValues[i])
}
} }
} }
}) })

View File

@@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/prysmaticlabs/prysm/shared" "github.com/prysmaticlabs/prysm/shared"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@@ -28,9 +29,7 @@ func TestLifecycle(t *testing.T) {
// Query the service to ensure it really started. // Query the service to ensure it really started.
resp, err := http.Get("http://localhost:2112/metrics") resp, err := http.Get("http://localhost:2112/metrics")
require.NoError(t, err) require.NoError(t, err)
if resp.ContentLength == 0 { assert.NotEqual(t, uint64(0), resp.ContentLength, "Unexpected content length 0")
t.Error("Unexpected content length 0")
}
err = prometheusService.Stop() err = prometheusService.Stop()
require.NoError(t, err) require.NoError(t, err)
@@ -39,9 +38,7 @@ func TestLifecycle(t *testing.T) {
// Query the service to ensure it really stopped. // Query the service to ensure it really stopped.
_, err = http.Get("http://localhost:2112/metrics") _, err = http.Get("http://localhost:2112/metrics")
if err == nil { assert.NotNil(t, err, "Service still running after Stop()")
t.Fatal("Service still running after Stop()")
}
} }
type mockService struct { type mockService struct {
@@ -62,9 +59,7 @@ func (m *mockService) Status() error {
func TestHealthz(t *testing.T) { func TestHealthz(t *testing.T) {
registry := shared.NewServiceRegistry() registry := shared.NewServiceRegistry()
m := &mockService{} m := &mockService{}
if err := registry.RegisterService(m); err != nil { require.NoError(t, registry.RegisterService(m), "Failed to register service")
t.Fatalf("failed to registry service %v", err)
}
s := NewPrometheusService("" /*addr*/, registry) s := NewPrometheusService("" /*addr*/, registry)
req, err := http.NewRequest("GET", "/healthz", nil /*reader*/) req, err := http.NewRequest("GET", "/healthz", nil /*reader*/)
@@ -116,9 +111,7 @@ func TestContentNegotiation(t *testing.T) {
t.Run("/healthz all services are ok", func(t *testing.T) { t.Run("/healthz all services are ok", func(t *testing.T) {
registry := shared.NewServiceRegistry() registry := shared.NewServiceRegistry()
m := &mockService{} m := &mockService{}
if err := registry.RegisterService(m); err != nil { require.NoError(t, registry.RegisterService(m), "Failed to register service")
t.Fatalf("failed to registry service %v", err)
}
s := NewPrometheusService("", registry) s := NewPrometheusService("", registry)
req, err := http.NewRequest("GET", "/healthz", nil /* body */) req, err := http.NewRequest("GET", "/healthz", nil /* body */)
@@ -149,9 +142,7 @@ func TestContentNegotiation(t *testing.T) {
registry := shared.NewServiceRegistry() registry := shared.NewServiceRegistry()
m := &mockService{} m := &mockService{}
m.status = errors.New("something is wrong") m.status = errors.New("something is wrong")
if err := registry.RegisterService(m); err != nil { require.NoError(t, registry.RegisterService(m), "Failed to register service")
t.Fatalf("failed to registry service %v", err)
}
s := NewPrometheusService("", registry) s := NewPrometheusService("", registry)
req, err := http.NewRequest("GET", "/healthz", nil /* body */) req, err := http.NewRequest("GET", "/healthz", nil /* body */)

View File

@@ -24,4 +24,5 @@ go_test(
name = "go_default_test", name = "go_default_test",
srcs = ["validate_test.go"], srcs = ["validate_test.go"],
embed = [":go_default_library"], embed = [":go_default_library"],
deps = ["//shared/testutil/assert:go_default_library"],
) )

View File

@@ -1,48 +1,53 @@
package promptutil package promptutil
import "testing" import (
"testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
)
func TestValidatePasswordInput(t *testing.T) { func TestValidatePasswordInput(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
input string input string
wantErr bool wantedErr string
}{ }{
{ {
name: "no numbers nor special characters", name: "no numbers nor special characters",
input: "abcdefghijklmnopqrs", input: "abcdefghijklmnopqrs",
wantErr: true, wantedErr: "password must have more than 8 characters, at least 1 special character, and 1 number",
}, },
{ {
name: "number and letters but no special characters", name: "number and letters but no special characters",
input: "abcdefghijklmnopqrs2020", input: "abcdefghijklmnopqrs2020",
wantErr: true, wantedErr: "password must have more than 8 characters, at least 1 special character, and 1 number",
}, },
{ {
name: "numbers, letters, special characters, but too short", name: "numbers, letters, special characters, but too short",
input: "abc2$", input: "abc2$",
wantErr: true, wantedErr: "password must have more than 8 characters, at least 1 special character, and 1 number",
}, },
{ {
name: "proper length and strong password", name: "proper length and strong password",
input: "%Str0ngpassword32kjAjsd22020$%", input: "%Str0ngpassword32kjAjsd22020$%",
wantErr: false,
}, },
{ {
name: "password format correct but weak entropy score", name: "password format correct but weak entropy score",
input: "aaaaaaa1$", input: "aaaaaaa1$",
wantErr: true, wantedErr: "password is too easy to guess, try a stronger password",
}, },
{ {
name: "allow spaces", name: "allow spaces",
input: "x*329293@aAJSD i22903saj", input: "x*329293@aAJSD i22903saj",
wantErr: false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if err := ValidatePasswordInput(tt.input); (err != nil) != tt.wantErr { err := ValidatePasswordInput(tt.input)
t.Errorf("validatePasswordInput() error = %v, wantErr %v", err, tt.wantErr) if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
} }
}) })
} }

View File

@@ -5,6 +5,7 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
@@ -43,16 +44,11 @@ func TestRegisterService_Twice(t *testing.T) {
} }
m := &mockService{} m := &mockService{}
if err := registry.RegisterService(m); err != nil { require.NoError(t, registry.RegisterService(m), "Failed to register first service")
t.Fatalf("failed to register first service")
}
// Checks if first service was indeed registered. // Checks if first service was indeed registered.
require.Equal(t, 1, len(registry.serviceTypes)) require.Equal(t, 1, len(registry.serviceTypes))
assert.ErrorContains(t, "service already exists", registry.RegisterService(m))
if err := registry.RegisterService(m); err == nil {
t.Errorf("should not be able to register a service twice, got nil error")
}
} }
func TestRegisterService_Different(t *testing.T) { func TestRegisterService_Different(t *testing.T) {
@@ -62,23 +58,16 @@ func TestRegisterService_Different(t *testing.T) {
m := &mockService{} m := &mockService{}
s := &secondMockService{} s := &secondMockService{}
if err := registry.RegisterService(m); err != nil { require.NoError(t, registry.RegisterService(m), "Failed to register first service")
t.Fatalf("failed to register first service") require.NoError(t, registry.RegisterService(s), "Failed to register second service")
}
if err := registry.RegisterService(s); err != nil {
t.Fatalf("failed to register second service")
}
require.Equal(t, 2, len(registry.serviceTypes)) require.Equal(t, 2, len(registry.serviceTypes))
if _, exists := registry.services[reflect.TypeOf(m)]; !exists { _, exists := registry.services[reflect.TypeOf(m)]
t.Errorf("service of type %v not registered", reflect.TypeOf(m)) assert.Equal(t, true, exists, "service of type %v not registered", reflect.TypeOf(m))
}
if _, exists := registry.services[reflect.TypeOf(s)]; !exists { _, exists = registry.services[reflect.TypeOf(s)]
t.Errorf("service of type %v not registered", reflect.TypeOf(s)) assert.Equal(t, true, exists, "service of type %v not registered", reflect.TypeOf(s))
}
} }
func TestFetchService_OK(t *testing.T) { func TestFetchService_OK(t *testing.T) {
@@ -87,24 +76,15 @@ func TestFetchService_OK(t *testing.T) {
} }
m := &mockService{} m := &mockService{}
if err := registry.RegisterService(m); err != nil { require.NoError(t, registry.RegisterService(m), "Failed to register first service")
t.Fatalf("failed to register first service")
}
if err := registry.FetchService(*m); err == nil { assert.ErrorContains(t, "input must be of pointer type, received value type instead", registry.FetchService(*m))
t.Errorf("passing in a value should throw an error, received nil error")
}
var s *secondMockService var s *secondMockService
if err := registry.FetchService(&s); err == nil { assert.ErrorContains(t, "unknown service", registry.FetchService(&s))
t.Errorf("fetching an unregistered service should return an error, got nil")
}
var m2 *mockService var m2 *mockService
if err := registry.FetchService(&m2); err != nil { require.NoError(t, registry.FetchService(&m2), "Failed to fetch service")
t.Fatalf("failed to fetch service")
}
require.Equal(t, m, m2) require.Equal(t, m, m2)
} }
@@ -114,27 +94,16 @@ func TestServiceStatus_OK(t *testing.T) {
} }
m := &mockService{} m := &mockService{}
if err := registry.RegisterService(m); err != nil { require.NoError(t, registry.RegisterService(m), "Failed to register first service")
t.Fatalf("failed to register first service")
}
s := &secondMockService{} s := &secondMockService{}
if err := registry.RegisterService(s); err != nil { require.NoError(t, registry.RegisterService(s), "Failed to register first service")
t.Fatalf("failed to register first service")
}
m.status = errors.New("something bad has happened") m.status = errors.New("something bad has happened")
s.status = errors.New("woah, horsee") s.status = errors.New("woah, horsee")
statuses := registry.Statuses() statuses := registry.Statuses()
mStatus := statuses[reflect.TypeOf(m)] assert.ErrorContains(t, "something bad has happened", statuses[reflect.TypeOf(m)])
if mStatus == nil || mStatus.Error() != "something bad has happened" { assert.ErrorContains(t, "woah, horsee", statuses[reflect.TypeOf(s)])
t.Errorf("Received unexpected status for %T = %v", m, mStatus)
}
sStatus := statuses[reflect.TypeOf(s)]
if sStatus == nil || sStatus.Error() != "woah, horsee" {
t.Errorf("Received unexpected status for %T = %v", s, sStatus)
}
} }

View File

@@ -20,9 +20,7 @@ func TestBlockSignature(t *testing.T) {
proposerIdx, err := helpers.BeaconProposerIndex(beaconState) proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
assert.NoError(t, err) assert.NoError(t, err)
if err := beaconState.SetSlot(beaconState.Slot() - 1); err != nil { assert.NoError(t, beaconState.SetSlot(beaconState.Slot()-1))
t.Error(err)
}
epoch := helpers.SlotToEpoch(block.Block.Slot) epoch := helpers.SlotToEpoch(block.Block.Slot)
blockSig, err := helpers.ComputeDomainAndSign(beaconState, epoch, block.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx]) blockSig, err := helpers.ComputeDomainAndSign(beaconState, epoch, block.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[proposerIdx])
require.NoError(t, err) require.NoError(t, err)

View File

@@ -188,9 +188,8 @@ func BenchmarkGenerateTrieFromItems(b *testing.B) {
[]byte("GGGGGGG"), []byte("GGGGGGG"),
} }
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if _, err := GenerateTrieFromItems(items, int(params.BeaconConfig().DepositContractTreeDepth)); err != nil { _, err := GenerateTrieFromItems(items, int(params.BeaconConfig().DepositContractTreeDepth))
b.Fatalf("Could not generate Merkle trie from items: %v", err) require.NoError(b, err, "Could not generate Merkle trie from items")
}
} }
} }
@@ -228,9 +227,8 @@ func BenchmarkGenerateProof(b *testing.B) {
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if _, err := normalTrie.MerkleProof(3); err != nil { _, err := normalTrie.MerkleProof(3)
b.Fatal(err) require.NoError(b, err)
}
} }
} }

View File

@@ -45,8 +45,6 @@ func BenchmarkSpan_Unmarshal(b *testing.B) {
var err error var err error
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
span, err = types.UnmarshalSpan(marshaled) span, err = types.UnmarshalSpan(marshaled)
if err != nil { require.NoError(b, err)
b.Fatal(err)
}
} }
} }

View File

@@ -29,4 +29,8 @@ go_test(
name = "go_default_test", name = "go_default_test",
srcs = ["embedded_walker_test.go"], srcs = ["embedded_walker_test.go"],
embed = [":go_default_library"], embed = [":go_default_library"],
deps = [
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
],
) )

View File

@@ -6,6 +6,9 @@ import (
"go/token" "go/token"
"go/types" "go/types"
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
const commonSrc = ` const commonSrc = `
@@ -46,25 +49,19 @@ func TestWalkThroughEmbeddedInterfaces(t *testing.T) {
for _, c := range cases { for _, c := range cases {
fset := token.NewFileSet() fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "test", commonSrc+c.selector, 0) f, err := parser.ParseFile(fset, "test", commonSrc+c.selector, 0)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
conf := types.Config{} conf := types.Config{}
info := types.Info{ info := types.Info{
Selections: make(map[*ast.SelectorExpr]*types.Selection), Selections: make(map[*ast.SelectorExpr]*types.Selection),
} }
_, err = conf.Check("test", fset, []*ast.File{f}, &info) _, err = conf.Check("test", fset, []*ast.File{f}, &info)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ast.Inspect(f, func(n ast.Node) bool { ast.Inspect(f, func(n ast.Node) bool {
s, ok := n.(*ast.SelectorExpr) s, ok := n.(*ast.SelectorExpr)
if ok { if ok {
selection, ok := info.Selections[s] selection, ok := info.Selections[s]
if !ok { require.Equal(t, true, ok, "No selection!")
t.Fatalf("no Selection!")
}
ts, ok := walkThroughEmbeddedInterfaces(selection) ts, ok := walkThroughEmbeddedInterfaces(selection)
if ok != c.expectedOk { if ok != c.expectedOk {
t.Errorf("expected ok %v got %v", c.expectedOk, ok) t.Errorf("expected ok %v got %v", c.expectedOk, ok)
@@ -74,20 +71,12 @@ func TestWalkThroughEmbeddedInterfaces(t *testing.T) {
return false return false
} }
if len(ts) != len(c.expected) { require.Equal(t, len(c.expected), len(ts))
t.Fatalf("expected %d types, got %d", len(c.expected), len(ts))
}
for i, e := range c.expected { for i, e := range c.expected {
if e != ts[i].String() { assert.Equal(t, e, ts[i].String(), "mismatch at index %d", i)
t.Errorf("mismatch at index %d: expected %s got %s", i, e, ts[i])
}
} }
} }
return true return true
}) })
} }
} }

View File

@@ -100,9 +100,12 @@ go_test(
deps = [ deps = [
"//shared/iputils:go_default_library", "//shared/iputils:go_default_library",
"//shared/maxprocs:go_default_library", "//shared/maxprocs:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"@com_github_btcsuite_btcd//btcec:go_default_library", "@com_github_btcsuite_btcd//btcec:go_default_library",
"@com_github_ethereum_go_ethereum//p2p/discover:go_default_library", "@com_github_ethereum_go_ethereum//p2p/discover:go_default_library",
"@com_github_ethereum_go_ethereum//p2p/enode:go_default_library", "@com_github_ethereum_go_ethereum//p2p/enode:go_default_library",
"@com_github_libp2p_go_libp2p_core//crypto:go_default_library", "@com_github_libp2p_go_libp2p_core//crypto:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
], ],
) )

View File

@@ -4,6 +4,8 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"crypto/rand" "crypto/rand"
"fmt" "fmt"
"io/ioutil"
"os"
"testing" "testing"
"time" "time"
@@ -13,13 +15,21 @@ import (
"github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/crypto"
"github.com/prysmaticlabs/prysm/shared/iputils" "github.com/prysmaticlabs/prysm/shared/iputils"
_ "github.com/prysmaticlabs/prysm/shared/maxprocs" _ "github.com/prysmaticlabs/prysm/shared/maxprocs"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/sirupsen/logrus"
) )
func TestMain(m *testing.M) {
logrus.SetLevel(logrus.DebugLevel)
logrus.SetOutput(ioutil.Discard)
os.Exit(m.Run())
}
func TestBootnode_OK(t *testing.T) { func TestBootnode_OK(t *testing.T) {
ipAddr, err := iputils.ExternalIPv4() ipAddr, err := iputils.ExternalIPv4()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
privKey := extractPrivateKey() privKey := extractPrivateKey()
cfg := discover.Config{ cfg := discover.Config{
PrivateKey: privKey, PrivateKey: privKey,
@@ -29,9 +39,7 @@ func TestBootnode_OK(t *testing.T) {
cfg.PrivateKey = extractPrivateKey() cfg.PrivateKey = extractPrivateKey()
bootNode, err := enode.Parse(enode.ValidSchemes, listener.Self().String()) bootNode, err := enode.Parse(enode.ValidSchemes, listener.Self().String())
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
cfg.Bootnodes = []*enode.Node{bootNode} cfg.Bootnodes = []*enode.Node{bootNode}
listener2 := createListener(ipAddr, 4001, cfg) listener2 := createListener(ipAddr, 4001, cfg)
defer listener2.Close() defer listener2.Close()
@@ -43,34 +51,20 @@ func TestBootnode_OK(t *testing.T) {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
nodes := listener.Lookup(listenerNode2.ID()) nodes := listener.Lookup(listenerNode2.ID())
if len(nodes) == 0 { assert.NotEqual(t, 0, len(nodes), "Length of nodes stored in table is not expected")
t.Fatalf("Length of nodes stored in table is not expected. Wanted to be more than %d but got %d", 0, len(nodes)) assert.Equal(t, listenerNode2.ID(), nodes[0].ID())
}
if nodes[0].ID() != listenerNode2.ID() {
t.Errorf("Wanted node ID of %s but got %s", listenerNode2.ID(), nodes[1].ID())
}
nodes = listener2.Lookup(listenerNode.ID()) nodes = listener2.Lookup(listenerNode.ID())
if len(nodes) == 0 { assert.NotEqual(t, 0, len(nodes), "Length of nodes stored in table is not expected")
t.Errorf("Length of nodes stored in table is not expected. Wanted to be more than %d but got %d", 0, len(nodes)) assert.Equal(t, listenerNode.ID(), nodes[0].ID())
}
if nodes[0].ID() != listenerNode.ID() {
t.Errorf("Wanted node ID of %s but got %s", listenerNode.ID(), nodes[1].ID())
}
} }
func TestPrivateKey_ParsesCorrectly(t *testing.T) { func TestPrivateKey_ParsesCorrectly(t *testing.T) {
privKey, _, err := crypto.GenerateSecp256k1Key(rand.Reader) privKey, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
pk, err := privKey.Raw() pk, err := privKey.Raw()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
*privateKey = fmt.Sprintf("%x", pk) *privateKey = fmt.Sprintf("%x", pk)
extractedKey := extractPrivateKey() extractedKey := extractPrivateKey()
@@ -78,13 +72,9 @@ func TestPrivateKey_ParsesCorrectly(t *testing.T) {
rawKey := (*ecdsa.PrivateKey)((*btcec.PrivateKey)(privKey.(*crypto.Secp256k1PrivateKey))) rawKey := (*ecdsa.PrivateKey)((*btcec.PrivateKey)(privKey.(*crypto.Secp256k1PrivateKey)))
r, s, err := ecdsa.Sign(rand.Reader, extractedKey, []byte{'t', 'e', 's', 't'}) r, s, err := ecdsa.Sign(rand.Reader, extractedKey, []byte{'t', 'e', 's', 't'})
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
isVerified := ecdsa.Verify(&rawKey.PublicKey, []byte{'t', 'e', 's', 't'}, r, s) isVerified := ecdsa.Verify(&rawKey.PublicKey, []byte{'t', 'e', 's', 't'}, r, s)
if !isVerified { assert.Equal(t, true, isVerified, "Unmarshalled key is not the same as the key that was given to the function")
t.Error("Unmarshalled key is not the same as the key that was given to the function")
}
*privateKey = "" *privateKey = ""
} }

View File

@@ -40,6 +40,8 @@ go_test(
"//shared/interop:go_default_library", "//shared/interop:go_default_library",
"//shared/params:go_default_library", "//shared/params:go_default_library",
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"//shared/trieutil:go_default_library", "//shared/trieutil:go_default_library",
"@com_github_ethereum_go_ethereum//:go_default_library", "@com_github_ethereum_go_ethereum//:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library",

View File

@@ -1,11 +1,11 @@
package main package main
import ( import (
"bytes"
"context" "context"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
"time" "time"
@@ -17,13 +17,17 @@ import (
"github.com/prysmaticlabs/prysm/shared/interop" "github.com/prysmaticlabs/prysm/shared/interop"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/shared/trieutil" "github.com/prysmaticlabs/prysm/shared/trieutil"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
func init() { func TestMain(m *testing.M) {
logrus.SetLevel(logrus.DebugLevel) logrus.SetLevel(logrus.DebugLevel)
logrus.SetOutput(ioutil.Discard) logrus.SetOutput(ioutil.Discard)
os.Exit(m.Run())
} }
func sendDeposits(t *testing.T, testAcc *contracts.TestAccount, func sendDeposits(t *testing.T, testAcc *contracts.TestAccount,
@@ -34,14 +38,10 @@ func sendDeposits(t *testing.T, testAcc *contracts.TestAccount,
depositContractAddrStr := testAcc.ContractAddr.Hex() depositContractAddrStr := testAcc.ContractAddr.Hex()
privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0, numberOfValidators) privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0, numberOfValidators)
if err != nil { require.NoError(t, err, "Unable to generate keys")
t.Fatalf("Unable to generate keys: %v", err)
}
depositData, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys) depositData, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys)
if err != nil { require.NoError(t, err, "Unable to generate deposit data from keys")
t.Fatalf("Unable to generate deposit data from keys: %v", err)
}
for i, data := range depositData { for i, data := range depositData {
dataRoot := [32]byte{} dataRoot := [32]byte{}
@@ -55,9 +55,7 @@ func sendDeposits(t *testing.T, testAcc *contracts.TestAccount,
for j := uint64(0); j < numberOfDeposits; j++ { for j := uint64(0); j < numberOfDeposits; j++ {
tx, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot) tx, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot)
if err != nil { require.NoError(t, err, "Unable to send transaction to contract")
t.Fatalf("unable to send transaction to contract: %v", err)
}
testAcc.Backend.Commit() testAcc.Backend.Commit()
@@ -74,9 +72,7 @@ func sendDeposits(t *testing.T, testAcc *contracts.TestAccount,
func TestEndtoEndDeposits(t *testing.T) { func TestEndtoEndDeposits(t *testing.T) {
testutil.ResetCache() testutil.ResetCache()
testAcc, err := contracts.Setup() testAcc, err := contracts.Setup()
if err != nil { require.NoError(t, err, "Unable to set up simulated backend")
t.Fatalf("Unable to set up simulated backend %v", err)
}
testAcc.Backend.Commit() testAcc.Backend.Commit()
@@ -94,39 +90,18 @@ func TestEndtoEndDeposits(t *testing.T) {
} }
logs, err := testAcc.Backend.FilterLogs(context.Background(), query) logs, err := testAcc.Backend.FilterLogs(context.Background(), query)
if err != nil { require.NoError(t, err, "Unable to retrieve logs")
t.Fatalf("Unable to retrieve logs %v", err) require.NotEqual(t, 0, len(logs), "No logs")
} require.Equal(t, int(numberOfDeposits*numberOfValidators), len(logs), "No sufficient number of logs")
if len(logs) == 0 {
t.Fatal("no logs")
}
if len(logs) != int(numberOfDeposits*numberOfValidators) {
t.Fatal("No sufficient number of logs")
}
j := 0 j := 0
for i, log := range logs { for i, log := range logs {
loggedPubkey, withCreds, _, loggedSig, index, err := contracts.UnpackDepositLogData(log.Data) loggedPubkey, withCreds, _, loggedSig, index, err := contracts.UnpackDepositLogData(log.Data)
if err != nil { require.NoError(t, err, "Unable to unpack logs")
t.Fatalf("Unable to unpack logs %v", err) assert.Equal(t, uint64(i), binary.LittleEndian.Uint64(index))
} assert.DeepEqual(t, deposits[j].Data.PublicKey, loggedPubkey, "Pubkey is not the same as the data that was put in %v, i: %d", loggedPubkey, i)
assert.DeepEqual(t, deposits[j].Data.Signature, loggedSig, "Proof of Possession is not the same as the data that was put in %v, i: %d", loggedSig, i)
if binary.LittleEndian.Uint64(index) != uint64(i) { assert.DeepEqual(t, deposits[j].Data.WithdrawalCredentials, withCreds, "Withdrawal Credentials is not the same as the data that was put in %v, i: %d", withCreds, i)
t.Errorf("Retrieved merkle tree index is incorrect %d", index)
}
if !bytes.Equal(loggedPubkey, deposits[j].Data.PublicKey) {
t.Errorf("Pubkey is not the same as the data that was put in %v, i: %d", loggedPubkey, i)
}
if !bytes.Equal(loggedSig, deposits[j].Data.Signature) {
t.Errorf("Proof of Possession is not the same as the data that was put in %v, i: %d", loggedSig, i)
}
if !bytes.Equal(withCreds, deposits[j].Data.WithdrawalCredentials) {
t.Errorf("Withdrawal Credentials is not the same as the data that was put in %v, i: %d", withCreds, i)
}
if i == int(numberOfDeposits)-1 { if i == int(numberOfDeposits)-1 {
j++ j++
@@ -136,35 +111,21 @@ func TestEndtoEndDeposits(t *testing.T) {
encodedDeposits := make([][]byte, numberOfValidators*numberOfDeposits) encodedDeposits := make([][]byte, numberOfValidators*numberOfDeposits)
for i := 0; i < int(numberOfValidators); i++ { for i := 0; i < int(numberOfValidators); i++ {
hashedDeposit, err := ssz.HashTreeRoot(deposits[i].Data) hashedDeposit, err := ssz.HashTreeRoot(deposits[i].Data)
if err != nil { require.NoError(t, err, "Could not tree hash deposit data")
t.Fatalf("could not tree hash deposit data: %v", err)
}
for j := 0; j < int(numberOfDeposits); j++ { for j := 0; j < int(numberOfDeposits); j++ {
encodedDeposits[i*int(numberOfDeposits)+j] = hashedDeposit[:] encodedDeposits[i*int(numberOfDeposits)+j] = hashedDeposit[:]
} }
} }
depositTrie, err := trieutil.GenerateTrieFromItems(encodedDeposits, int(params.BeaconConfig().DepositContractTreeDepth)) depositTrie, err := trieutil.GenerateTrieFromItems(encodedDeposits, int(params.BeaconConfig().DepositContractTreeDepth))
if err != nil { require.NoError(t, err, "Could not generate trie")
t.Fatalf("Could not generate trie: %v", err)
}
root := depositTrie.Root() root := depositTrie.Root()
for i, encodedDeposit := range encodedDeposits { for i, encodedDeposit := range encodedDeposits {
proof, err := depositTrie.MerkleProof(i) proof, err := depositTrie.MerkleProof(i)
if err != nil { require.NoError(t, err, "Could not generate proof")
t.Fatalf("Could not generate proof: %v", err) require.Equal(t, true, trieutil.VerifyMerkleBranch(root[:], encodedDeposit, i, proof),
} "Unable verify deposit merkle branch of deposit root for root: %#x, encodedDeposit: %#x, i : %d", root[:], encodedDeposit, i)
if ok := trieutil.VerifyMerkleBranch(
root[:],
encodedDeposit,
i,
proof,
); !ok {
t.Fatalf(
"Unable verify deposit merkle branch of deposit root for root: %#x, encodedDeposit: %#x, i : %d",
root[:], encodedDeposit, i)
}
} }
} }

View File

@@ -25,5 +25,9 @@ go_test(
name = "go_default_test", name = "go_default_test",
srcs = ["main_test.go"], srcs = ["main_test.go"],
embed = [":go_default_library"], embed = [":go_default_library"],
deps = ["//tools/unencrypted-keys-gen/keygen:go_default_library"], deps = [
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library",
"//tools/unencrypted-keys-gen/keygen:go_default_library",
],
) )

View File

@@ -3,9 +3,10 @@ package main
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"reflect"
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/tools/unencrypted-keys-gen/keygen" "github.com/prysmaticlabs/prysm/tools/unencrypted-keys-gen/keygen"
) )
@@ -14,15 +15,9 @@ func TestSavesUnencryptedKeys(t *testing.T) {
numKeys = &keys numKeys = &keys
ctnr := generateUnencryptedKeys(0 /* start index */) ctnr := generateUnencryptedKeys(0 /* start index */)
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
if err := keygen.SaveUnencryptedKeysToFile(buf, ctnr); err != nil { require.NoError(t, keygen.SaveUnencryptedKeysToFile(buf, ctnr))
t.Fatal(err)
}
enc := buf.Bytes() enc := buf.Bytes()
dec := &keygen.UnencryptedKeysContainer{} dec := &keygen.UnencryptedKeysContainer{}
if err := json.Unmarshal(enc, dec); err != nil { require.NoError(t, json.Unmarshal(enc, dec))
t.Fatal(err) assert.DeepEqual(t, ctnr, dec)
}
if !reflect.DeepEqual(ctnr, dec) {
t.Errorf("Wanted %v, received %v", ctnr, dec)
}
} }

View File

@@ -62,9 +62,7 @@ func TestNewValidatorAccount_CreateValidatorAccount(t *testing.T) {
t.Run("empty existing dir", func(t *testing.T) { t.Run("empty existing dir", func(t *testing.T) {
directory := testutil.TempDir() + "/testkeystore" directory := testutil.TempDir() + "/testkeystore"
defer func() { defer func() {
if err := os.RemoveAll(directory); err != nil { assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
t.Logf("Could not remove directory: %v", err)
}
}() }()
// Make sure that empty existing directory doesn't trigger any errors. // Make sure that empty existing directory doesn't trigger any errors.
@@ -76,9 +74,7 @@ func TestNewValidatorAccount_CreateValidatorAccount(t *testing.T) {
t.Run("empty string as password", func(t *testing.T) { t.Run("empty string as password", func(t *testing.T) {
directory := testutil.TempDir() + "/testkeystore" directory := testutil.TempDir() + "/testkeystore"
defer func() { defer func() {
if err := os.RemoveAll(directory); err != nil { assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
t.Logf("Could not remove directory: %v", err)
}
}() }()
require.NoError(t, os.Mkdir(directory, 0777)) require.NoError(t, os.Mkdir(directory, 0777))
_, _, err := CreateValidatorAccount(directory, "") _, _, err := CreateValidatorAccount(directory, "")
@@ -106,9 +102,7 @@ func TestHandleEmptyFlags_FlagsSet(t *testing.T) {
func TestChangePassword_KeyEncryptedWithNewPassword(t *testing.T) { func TestChangePassword_KeyEncryptedWithNewPassword(t *testing.T) {
directory := testutil.TempDir() + "/testkeystore" directory := testutil.TempDir() + "/testkeystore"
defer func() { defer func() {
if err := os.RemoveAll(directory); err != nil { assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
t.Logf("Could not remove directory: %v", err)
}
}() }()
oldPassword := "old" oldPassword := "old"
@@ -132,9 +126,7 @@ func TestChangePassword_KeyEncryptedWithNewPassword(t *testing.T) {
func TestChangePassword_KeyNotMatchingOldPasswordNotEncryptedWithNewPassword(t *testing.T) { func TestChangePassword_KeyNotMatchingOldPasswordNotEncryptedWithNewPassword(t *testing.T) {
directory := testutil.TempDir() + "/testkeystore" directory := testutil.TempDir() + "/testkeystore"
defer func() { defer func() {
if err := os.RemoveAll(directory); err != nil { assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
t.Logf("Could not remove directory: %v", err)
}
}() }()
oldPassword := "old" oldPassword := "old"

View File

@@ -32,11 +32,9 @@ var _ = Validator(&validator{})
const cancelledCtx = "context has been canceled" const cancelledCtx = "context has been canceled"
func publicKeys(km keymanager.KeyManager) [][]byte { func publicKeys(t *testing.T, km keymanager.KeyManager) [][]byte {
keys, err := km.FetchValidatingKeys() keys, err := km.FetchValidatingKeys()
if err != nil { assert.NoError(t, err, "Cannot fetch validating keys")
log.WithError(err).Debug("Cannot fetch validating keys")
}
res := make([][]byte, len(keys)) res := make([][]byte, len(keys))
for i := range keys { for i := range keys {
res[i] = keys[i][:] res[i] = keys[i][:]
@@ -263,7 +261,7 @@ func TestWaitActivation_ContextCanceled(t *testing.T) {
client.EXPECT().WaitForActivation( client.EXPECT().WaitForActivation(
gomock.Any(), gomock.Any(),
&ethpb.ValidatorActivationRequest{ &ethpb.ValidatorActivationRequest{
PublicKeys: publicKeys(v.keyManager), PublicKeys: publicKeys(t, v.keyManager),
}, },
).Return(clientStream, nil) ).Return(clientStream, nil)
clientStream.EXPECT().Recv().Return( clientStream.EXPECT().Recv().Return(
@@ -288,7 +286,7 @@ func TestWaitActivation_StreamSetupFails(t *testing.T) {
client.EXPECT().WaitForActivation( client.EXPECT().WaitForActivation(
gomock.Any(), gomock.Any(),
&ethpb.ValidatorActivationRequest{ &ethpb.ValidatorActivationRequest{
PublicKeys: publicKeys(v.keyManager), PublicKeys: publicKeys(t, v.keyManager),
}, },
).Return(clientStream, errors.New("failed stream")) ).Return(clientStream, errors.New("failed stream"))
err := v.WaitForActivation(context.Background()) err := v.WaitForActivation(context.Background())
@@ -309,7 +307,7 @@ func TestWaitActivation_ReceiveErrorFromStream(t *testing.T) {
client.EXPECT().WaitForActivation( client.EXPECT().WaitForActivation(
gomock.Any(), gomock.Any(),
&ethpb.ValidatorActivationRequest{ &ethpb.ValidatorActivationRequest{
PublicKeys: publicKeys(v.keyManager), PublicKeys: publicKeys(t, v.keyManager),
}, },
).Return(clientStream, nil) ).Return(clientStream, nil)
clientStream.EXPECT().Recv().Return( clientStream.EXPECT().Recv().Return(
@@ -332,13 +330,13 @@ func TestWaitActivation_LogsActivationEpochOK(t *testing.T) {
validatorClient: client, validatorClient: client,
genesisTime: 1, genesisTime: 1,
} }
resp := generateMockStatusResponse(publicKeys(v.keyManager)) resp := generateMockStatusResponse(publicKeys(t, v.keyManager))
resp.Statuses[0].Status.Status = ethpb.ValidatorStatus_ACTIVE resp.Statuses[0].Status.Status = ethpb.ValidatorStatus_ACTIVE
clientStream := mock.NewMockBeaconNodeValidator_WaitForActivationClient(ctrl) clientStream := mock.NewMockBeaconNodeValidator_WaitForActivationClient(ctrl)
client.EXPECT().WaitForActivation( client.EXPECT().WaitForActivation(
gomock.Any(), gomock.Any(),
&ethpb.ValidatorActivationRequest{ &ethpb.ValidatorActivationRequest{
PublicKeys: publicKeys(v.keyManager), PublicKeys: publicKeys(t, v.keyManager),
}, },
).Return(clientStream, nil) ).Return(clientStream, nil)
clientStream.EXPECT().Recv().Return( clientStream.EXPECT().Recv().Return(
@@ -394,7 +392,7 @@ func TestWaitMultipleActivation_LogsActivationEpochOK(t *testing.T) {
validatorClient: client, validatorClient: client,
genesisTime: 1, genesisTime: 1,
} }
publicKeys := publicKeys(v.keyManager) publicKeys := publicKeys(t, v.keyManager)
resp := generateMockStatusResponse(publicKeys) resp := generateMockStatusResponse(publicKeys)
resp.Statuses[0].Status.Status = ethpb.ValidatorStatus_ACTIVE resp.Statuses[0].Status.Status = ethpb.ValidatorStatus_ACTIVE
resp.Statuses[1].Status.Status = ethpb.ValidatorStatus_ACTIVE resp.Statuses[1].Status.Status = ethpb.ValidatorStatus_ACTIVE
@@ -423,7 +421,7 @@ func TestWaitActivation_NotAllValidatorsActivatedOK(t *testing.T) {
validatorClient: client, validatorClient: client,
genesisTime: 1, genesisTime: 1,
} }
resp := generateMockStatusResponse(publicKeys(v.keyManager)) resp := generateMockStatusResponse(publicKeys(t, v.keyManager))
resp.Statuses[0].Status.Status = ethpb.ValidatorStatus_ACTIVE resp.Statuses[0].Status.Status = ethpb.ValidatorStatus_ACTIVE
clientStream := mock.NewMockBeaconNodeValidator_WaitForActivationClient(ctrl) clientStream := mock.NewMockBeaconNodeValidator_WaitForActivationClient(ctrl)
client.EXPECT().WaitForActivation( client.EXPECT().WaitForActivation(
@@ -674,9 +672,7 @@ func TestSaveProtections_OK(t *testing.T) {
db := dbTest.SetupDB(t, [][48]byte{pubKey1, pubKey2}) db := dbTest.SetupDB(t, [][48]byte{pubKey1, pubKey2})
cleanHistories, err := db.AttestationHistoryForPubKeys(context.Background(), [][48]byte{pubKey1, pubKey2}) cleanHistories, err := db.AttestationHistoryForPubKeys(context.Background(), [][48]byte{pubKey1, pubKey2})
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
v := validator{ v := validator{
db: db, db: db,
keyManager: testKeyManager, keyManager: testKeyManager,

View File

@@ -2,11 +2,11 @@ package kv
import ( import (
"context" "context"
"reflect"
"testing" "testing"
slashpb "github.com/prysmaticlabs/prysm/proto/slashing" slashpb "github.com/prysmaticlabs/prysm/proto/slashing"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
) )
func TestAttestationHistoryForPubKeys_EmptyVals(t *testing.T) { func TestAttestationHistoryForPubKeys_EmptyVals(t *testing.T) {
@@ -14,9 +14,7 @@ func TestAttestationHistoryForPubKeys_EmptyVals(t *testing.T) {
db := setupDB(t, pubkeys) db := setupDB(t, pubkeys)
historyForPubKeys, err := db.AttestationHistoryForPubKeys(context.Background(), pubkeys) historyForPubKeys, err := db.AttestationHistoryForPubKeys(context.Background(), pubkeys)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
newMap := make(map[uint64]uint64) newMap := make(map[uint64]uint64)
newMap[0] = params.BeaconConfig().FarFutureEpoch newMap[0] = params.BeaconConfig().FarFutureEpoch
@@ -28,13 +26,7 @@ func TestAttestationHistoryForPubKeys_EmptyVals(t *testing.T) {
cleanAttHistoryForPubKeys[pubKey] = clean cleanAttHistoryForPubKeys[pubKey] = clean
} }
if !reflect.DeepEqual(cleanAttHistoryForPubKeys, historyForPubKeys) { require.DeepEqual(t, cleanAttHistoryForPubKeys, historyForPubKeys, "Expected attestation history epoch bits to be empty")
t.Fatalf(
"Expected attestation history epoch bits to be empty, expected %v received %v",
cleanAttHistoryForPubKeys,
historyForPubKeys,
)
}
} }
func TestSaveAttestationHistory_OK(t *testing.T) { func TestSaveAttestationHistory_OK(t *testing.T) {
@@ -67,39 +59,22 @@ func TestSaveAttestationHistory_OK(t *testing.T) {
attestationHistory[pubKeys[0]] = history attestationHistory[pubKeys[0]] = history
attestationHistory[pubKeys[1]] = history2 attestationHistory[pubKeys[1]] = history2
if err := db.SaveAttestationHistoryForPubKeys(context.Background(), attestationHistory); err != nil { require.NoError(t, db.SaveAttestationHistoryForPubKeys(context.Background(), attestationHistory), "Saving attestation history failed")
t.Fatalf("Saving attestation history failed: %v", err)
}
savedHistories, err := db.AttestationHistoryForPubKeys(context.Background(), pubKeys) savedHistories, err := db.AttestationHistoryForPubKeys(context.Background(), pubKeys)
if err != nil { require.NoError(t, err, "Failed to get attestation history")
t.Fatalf("Failed to get attestation history: %v", err)
}
if savedHistories == nil || !reflect.DeepEqual(attestationHistory, savedHistories) { require.NotNil(t, savedHistories)
t.Fatalf("Expected DB to keep object the same, received: %v", history) require.DeepEqual(t, attestationHistory, savedHistories, "Expected DB to keep object the same, received: %v", history)
}
savedHistory := savedHistories[pubKeys[0]] savedHistory := savedHistories[pubKeys[0]]
if savedHistory.TargetToSource[2] != newMap[2] { require.Equal(t, newMap[2], savedHistory.TargetToSource[2], "Expected target epoch %d to have the same marked source epoch", 2)
t.Fatalf("Expected target epoch %d to have the same marked source epoch, received %d", 2, savedHistory.TargetToSource[2]) require.Equal(t, newMap[1], savedHistory.TargetToSource[1], "Expected target epoch %d to have the same marked source epoch", 1)
} require.Equal(t, newMap[0], savedHistory.TargetToSource[0], "Expected target epoch %d to have the same marked source epoch", 0)
if savedHistory.TargetToSource[1] != newMap[1] {
t.Fatalf("Expected target epoch %d to not be marked as attested for, received %d ", 1, savedHistory.TargetToSource[1])
}
if savedHistory.TargetToSource[0] != newMap[0] {
t.Fatalf("Expected target epoch %d to not be marked as attested for, received %d", 0, savedHistory.TargetToSource[0])
}
savedHistory = savedHistories[pubKeys[1]] savedHistory = savedHistories[pubKeys[1]]
if savedHistory.TargetToSource[3] != newMap2[3] { require.Equal(t, newMap2[3], savedHistory.TargetToSource[3], "Expected target epoch %d to have the same marked source epoch", 3)
t.Fatalf("Expected target epoch %d to have the same marked source epoch, received %d", 3, savedHistory.TargetToSource[3]) require.Equal(t, newMap2[2], savedHistory.TargetToSource[2], "Expected target epoch %d to have the same marked source epoch", 2)
} require.Equal(t, newMap2[1], savedHistory.TargetToSource[1], "Expected target epoch %d to have the same marked source epoch", 1)
if savedHistory.TargetToSource[2] != newMap2[2] {
t.Fatalf("Expected target epoch %d to not be marked as attested for, received %d ", 2, savedHistory.TargetToSource[2])
}
if savedHistory.TargetToSource[1] != newMap2[1] {
t.Fatalf("Expected target epoch %d to not be marked as attested for, received %d", 1, savedHistory.TargetToSource[1])
}
} }
func TestSaveAttestationHistory_Overwrites(t *testing.T) { func TestSaveAttestationHistory_Overwrites(t *testing.T) {
@@ -151,23 +126,16 @@ func TestSaveAttestationHistory_Overwrites(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
attHistory := make(map[[48]byte]*slashpb.AttestationHistory) attHistory := make(map[[48]byte]*slashpb.AttestationHistory)
attHistory[tt.pubkey] = tt.history attHistory[tt.pubkey] = tt.history
if err := db.SaveAttestationHistoryForPubKeys(context.Background(), attHistory); err != nil { require.NoError(t, db.SaveAttestationHistoryForPubKeys(context.Background(), attHistory), "Saving attestation history failed")
t.Fatalf("Saving attestation history failed: %v", err)
}
histories, err := db.AttestationHistoryForPubKeys(context.Background(), [][48]byte{tt.pubkey}) histories, err := db.AttestationHistoryForPubKeys(context.Background(), [][48]byte{tt.pubkey})
if err != nil { require.NoError(t, err, "Failed to get attestation history")
t.Fatalf("Failed to get attestation history: %v", err)
}
history := histories[tt.pubkey] history := histories[tt.pubkey]
if history == nil || !reflect.DeepEqual(history, tt.history) { require.NotNil(t, history)
t.Fatalf("Expected DB to keep object the same, received: %v", history) require.DeepEqual(t, tt.history, history, "Expected DB to keep object the same")
} require.Equal(t, tt.epoch-1, history.TargetToSource[tt.epoch],
if history.TargetToSource[tt.epoch] != tt.epoch-1 { "Expected target epoch %d to be marked with correct source epoch %d", tt.epoch, history.TargetToSource[tt.epoch])
t.Fatalf("Expected target epoch %d to be marked with correct source epoch %d", tt.epoch, history.TargetToSource[tt.epoch]) require.Equal(t, farFuture, history.TargetToSource[tt.epoch-1],
} "Expected target epoch %d to not be marked as attested for, received %d", tt.epoch-1, history.TargetToSource[tt.epoch-1])
if history.TargetToSource[tt.epoch-1] != farFuture {
t.Fatalf("Expected target epoch %d to not be marked as attested for, received %d", tt.epoch-1, history.TargetToSource[tt.epoch-1])
}
} }
} }

View File

@@ -94,34 +94,23 @@ func TestSplit(t *testing.T) {
require.NoError(t, err, "Retrieving the store for public key %v failed", encodedKey2) require.NoError(t, err, "Retrieving the store for public key %v failed", encodedKey2)
require.NotNil(t, keyStore2, "No store created for public key %v", encodedKey2) require.NotNil(t, keyStore2, "No store created for public key %v", encodedKey2)
if err := keyStore1.view(func(tx *bolt.Tx) error { err = keyStore1.view(func(tx *bolt.Tx) error {
otherKeyProposalsBucket := tx.Bucket(historicProposalsBucket).Bucket(pubKey2[:]) otherKeyProposalsBucket := tx.Bucket(historicProposalsBucket).Bucket(pubKey2[:])
if otherKeyProposalsBucket != nil { require.Equal(t, (*bolt.Bucket)(nil), otherKeyProposalsBucket, "Store for public key %v contains proposals for another key", encodedKey2)
t.Fatalf("Store for public key %v contains proposals for another key", encodedKey2)
}
otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey2[:]) otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey2[:])
if otherKeyAttestationsBucket != nil { require.Equal(t, (*bolt.Bucket)(nil), otherKeyAttestationsBucket, "Store for public key %v contains attestations for another key", encodedKey2)
t.Fatalf("Store for public key %v contains attestations for another key", encodedKey2)
}
return nil return nil
}); err != nil { })
t.Fatalf("Failed to close store: %v", err) require.NoError(t, err)
}
if err := keyStore2.view(func(tx *bolt.Tx) error { err = keyStore2.view(func(tx *bolt.Tx) error {
otherKeyProposalsBucket := tx.Bucket(historicProposalsBucket).Bucket(pubKey1[:]) otherKeyProposalsBucket := tx.Bucket(historicProposalsBucket).Bucket(pubKey1[:])
if otherKeyProposalsBucket != nil { require.Equal(t, (*bolt.Bucket)(nil), otherKeyProposalsBucket, "Store for public key %v contains proposals for another key", encodedKey1)
t.Fatalf("Store for public key %v contains proposals for another key", encodedKey1)
}
otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey1[:]) otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey1[:])
if otherKeyAttestationsBucket != nil { require.Equal(t, (*bolt.Bucket)(nil), otherKeyAttestationsBucket, "Store for public key %v contains attestations for another key", encodedKey1)
t.Fatalf("Store for public key %v contains attestations for another key", encodedKey1)
}
return nil return nil
}); err != nil { })
t.Fatalf("Failed to close store: %v", err) require.NoError(t, err)
}
assertStore(t, keyStore1, [][48]byte{pubKey1}, storeHistory1) assertStore(t, keyStore1, [][48]byte{pubKey1}, storeHistory1)
assertStore(t, keyStore2, [][48]byte{pubKey2}, storeHistory2) assertStore(t, keyStore2, [][48]byte{pubKey2}, storeHistory2)
@@ -151,20 +140,14 @@ func TestSplit_AttestationsWithoutMatchingProposalsAreSplit(t *testing.T) {
require.NoError(t, err, "Retrieving the store failed") require.NoError(t, err, "Retrieving the store failed")
require.NotNil(t, attestationsOnlyKeyStore, "No store created for public key %v", encodedKey2) require.NotNil(t, attestationsOnlyKeyStore, "No store created for public key %v", encodedKey2)
if err := attestationsOnlyKeyStore.view(func(tx *bolt.Tx) error { err = attestationsOnlyKeyStore.view(func(tx *bolt.Tx) error {
otherKeyProposalsBucket := tx.Bucket(historicProposalsBucket).Bucket(pubKey1[:]) otherKeyProposalsBucket := tx.Bucket(historicProposalsBucket).Bucket(pubKey1[:])
if otherKeyProposalsBucket != nil { require.Equal(t, (*bolt.Bucket)(nil), otherKeyProposalsBucket, "Store for public key %v contains proposals for another key", encodedKey1)
t.Fatalf("Store for public key %v contains proposals for another key", encodedKey1)
}
otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey1[:]) otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey1[:])
if otherKeyAttestationsBucket != nil { require.Equal(t, (*bolt.Bucket)(nil), otherKeyAttestationsBucket, "Store for public key %v contains attestations for another key", encodedKey1)
t.Fatalf("Store for public key %v contains attestations for another key", encodedKey1)
}
return nil return nil
}); err != nil { })
t.Fatalf("Failed to retrieve attestations: %v", err) require.NoError(t, err)
}
splitAttestationsHistory, err := splitAttestationsHistory, err :=
attestationsOnlyKeyStore.AttestationHistoryForPubKeys(context.Background(), [][48]byte{pubKey2}) attestationsOnlyKeyStore.AttestationHistoryForPubKeys(context.Background(), [][48]byte{pubKey2})

View File

@@ -49,9 +49,7 @@ func wallet(t *testing.T, opts string) keymanager.KeyManager {
func TestMultiplePassphrases(t *testing.T) { func TestMultiplePassphrases(t *testing.T) {
path := SetupWallet(t) path := SetupWallet(t)
defer func() { defer func() {
if err := os.RemoveAll(path); err != nil { assert.NoError(t, os.RemoveAll(path))
t.Log(err)
}
}() }()
tests := []struct { tests := []struct {
name string name string
@@ -92,9 +90,7 @@ func TestMultiplePassphrases(t *testing.T) {
func TestEnvPassphrases(t *testing.T) { func TestEnvPassphrases(t *testing.T) {
path := SetupWallet(t) path := SetupWallet(t)
defer func() { defer func() {
if err := os.RemoveAll(path); err != nil { assert.NoError(t, os.RemoveAll(path))
t.Log(err)
}
}() }()
err := os.Setenv("TESTENVPASSPHRASES_NEITHER", "neither") err := os.Setenv("TESTENVPASSPHRASES_NEITHER", "neither")

View File

@@ -1,7 +1,6 @@
package derived package derived
import ( import (
"bytes"
"context" "context"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
@@ -17,6 +16,8 @@ import (
"github.com/prysmaticlabs/prysm/shared/interop" "github.com/prysmaticlabs/prysm/shared/interop"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/shared/trieutil" "github.com/prysmaticlabs/prysm/shared/trieutil"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@@ -36,14 +37,10 @@ func sendDepositsTest(
depositContractAddrStr := testAcc.ContractAddr.Hex() depositContractAddrStr := testAcc.ContractAddr.Hex()
privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0, numberOfValidators) privKeys, pubKeys, err := interop.DeterministicallyGenerateKeys(0, numberOfValidators)
if err != nil { require.NoError(t, err, "Unable to generate keys")
t.Fatalf("Unable to generate keys: %v", err)
}
depositData, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys) depositData, depositDataRoots, err := interop.DepositDataFromKeys(privKeys, pubKeys)
if err != nil { require.NoError(t, err, "Unable to generate deposit data from keys")
t.Fatalf("Unable to generate deposit data from keys: %v", err)
}
for i, data := range depositData { for i, data := range depositData {
dataRoot := [32]byte{} dataRoot := [32]byte{}
@@ -57,9 +54,7 @@ func sendDepositsTest(
for j := uint64(0); j < numberOfDeposits; j++ { for j := uint64(0); j < numberOfDeposits; j++ {
tx, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot) tx, err := testAcc.Contract.Deposit(testAcc.TxOpts, data.PublicKey, data.WithdrawalCredentials, data.Signature, dataRoot)
if err != nil { require.NoError(t, err, "Unable to send transaction to contract")
t.Fatalf("unable to send transaction to contract: %v", err)
}
testAcc.Backend.Commit() testAcc.Backend.Commit()
@@ -76,9 +71,7 @@ func sendDepositsTest(
func TestSendDepositTx(t *testing.T) { func TestSendDepositTx(t *testing.T) {
testutil.ResetCache() testutil.ResetCache()
testAcc, err := contracts.Setup() testAcc, err := contracts.Setup()
if err != nil { require.NoError(t, err, "Unable to set up simulated backend")
t.Fatalf("Unable to set up simulated backend %v", err)
}
testAcc.Backend.Commit() testAcc.Backend.Commit()
@@ -96,39 +89,18 @@ func TestSendDepositTx(t *testing.T) {
} }
logs, err := testAcc.Backend.FilterLogs(context.Background(), query) logs, err := testAcc.Backend.FilterLogs(context.Background(), query)
if err != nil { require.NoError(t, err, "Unable to retrieve logs")
t.Fatalf("Unable to retrieve logs %v", err) require.NotEqual(t, 0, len(logs), "No logs")
} require.Equal(t, int(numberOfDeposits*numberOfValidators), len(logs), "No sufficient number of logs")
if len(logs) == 0 {
t.Fatal("no logs")
}
if len(logs) != int(numberOfDeposits*numberOfValidators) {
t.Fatal("No sufficient number of logs")
}
j := 0 j := 0
for i, log := range logs { for i, log := range logs {
loggedPubkey, withCreds, _, loggedSig, index, err := contracts.UnpackDepositLogData(log.Data) loggedPubkey, withCreds, _, loggedSig, index, err := contracts.UnpackDepositLogData(log.Data)
if err != nil { require.NoError(t, err, "Unable to unpack logs")
t.Fatalf("Unable to unpack logs %v", err) assert.Equal(t, uint64(i), binary.LittleEndian.Uint64(index), "Retrieved merkle tree index is incorrect %d", index)
} assert.DeepEqual(t, deposits[j].Data.PublicKey, loggedPubkey, "Pubkey is not the same as the data that was put in i: %d", i)
assert.DeepEqual(t, deposits[j].Data.Signature, loggedSig, "Proof of Possession is not the same as the data that was put in i: %d", i)
if binary.LittleEndian.Uint64(index) != uint64(i) { assert.DeepEqual(t, deposits[j].Data.WithdrawalCredentials, withCreds, "Withdrawal Credentials is not the same as the data that was put in i: %d", i)
t.Errorf("Retrieved merkle tree index is incorrect %d", index)
}
if !bytes.Equal(loggedPubkey, deposits[j].Data.PublicKey) {
t.Errorf("Pubkey is not the same as the data that was put in %v, i: %d", loggedPubkey, i)
}
if !bytes.Equal(loggedSig, deposits[j].Data.Signature) {
t.Errorf("Proof of Possession is not the same as the data that was put in %v, i: %d", loggedSig, i)
}
if !bytes.Equal(withCreds, deposits[j].Data.WithdrawalCredentials) {
t.Errorf("Withdrawal Credentials is not the same as the data that was put in %v, i: %d", withCreds, i)
}
if i == int(numberOfDeposits)-1 { if i == int(numberOfDeposits)-1 {
j++ j++
@@ -138,35 +110,21 @@ func TestSendDepositTx(t *testing.T) {
encodedDeposits := make([][]byte, numberOfValidators*numberOfDeposits) encodedDeposits := make([][]byte, numberOfValidators*numberOfDeposits)
for i := 0; i < int(numberOfValidators); i++ { for i := 0; i < int(numberOfValidators); i++ {
hashedDeposit, err := ssz.HashTreeRoot(deposits[i].Data) hashedDeposit, err := ssz.HashTreeRoot(deposits[i].Data)
if err != nil { require.NoError(t, err, "Could not tree hash deposit data")
t.Fatalf("could not tree hash deposit data: %v", err)
}
for j := 0; j < int(numberOfDeposits); j++ { for j := 0; j < int(numberOfDeposits); j++ {
encodedDeposits[i*int(numberOfDeposits)+j] = hashedDeposit[:] encodedDeposits[i*int(numberOfDeposits)+j] = hashedDeposit[:]
} }
} }
depositTrie, err := trieutil.GenerateTrieFromItems(encodedDeposits, int(params.BeaconConfig().DepositContractTreeDepth)) depositTrie, err := trieutil.GenerateTrieFromItems(encodedDeposits, int(params.BeaconConfig().DepositContractTreeDepth))
if err != nil { require.NoError(t, err, "Could not generate trie")
t.Fatalf("Could not generate trie: %v", err)
}
root := depositTrie.Root() root := depositTrie.Root()
for i, encodedDeposit := range encodedDeposits { for i, encodedDeposit := range encodedDeposits {
proof, err := depositTrie.MerkleProof(i) proof, err := depositTrie.MerkleProof(i)
if err != nil { require.NoError(t, err, "Could not generate proof")
t.Fatalf("Could not generate proof: %v", err) require.Equal(t, true, trieutil.VerifyMerkleBranch(root[:], encodedDeposit, i, proof),
} "Unable verify deposit merkle branch of deposit root for root: %#x, encodedDeposit: %#x, i : %d", root[:], encodedDeposit, i)
if ok := trieutil.VerifyMerkleBranch(
root[:],
encodedDeposit,
i,
proof,
); !ok {
t.Fatalf(
"Unable verify deposit merkle branch of deposit root for root: %#x, encodedDeposit: %#x, i : %d",
root[:], encodedDeposit, i)
}
} }
} }

View File

@@ -36,6 +36,7 @@ go_test(
"//shared/mock:go_default_library", "//shared/mock:go_default_library",
"//shared/params:go_default_library", "//shared/params:go_default_library",
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"@com_github_golang_mock//gomock:go_default_library", "@com_github_golang_mock//gomock:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library", "@com_github_urfave_cli_v2//:go_default_library",

View File

@@ -1,13 +1,11 @@
package remote package remote
import ( import (
"bytes"
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"reflect"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
@@ -18,6 +16,7 @@ import (
"github.com/prysmaticlabs/prysm/shared/mock" "github.com/prysmaticlabs/prysm/shared/mock"
"github.com/prysmaticlabs/prysm/shared/params" "github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
@@ -244,12 +243,8 @@ func TestRemoteKeymanager_Sign(t *testing.T) {
Signature: sig.Marshal(), Signature: sig.Marshal(),
}, nil /*err*/) }, nil /*err*/)
resp, err := k.Sign(context.Background(), nil) resp, err := k.Sign(context.Background(), nil)
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.DeepEqual(t, sig.Marshal(), resp.Marshal())
}
if !bytes.Equal(sig.Marshal(), resp.Marshal()) {
t.Errorf("Expected %#x, received %#x", sig.Marshal(), resp.Marshal())
}
} }
func TestRemoteKeymanager_FetchValidatingPublicKeys(t *testing.T) { func TestRemoteKeymanager_FetchValidatingPublicKeys(t *testing.T) {
@@ -280,12 +275,8 @@ func TestRemoteKeymanager_FetchValidatingPublicKeys(t *testing.T) {
ValidatingPublicKeys: make([][]byte, 0), ValidatingPublicKeys: make([][]byte, 0),
}, nil /*err*/) }, nil /*err*/)
keys, err := k.FetchValidatingPublicKeys(context.Background()) keys, err := k.FetchValidatingPublicKeys(context.Background())
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, 0, len(keys), "Expected empty response")
}
if len(keys) != 0 {
t.Errorf("Expected empty response, received %v", keys)
}
numKeys := 10 numKeys := 10
pubKeys := make([][]byte, numKeys) pubKeys := make([][]byte, numKeys)
@@ -301,14 +292,10 @@ func TestRemoteKeymanager_FetchValidatingPublicKeys(t *testing.T) {
ValidatingPublicKeys: pubKeys, ValidatingPublicKeys: pubKeys,
}, nil /*err*/) }, nil /*err*/)
keys, err = k.FetchValidatingPublicKeys(context.Background()) keys, err = k.FetchValidatingPublicKeys(context.Background())
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
rawKeys := make([][]byte, len(keys)) rawKeys := make([][]byte, len(keys))
for i := 0; i < len(rawKeys); i++ { for i := 0; i < len(rawKeys); i++ {
rawKeys[i] = keys[i][:] rawKeys[i] = keys[i][:]
} }
if !reflect.DeepEqual(pubKeys, rawKeys) { assert.DeepEqual(t, pubKeys, rawKeys)
t.Errorf("Wanted %v, received %v", pubKeys, rawKeys)
}
} }

View File

@@ -8,6 +8,7 @@ go_test(
embed = [":go_default_library"], embed = [":go_default_library"],
deps = [ deps = [
"//shared/testutil:go_default_library", "//shared/testutil:go_default_library",
"//shared/testutil/assert:go_default_library",
"//shared/testutil/require:go_default_library", "//shared/testutil/require:go_default_library",
"//validator/accounts/v1:go_default_library", "//validator/accounts/v1:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library", "@com_github_urfave_cli_v2//:go_default_library",

View File

@@ -6,6 +6,7 @@ import (
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/testutil" "github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require" "github.com/prysmaticlabs/prysm/shared/testutil/require"
v1 "github.com/prysmaticlabs/prysm/validator/accounts/v1" v1 "github.com/prysmaticlabs/prysm/validator/accounts/v1"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
@@ -18,14 +19,10 @@ func TestNode_Builds(t *testing.T) {
set.String("datadir", testutil.TempDir()+"/datadir", "the node data directory") set.String("datadir", testutil.TempDir()+"/datadir", "the node data directory")
dir := testutil.TempDir() + "/keystore1" dir := testutil.TempDir() + "/keystore1"
defer func() { defer func() {
if err := os.RemoveAll(dir); err != nil { assert.NoError(t, os.RemoveAll(dir))
t.Log(err)
}
}() }()
defer func() { defer func() {
if err := os.RemoveAll(testutil.TempDir() + "/datadir"); err != nil { assert.NoError(t, os.RemoveAll(testutil.TempDir()+"/datadir"))
t.Log(err)
}
}() }()
set.String("keystore-path", dir, "path to keystore") set.String("keystore-path", dir, "path to keystore")
set.String("password", "1234", "validator account password") set.String("password", "1234", "validator account password")

View File

@@ -5,6 +5,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
) )
@@ -22,18 +23,14 @@ func TestServer_JWTInterceptor_Verify(t *testing.T) {
return nil, nil return nil, nil
} }
token, _, err := s.createTokenString() token, _, err := s.createTokenString()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ctxMD := map[string][]string{ ctxMD := map[string][]string{
"authorization": {token}, "authorization": {token},
} }
ctx := context.Background() ctx := context.Background()
ctx = metadata.NewIncomingContext(ctx, ctxMD) ctx = metadata.NewIncomingContext(ctx, ctxMD)
_, err = interceptor(ctx, "xyz", unaryInfo, unaryHandler) _, err = interceptor(ctx, "xyz", unaryInfo, unaryHandler)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
} }
func TestServer_JWTInterceptor_BadToken(t *testing.T) { func TestServer_JWTInterceptor_BadToken(t *testing.T) {
@@ -53,9 +50,7 @@ func TestServer_JWTInterceptor_BadToken(t *testing.T) {
jwtKey: []byte("badTestKey"), jwtKey: []byte("badTestKey"),
} }
token, _, err := badServer.createTokenString() token, _, err := badServer.createTokenString()
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ctxMD := map[string][]string{ ctxMD := map[string][]string{
"authorization": {token}, "authorization": {token},
} }