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

View File

@@ -59,13 +59,12 @@ func TestStore_OnAttestation(t *testing.T) {
BlkWithValidStateRoot, err := stateutil.BlockRoot(BlkWithValidState.Block)
require.NoError(t, err)
s = testutil.NewBeaconState()
if err := s.SetFork(&pb.Fork{
err = s.SetFork(&pb.Fork{
Epoch: 0,
CurrentVersion: 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))
tests := []struct {
@@ -182,13 +181,12 @@ func TestStore_OnAttestationUsingCheckptCache(t *testing.T) {
BlkWithValidStateRoot, err := stateutil.BlockRoot(BlkWithValidState.Block)
require.NoError(t, err)
s = testutil.NewBeaconState()
if err := s.SetFork(&pb.Fork{
err = s.SetFork(&pb.Fork{
Epoch: 0,
CurrentVersion: 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))
tests := []struct {
@@ -389,13 +387,8 @@ func TestAttEpoch_MatchPrevEpoch(t *testing.T) {
service, err := NewService(ctx, cfg)
require.NoError(t, err)
if err := service.verifyAttTargetEpoch(
ctx,
0,
params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot,
&ethpb.Checkpoint{}); err != nil {
t.Error(err)
}
nowTime := params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().SecondsPerSlot
require.NoError(t, service.verifyAttTargetEpoch(ctx, 0, nowTime, &ethpb.Checkpoint{}))
}
func TestAttEpoch_MatchCurrentEpoch(t *testing.T) {
@@ -406,13 +399,8 @@ func TestAttEpoch_MatchCurrentEpoch(t *testing.T) {
service, err := NewService(ctx, cfg)
require.NoError(t, err)
if err := service.verifyAttTargetEpoch(
ctx,
0,
params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot,
&ethpb.Checkpoint{Epoch: 1}); err != nil {
t.Error(err)
}
nowTime := params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().SecondsPerSlot
require.NoError(t, service.verifyAttTargetEpoch(ctx, 0, nowTime, &ethpb.Checkpoint{Epoch: 1}))
}
func TestAttEpoch_NotMatch(t *testing.T) {
@@ -423,14 +411,9 @@ func TestAttEpoch_NotMatch(t *testing.T) {
service, err := NewService(ctx, cfg)
require.NoError(t, err)
if err := service.verifyAttTargetEpoch(
ctx,
0,
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")
}
nowTime := 2 * params.BeaconConfig().SlotsPerEpoch * params.BeaconConfig().SecondsPerSlot
err = service.verifyAttTargetEpoch(ctx, 0, nowTime, &ethpb.Checkpoint{})
assert.ErrorContains(t, "target epoch 0 does not match current epoch 2 or prev epoch 1", err)
}
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, newCp, service.CurrentJustifiedCheckpt(), "Incorrect current justified checkpoint in cache")
cp, err := service.beaconDB.JustifiedCheckpoint(ctx)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
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
}
tests := []struct {
name string
args args
wantErr bool
check func(*testing.T, *Service)
name string
args args
wantedErr string
check func(*testing.T, *Service)
}{
{
name: "applies block with state transition",
@@ -143,9 +143,11 @@ func TestService_ReceiveBlock(t *testing.T) {
s.finalizedCheckpt = &ethpb.Checkpoint{Root: gRoot[:]}
root, err := stateutil.BlockRoot(tt.args.block.Block)
require.NoError(t, err)
if err := s.ReceiveBlock(ctx, tt.args.block, root); (err != nil) != tt.wantErr {
t.Errorf("ReceiveBlock() error = %v, wantErr %v", err, tt.wantErr)
err = s.ReceiveBlock(ctx, tt.args.block, root)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
tt.check(t, s)
}
})
@@ -201,9 +203,7 @@ func TestService_ReceiveBlockInitialSync(t *testing.T) {
genesis, keys := testutil.DeterministicGenesisState(t, 64)
genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock {
blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot)
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
return blk
}
@@ -211,10 +211,10 @@ func TestService_ReceiveBlockInitialSync(t *testing.T) {
block *ethpb.SignedBeaconBlock
}
tests := []struct {
name string
args args
wantErr bool
check func(*testing.T, *Service)
name string
args args
wantedErr string
check func(*testing.T, *Service)
}{
{
name: "applies block with state transition",
@@ -266,9 +266,11 @@ func TestService_ReceiveBlockInitialSync(t *testing.T) {
root, err := stateutil.BlockRoot(tt.args.block.Block)
require.NoError(t, err)
if err := s.ReceiveBlockInitialSync(ctx, tt.args.block, root); (err != nil) != tt.wantErr {
t.Errorf("ReceiveBlockInitialSync() error = %v, wantErr %v", err, tt.wantErr)
err = s.ReceiveBlockInitialSync(ctx, tt.args.block, root)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
tt.check(t, s)
}
})
@@ -281,9 +283,7 @@ func TestService_ReceiveBlockBatch(t *testing.T) {
genesis, keys := testutil.DeterministicGenesisState(t, 64)
genFullBlock := func(t *testing.T, conf *testutil.BlockGenConfig, slot uint64) *ethpb.SignedBeaconBlock {
blk, err := testutil.GenerateFullBlock(genesis, keys, conf, slot)
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
return blk
}
@@ -291,10 +291,10 @@ func TestService_ReceiveBlockBatch(t *testing.T) {
block *ethpb.SignedBeaconBlock
}
tests := []struct {
name string
args args
wantErr bool
check func(*testing.T, *Service)
name string
args args
wantedErr string
check func(*testing.T, *Service)
}{
{
name: "applies block with state transition",
@@ -347,9 +347,11 @@ func TestService_ReceiveBlockBatch(t *testing.T) {
require.NoError(t, err)
blks := []*ethpb.SignedBeaconBlock{tt.args.block}
roots := [][32]byte{root}
if err := s.ReceiveBlockBatch(ctx, blks, roots); (err != nil) != tt.wantErr {
t.Errorf("ReceiveBlockBatch() error = %v, wantErr %v", err, tt.wantErr)
err = s.ReceiveBlockBatch(ctx, blks, roots)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
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.
if err := cfg.StateGen.SaveState(ctx, bytesutil.ToBytes32(bState.FinalizedCheckpoint().Root), bState); err != nil {
t.Fatal(err)
}
require.NoError(t, cfg.StateGen.SaveState(ctx, bytesutil.ToBytes32(bState.FinalizedCheckpoint().Root), bState))
chainService, err := NewService(ctx, cfg)
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, genesisRoot))
require.NoError(t, db.SaveBlock(ctx, headBlock))
if err := db.SaveFinalizedCheckpoint(ctx, &ethpb.Checkpoint{
Epoch: helpers.SlotToEpoch(finalizedSlot),
Root: headRoot[:],
}); err != nil {
t.Fatal(err)
}
require.NoError(t, db.SaveFinalizedCheckpoint(ctx, &ethpb.Checkpoint{Epoch: helpers.SlotToEpoch(finalizedSlot), Root: headRoot[:]}))
c := &Service{beaconDB: db, stateGen: stategen.New(db, sc)}
require.NoError(t, c.initializeChainInfo(ctx))
headBlk, err := c.HeadBlock(ctx)

View File

@@ -1,7 +1,6 @@
package epoch
import (
"bytes"
"testing"
"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")
// Verify randao is correctly updated in the right position.
if mix, err := newS.RandaoMixAtIndex(ne); err != nil || bytes.Equal(mix, params.BeaconConfig().ZeroHash[:]) {
t.Error("latest RANDAO still zero hashes")
}
mix, err := newS.RandaoMixAtIndex(ne)
assert.NoError(t, err)
assert.DeepNotEqual(t, params.BeaconConfig().ZeroHash[:], mix, "latest RANDAO still zero hashes")
// Verify historical root accumulator was appended.
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
}
tests := []struct {
name string
args args
wantErr bool
name string
args args
wantedErr string
}{
{
name: "attestation.slot == current_slot",
@@ -164,7 +164,6 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 15,
genesisTime: roughtime.Now().Add(-15 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second),
},
wantErr: false,
},
{
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,
).Add(-(time.Duration(params.BeaconConfig().SecondsPerSlot/2) * time.Second)),
},
wantErr: false,
},
{
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,
).Add(-200 * time.Millisecond),
},
wantErr: false,
},
{
name: "attestation.slot > current_slot",
@@ -192,7 +189,7 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 16,
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",
@@ -200,7 +197,7 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 100 - params.BeaconNetworkConfig().AttestationPropagationSlotRange - 1,
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",
@@ -208,7 +205,6 @@ func Test_ValidateAttestationTime(t *testing.T) {
attSlot: 100 - params.BeaconNetworkConfig().AttestationPropagationSlotRange,
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",
@@ -218,13 +214,15 @@ func Test_ValidateAttestationTime(t *testing.T) {
-100 * time.Duration(params.BeaconConfig().SecondsPerSlot) * time.Second,
).Add(200 * time.Millisecond),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := helpers.ValidateAttestationTime(tt.args.attSlot, tt.args.genesisTime); (err != nil) != tt.wantErr {
t.Errorf("validateAggregateAttTime() error = %v, wantErr %v", err, tt.wantErr)
err := helpers.ValidateAttestationTime(tt.args.attSlot, tt.args.genesisTime)
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))
err := VerifyAttestationBitfieldLengths(state, tt.attestation)
if tt.verificationFailure {
if err == nil {
t.Error("verification succeeded when it was supposed to fail")
}
continue
}
if err != nil {
t.Errorf("%d Failed to verify bitfield: %v", i, err)
continue
assert.NotNil(t, err, "Verification succeeded when it was supposed to fail")
} else {
assert.NoError(t, err, "%d Failed to verify bitfield: %v", i, err)
}
}
}

View File

@@ -2,7 +2,6 @@ package helpers
import (
"math"
"reflect"
"testing"
"time"
@@ -190,10 +189,10 @@ func TestSlotToTime(t *testing.T) {
slot uint64
}
tests := []struct {
name string
args args
want time.Time
wantErr bool
name string
args args
want time.Time
wantedErr string
}{
{
name: "slot_0",
@@ -201,8 +200,7 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 0,
slot: 0,
},
want: time.Unix(0, 0),
wantErr: false,
want: time.Unix(0, 0),
},
{
name: "slot_1",
@@ -210,8 +208,7 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 0,
slot: 1,
},
want: time.Unix(int64(1*params.BeaconConfig().SecondsPerSlot), 0),
wantErr: false,
want: time.Unix(int64(1*params.BeaconConfig().SecondsPerSlot), 0),
},
{
name: "slot_12",
@@ -219,8 +216,7 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 500,
slot: 12,
},
want: time.Unix(500+int64(12*params.BeaconConfig().SecondsPerSlot), 0),
wantErr: false,
want: time.Unix(500+int64(12*params.BeaconConfig().SecondsPerSlot), 0),
},
{
name: "overflow",
@@ -228,13 +224,17 @@ func TestSlotToTime(t *testing.T) {
genesisTimeSec: 500,
slot: math.MaxUint64,
},
wantErr: true,
wantedErr: "is in the far distant future",
},
}
for _, tt := range tests {
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) {
t.Errorf("SlotToTime() = %v, want %v", got, tt.want)
got, err := SlotToTime(tt.args.genesisTimeSec, tt.args.slot)
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
}
tests := []struct {
name string
args args
wantErr bool
name string
args args
wantedErr string
}{
{
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(),
slot: 3,
},
wantErr: false,
},
{
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(),
slot: 5,
},
wantErr: false,
},
{
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(),
slot: 6,
},
wantErr: true,
wantedErr: "could not process slot from the future",
},
}
for _, tt := range tests {
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 {
t.Errorf("VerifySlotTime() error = %v, wantErr %v", err, tt.wantErr)
err := VerifySlotTime(uint64(tt.args.genesisTime), tt.args.slot, tt.args.timeTolerance)
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
}
tests := []struct {
name string
args args
want []uint64
wantErr bool
name string
args args
want []uint64
wantedErr string
}{
{
name: "all_active_epoch_10",
@@ -558,8 +558,8 @@ func TestActiveValidatorIndices(t *testing.T) {
s, err := beaconstate.InitializeFromProto(tt.args.state)
require.NoError(t, err)
got, err := ActiveValidatorIndices(s, tt.args.epoch)
if (err != nil) != tt.wantErr {
t.Errorf("ActiveValidatorIndices() error = %v, wantErr %v", err, tt.wantErr)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
return
}
assert.DeepEqual(t, tt.want, got, "ActiveValidatorIndices()")
@@ -576,10 +576,10 @@ func TestComputeProposerIndex(t *testing.T) {
seed [32]byte
}
tests := []struct {
name string
args args
want uint64
wantErr bool
name string
args args
want uint64
wantedErr string
}{
{
name: "all_active_indices",
@@ -624,7 +624,7 @@ func TestComputeProposerIndex(t *testing.T) {
indices: []uint64{},
seed: seed,
},
wantErr: true,
wantedErr: "empty active indices list",
},
{
name: "active_indices_out_of_range",
@@ -639,7 +639,7 @@ func TestComputeProposerIndex(t *testing.T) {
indices: []uint64{100},
seed: seed,
},
wantErr: true,
wantedErr: "active index out of range",
},
{
name: "second_half_active",
@@ -681,13 +681,10 @@ func TestComputeProposerIndex(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
bState := &pb.BeaconState{Validators: tt.args.validators}
stTrie, err := beaconstate.InitializeFromProtoUnsafe(bState)
if err != nil {
t.Error(err)
return
}
require.NoError(t, err)
got, err := ComputeProposerIndex(stTrie, tt.args.indices, tt.args.seed)
if (err != nil) != tt.wantErr {
t.Errorf("ComputeProposerIndex() error = %v, wantErr %v", err, tt.wantErr)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
return
}
assert.Equal(t, tt.want, got, "ComputeProposerIndex()")

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,6 @@
package kv
import (
"reflect"
"sort"
"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()}
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}
if err := cache.SaveUnaggregatedAttestations(atts); err != nil {
t.Fatal(err)
}
if err := cache.AggregateUnaggregatedAttestations(); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveUnaggregatedAttestations(atts))
require.NoError(t, cache.AggregateUnaggregatedAttestations())
if len(cache.AggregatedAttestationsBySlotIndex(1, 0)) != 1 {
t.Fatal("Did not aggregate correctly")
}
if len(cache.AggregatedAttestationsBySlotIndex(2, 0)) != 1 {
t.Fatal("Did not aggregate correctly")
}
require.Equal(t, 1, len(cache.AggregatedAttestationsBySlotIndex(1, 0)), "Did not aggregate correctly")
require.Equal(t, 1, len(cache.AggregatedAttestationsBySlotIndex(2, 0)), "Did not aggregate correctly")
}
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) {
cache := NewAttCaches()
cache.seenAtt.Set(string(r[:]), []bitfield.Bitlist{{0xff}}, c.DefaultExpiration)
if len(cache.unAggregatedAtt) != 0 {
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
assert.Equal(t, 0, len(cache.unAggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
err := cache.SaveAggregatedAttestation(tt.att)
if tt.wantErrString != "" && (err == nil || err.Error() != tt.wantErrString) {
t.Errorf("Did not receive wanted error, want: %q, got: %v", tt.wantErrString, err)
return
}
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())
if tt.wantErrString != "" {
assert.ErrorContains(t, tt.wantErrString, err)
} else {
assert.NoError(t, err)
}
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 {
t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches()
if len(cache.aggregatedAtt) != 0 {
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
assert.Equal(t, 0, len(cache.aggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
err := cache.SaveAggregatedAttestations(tt.atts)
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())
if tt.wantErrString != "" {
assert.ErrorContains(t, tt.wantErrString, err)
} else {
assert.NoError(t, err)
}
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}
for _, att := range atts {
if err := cache.SaveAggregatedAttestation(att); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveAggregatedAttestation(att))
}
returned := cache.AggregatedAttestations()
@@ -190,23 +165,16 @@ func TestKV_Aggregated_AggregatedAttestations(t *testing.T) {
func TestKV_Aggregated_DeleteAggregatedAttestation(t *testing.T) {
t.Run("nil attestation", func(t *testing.T) {
cache := NewAttCaches()
if err := cache.DeleteAggregatedAttestation(nil); err != nil {
t.Error(err)
}
assert.NoError(t, cache.DeleteAggregatedAttestation(nil))
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b10101}}
if err := cache.DeleteAggregatedAttestation(att); err != nil {
t.Error(err)
}
assert.NoError(t, cache.DeleteAggregatedAttestation(att))
})
t.Run("non aggregated attestation", func(t *testing.T) {
cache := NewAttCaches()
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1001}, Data: &ethpb.AttestationData{Slot: 2}}
err := cache.DeleteAggregatedAttestation(att)
wantErr := "attestation is not aggregated"
if err == nil || err.Error() != wantErr {
t.Errorf("Did not receive wanted error, want: %q, got: %v", wantErr, err)
}
assert.ErrorContains(t, "attestation is not aggregated", err)
})
t.Run("invalid hash", func(t *testing.T) {
@@ -220,17 +188,13 @@ func TestKV_Aggregated_DeleteAggregatedAttestation(t *testing.T) {
}
err := cache.DeleteAggregatedAttestation(att)
wantErr := "could not tree hash attestation data: incorrect fixed bytes marshalling"
if err == nil || err.Error() != wantErr {
t.Errorf("Did not receive wanted error, want: %q, got: %v", wantErr, err)
}
assert.ErrorContains(t, wantErr, err)
})
t.Run("nonexistent attestation", func(t *testing.T) {
cache := NewAttCaches()
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1111}, Data: &ethpb.AttestationData{Slot: 2}}
if err := cache.DeleteAggregatedAttestation(att); err != nil {
t.Error(err)
}
assert.NoError(t, cache.DeleteAggregatedAttestation(att))
})
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}}
att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b10101}}
atts := []*ethpb.Attestation{att1, att2, att3, att4}
if err := cache.SaveAggregatedAttestations(atts); err != nil {
t.Fatal(err)
}
if err := cache.DeleteAggregatedAttestation(att1); err != nil {
t.Fatal(err)
}
if err := cache.DeleteAggregatedAttestation(att3); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveAggregatedAttestations(atts))
require.NoError(t, cache.DeleteAggregatedAttestation(att1))
require.NoError(t, cache.DeleteAggregatedAttestation(att3))
returned := cache.AggregatedAttestations()
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}}
att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 2}, AggregationBits: bitfield.Bitlist{0b110101}}
atts := []*ethpb.Attestation{att1, att2, att3, att4}
if err := cache.SaveAggregatedAttestations(atts); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveAggregatedAttestations(atts))
if cache.AggregatedAttestationCount() != 2 {
t.Error("Unexpected number of atts")
}
if err := cache.DeleteAggregatedAttestation(att4); err != nil {
t.Fatal(err)
}
assert.Equal(t, 2, cache.AggregatedAttestationCount(), "Unexpected number of atts")
require.NoError(t, cache.DeleteAggregatedAttestation(att4))
returned := cache.AggregatedAttestations()
wanted := []*ethpb.Attestation{att1, att2}
@@ -456,27 +407,19 @@ func TestKV_Aggregated_HasAggregatedAttestation(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches()
if err := cache.SaveAggregatedAttestations(tt.existing); err != nil {
t.Error(err)
}
require.NoError(t, cache.SaveAggregatedAttestations(tt.existing))
result, err := cache.HasAggregatedAttestation(tt.input)
require.NoError(t, err)
if result != tt.want {
t.Errorf("Result = %v, wanted = %v", result, tt.want)
}
assert.Equal(t, tt.want, result)
// Same test for block attestations
cache = NewAttCaches()
if err := cache.SaveBlockAttestations(tt.existing); err != nil {
t.Error(err)
}
assert.NoError(t, cache.SaveBlockAttestations(tt.existing))
result, err = cache.HasAggregatedAttestation(tt.input)
require.NoError(t, err)
if result != tt.want {
t.Errorf("Result = %v, wanted = %v", result, tt.want)
}
assert.Equal(t, tt.want, result)
})
}
}
@@ -489,15 +432,12 @@ func TestKV_Aggregated_DuplicateAggregatedAttestations(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2}
for _, att := range atts {
if err := cache.SaveAggregatedAttestation(att); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveAggregatedAttestation(att))
}
returned := cache.AggregatedAttestations()
// It should have only returned att2.
if !reflect.DeepEqual(att2, returned[0]) || len(returned) != 1 {
t.Error("Did not receive correct aggregated atts")
}
assert.DeepEqual(t, att2, returned[0], "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"
"github.com/prysmaticlabs/prysm/beacon-chain/operations/attestations/kv"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
)
func BenchmarkAttCaches(b *testing.B) {
@@ -13,11 +14,7 @@ func BenchmarkAttCaches(b *testing.B) {
att := &ethpb.Attestation{}
for i := 0; i < b.N; i++ {
if err := ac.SaveUnaggregatedAttestation(att); err != nil {
b.Error(err)
}
if err := ac.DeleteAggregatedAttestation(att); err != nil {
b.Error(err)
}
assert.NoError(b, ac.SaveUnaggregatedAttestation(att))
assert.NoError(b, ac.DeleteAggregatedAttestation(att))
}
}

View File

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

View File

@@ -7,6 +7,7 @@ import (
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
func TestKV_Forkchoice_CanSaveRetrieve(t *testing.T) {
@@ -18,9 +19,7 @@ func TestKV_Forkchoice_CanSaveRetrieve(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts {
if err := cache.SaveForkchoiceAttestation(att); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveForkchoiceAttestation(att))
}
returned := cache.ForkchoiceAttestations()
@@ -41,17 +40,11 @@ func TestKV_Forkchoice_CanDelete(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts {
if err := cache.SaveForkchoiceAttestation(att); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveForkchoiceAttestation(att))
}
if err := cache.DeleteForkchoiceAttestation(att1); err != nil {
t.Fatal(err)
}
if err := cache.DeleteForkchoiceAttestation(att3); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.DeleteForkchoiceAttestation(att1))
require.NoError(t, cache.DeleteForkchoiceAttestation(att3))
returned := cache.ForkchoiceAttestations()
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) {
cache := NewAttCaches()
cache.seenAtt.Set(string(r[:]), []bitfield.Bitlist{{0xff}}, c.DefaultExpiration)
if len(cache.unAggregatedAtt) != 0 {
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
assert.Equal(t, 0, len(cache.unAggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
err := cache.SaveUnaggregatedAttestation(tt.att)
if tt.wantErrString != "" && (err == nil || err.Error() != tt.wantErrString) {
t.Errorf("Did not receive wanted error, want: %q, got: %v", tt.wantErrString, err)
return
}
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())
if tt.wantErrString != "" {
assert.ErrorContains(t, tt.wantErrString, err)
} else {
assert.NoError(t, err)
}
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 {
t.Run(tt.name, func(t *testing.T) {
cache := NewAttCaches()
if len(cache.unAggregatedAtt) != 0 {
t.Errorf("Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
}
assert.Equal(t, 0, len(cache.unAggregatedAtt), "Invalid start pool, atts: %d", len(cache.unAggregatedAtt))
err := cache.SaveUnaggregatedAttestations(tt.atts)
if tt.wantErrString != "" && (err == nil || err.Error() != tt.wantErrString) {
t.Errorf("Did not receive wanted error, want: %q, got: %v", tt.wantErrString, err)
}
if tt.wantErrString == "" && err != nil {
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())
if tt.wantErrString != "" {
assert.ErrorContains(t, tt.wantErrString, err)
} else {
assert.NoError(t, err)
}
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) {
t.Run("nil attestation", func(t *testing.T) {
cache := NewAttCaches()
if err := cache.DeleteUnaggregatedAttestation(nil); err != nil {
t.Error(err)
}
assert.NoError(t, cache.DeleteUnaggregatedAttestation(nil))
})
t.Run("aggregated attestation", func(t *testing.T) {
cache := NewAttCaches()
att := &ethpb.Attestation{AggregationBits: bitfield.Bitlist{0b1111}, Data: &ethpb.AttestationData{Slot: 2}}
err := cache.DeleteUnaggregatedAttestation(att)
wantErr := "attestation is aggregated"
if err == nil || err.Error() != wantErr {
t.Errorf("Did not receive wanted error, want: %q, got: %v", wantErr, err)
}
assert.ErrorContains(t, "attestation is aggregated", err)
})
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}}
att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 3}, AggregationBits: bitfield.Bitlist{0b110}}
atts := []*ethpb.Attestation{att1, att2, att3}
if err := cache.SaveUnaggregatedAttestations(atts); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveUnaggregatedAttestations(atts))
for _, att := range atts {
if err := cache.DeleteUnaggregatedAttestation(att); err != nil {
t.Error(err)
}
assert.NoError(t, cache.DeleteUnaggregatedAttestation(att))
}
returned, err := cache.UnaggregatedAttestations()
require.NoError(t, err)
@@ -187,9 +162,7 @@ func TestKV_Unaggregated_UnaggregatedAttestationsBySlotIndex(t *testing.T) {
atts := []*ethpb.Attestation{att1, att2, att3}
for _, att := range atts {
if err := cache.SaveUnaggregatedAttestation(att); err != nil {
t.Fatal(err)
}
require.NoError(t, cache.SaveUnaggregatedAttestation(att))
}
returned := cache.UnaggregatedAttestationsBySlotIndex(1, 1)

View File

@@ -83,19 +83,10 @@ func TestBatchAttestations_Multiple(t *testing.T) {
Source: &ethpb.Checkpoint{Root: mockRoot[:]},
Target: &ethpb.Checkpoint{Root: mockRoot[:]}}, AggregationBits: bitfield.Bitlist{0b100011}, Signature: sig.Marshal()}, // Duplicated
}
if err := s.pool.SaveUnaggregatedAttestations(unaggregatedAtts); err != nil {
t.Fatal(err)
}
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)
}
require.NoError(t, s.pool.SaveUnaggregatedAttestations(unaggregatedAtts))
require.NoError(t, s.pool.SaveAggregatedAttestations(aggregatedAtts))
require.NoError(t, s.pool.SaveBlockAttestations(blockAtts))
require.NoError(t, s.batchForkChoiceAtts(context.Background()))
wanted, err := attaggregation.Aggregate([]*ethpb.Attestation{aggregatedAtts[0], blockAtts[0]})
require.NoError(t, err)
@@ -106,9 +97,7 @@ func TestBatchAttestations_Multiple(t *testing.T) {
require.NoError(t, err)
wanted = append(wanted, aggregated...)
if err := s.pool.AggregateUnaggregatedAttestations(); err != nil {
return
}
require.NoError(t, s.pool.AggregateUnaggregatedAttestations())
received := s.pool.ForkchoiceAttestations()
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{0b110010}, Signature: sig.Marshal()}, // Duplicated
}
if err := s.pool.SaveUnaggregatedAttestations(unaggregatedAtts); err != nil {
t.Fatal(err)
}
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)
}
require.NoError(t, s.pool.SaveUnaggregatedAttestations(unaggregatedAtts))
require.NoError(t, s.pool.SaveAggregatedAttestations(aggregatedAtts))
require.NoError(t, s.pool.SaveBlockAttestations(blockAtts))
require.NoError(t, s.batchForkChoiceAtts(context.Background()))
wanted, err := attaggregation.Aggregate(append(aggregatedAtts, unaggregatedAtts...))
require.NoError(t, err)
@@ -189,9 +167,7 @@ func TestAggregateAndSaveForkChoiceAtts_Single(t *testing.T) {
atts := []*ethpb.Attestation{
{Data: d, AggregationBits: bitfield.Bitlist{0b101}, Signature: sig.Marshal()},
{Data: d, AggregationBits: bitfield.Bitlist{0b110}, Signature: sig.Marshal()}}
if err := s.aggregateAndSaveForkChoiceAtts(atts); err != nil {
t.Fatal(err)
}
require.NoError(t, s.aggregateAndSaveForkChoiceAtts(atts))
wanted, err := attaggregation.Aggregate(atts)
require.NoError(t, err)
@@ -211,37 +187,27 @@ func TestAggregateAndSaveForkChoiceAtts_Multiple(t *testing.T) {
Target: &ethpb.Checkpoint{Root: mockRoot[:]},
}
d1, ok := proto.Clone(d).(*ethpb.AttestationData)
if !ok {
t.Fatal("Entity is not of type *ethpb.AttestationData")
}
require.Equal(t, true, ok, "Entity is not of type *ethpb.AttestationData")
d1.Slot = 1
d2, ok := proto.Clone(d).(*ethpb.AttestationData)
if !ok {
t.Fatal("Entity is not of type *ethpb.AttestationData")
}
require.Equal(t, true, ok, "Entity is not of type *ethpb.AttestationData")
d2.Slot = 2
atts1 := []*ethpb.Attestation{
{Data: d, AggregationBits: bitfield.Bitlist{0b101}, Signature: sig.Marshal()},
{Data: d, AggregationBits: bitfield.Bitlist{0b110}, Signature: sig.Marshal()},
}
if err := s.aggregateAndSaveForkChoiceAtts(atts1); err != nil {
t.Fatal(err)
}
require.NoError(t, s.aggregateAndSaveForkChoiceAtts(atts1))
atts2 := []*ethpb.Attestation{
{Data: d1, AggregationBits: bitfield.Bitlist{0b10110}, Signature: sig.Marshal()},
{Data: d1, AggregationBits: bitfield.Bitlist{0b11100}, Signature: sig.Marshal()},
{Data: d1, AggregationBits: bitfield.Bitlist{0b11000}, Signature: sig.Marshal()},
}
if err := s.aggregateAndSaveForkChoiceAtts(atts2); err != nil {
t.Fatal(err)
}
require.NoError(t, s.aggregateAndSaveForkChoiceAtts(atts2))
att3 := []*ethpb.Attestation{
{Data: d2, AggregationBits: bitfield.Bitlist{0b1100}, Signature: sig.Marshal()},
}
if err := s.aggregateAndSaveForkChoiceAtts(att3); err != nil {
t.Fatal(err)
}
require.NoError(t, s.aggregateAndSaveForkChoiceAtts(att3))
wanted, err := attaggregation.Aggregate(atts1)
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 */}
got, err := s.seen(att1)
require.NoError(t, err)
if got {
t.Error("Wanted false, got true")
}
assert.Equal(t, false, got)
att2 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x17} /* 0b00010111 */}
got, err = s.seen(att2)
require.NoError(t, err)
if got {
t.Error("Wanted false, got true")
}
assert.Equal(t, false, got)
att3 := &ethpb.Attestation{Data: &ethpb.AttestationData{}, Signature: []byte{'A'}, AggregationBits: bitfield.Bitlist{0x17} /* 0b00010111 */}
got, err = s.seen(att3)
require.NoError(t, err)
if !got {
t.Error("Wanted true, got false")
}
assert.Equal(t, true, got)
}
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: 1}, AggregationBits: bitfield.Bitlist{0b1000, 0b1}},
}
if err := s.pool.SaveUnaggregatedAttestations(atts); err != nil {
t.Fatal(err)
}
if s.pool.UnaggregatedAttestationCount() != 2 {
t.Fatalf("Unexpected number of attestations: %d", s.pool.UnaggregatedAttestationCount())
}
require.NoError(t, s.pool.SaveUnaggregatedAttestations(atts))
require.Equal(t, 2, s.pool.UnaggregatedAttestationCount(), "Unexpected number of attestations")
atts = []*ethpb.Attestation{
{Data: &ethpb.AttestationData{Slot: 0}, AggregationBits: bitfield.Bitlist{0b1101, 0b1}},
{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1101, 0b1}},
}
if err := s.pool.SaveAggregatedAttestations(atts); err != nil {
t.Fatal(err)
}
require.NoError(t, s.pool.SaveAggregatedAttestations(atts))
assert.Equal(t, 2, s.pool.AggregatedAttestationCount())
if err := s.pool.SaveBlockAttestations(atts); err != nil {
t.Fatal(err)
}
require.NoError(t, s.pool.SaveBlockAttestations(atts))
// Rewind back one epoch worth of time.
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}}
att4 := &ethpb.Attestation{Data: &ethpb.AttestationData{Slot: 1}, AggregationBits: bitfield.Bitlist{0b1110}}
atts := []*ethpb.Attestation{att1, att2, att3, att4}
if err := s.pool.SaveAggregatedAttestations(atts); err != nil {
t.Fatal(err)
}
if err := s.pool.SaveBlockAttestations(atts); err != nil {
t.Fatal(err)
}
require.NoError(t, s.pool.SaveAggregatedAttestations(atts))
require.NoError(t, s.pool.SaveBlockAttestations(atts))
// Rewind back one epoch worth of time.
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.
s.genesisTime = uint64(roughtime.Now().Unix()) - params.BeaconConfig().SlotsPerEpoch*params.BeaconConfig().SecondsPerSlot
if !s.expired(0) {
t.Error("Should expired")
}
if s.expired(1) {
t.Error("Should not expired")
}
assert.Equal(t, true, s.expired(0), "Should be expired")
assert.Equal(t, false, s.expired(1), "Should not be expired")
}

View File

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

View File

@@ -44,7 +44,6 @@ go_test(
"//shared/testutil:go_default_library",
"//shared/testutil/assert: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",
],
)

View File

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

View File

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

View File

@@ -20,9 +20,7 @@ func TestRelayAddrs_OnlyFactory(t *testing.T) {
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"
if result[1].String() != expected {
t.Errorf("Address at index 1 (%s) is not the expected p2p-circuit address", result[1].String())
}
assert.Equal(t, expected, result[1].String(), "Address at index 1 (%s) is not the expected p2p-circuit address", result[1].String())
}
func TestRelayAddrs_UseNonRelayAddrs(t *testing.T) {
@@ -37,9 +35,7 @@ func TestRelayAddrs_UseNonRelayAddrs(t *testing.T) {
addrs := make([]ma.Multiaddr, len(expected))
for i, addr := range expected {
a, err := ma.NewMultiaddr(addr)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
addrs[i] = a
}

View File

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

View File

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

View File

@@ -11,6 +11,7 @@ import (
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
)
@@ -18,9 +19,7 @@ func TestPrivateKeyLoading(t *testing.T) {
file, err := ioutil.TempFile(testutil.TempDir(), "key")
require.NoError(t, err)
defer func() {
if err := os.Remove(file.Name()); err != nil {
t.Log(err)
}
assert.NoError(t, os.Remove(file.Name()))
}()
key, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
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 = net.ParseIP("127.0.0.1")
listen, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr, port))
if err != nil {
t.Fatalf("Failed to p2p listen: %v", err)
}
require.NoError(t, err, "Failed to p2p listen")
h, err := libp2p.New(context.Background(), []libp2p.Option{privKeyOption(pkey), libp2p.ListenAddrs(listen)}...)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
return h, pkey, ipAddr
}

View File

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

View File

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

View File

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

View File

@@ -40,9 +40,7 @@ func TestServer_GetValidatorActiveSetChanges_CannotRequestFutureEpoch(t *testing
db, _ := dbTest.SetupDB(t)
ctx := context.Background()
st := testutil.NewBeaconState()
if err := st.SetSlot(0); err != nil {
t.Fatal(err)
}
require.NoError(t, st.SetSlot(0))
bs := &Server{
GenesisTimeFetcher: &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}}
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) {
t.Errorf("Expected error %v, received %v", wanted, err)
if _, err := bs.ListValidatorBalances(context.Background(), req); err != nil {
assert.ErrorContains(t, wanted, err)
}
}
@@ -1013,10 +1011,9 @@ func TestServer_GetValidator(t *testing.T) {
}
tests := []struct {
req *ethpb.GetValidatorRequest
res *ethpb.Validator
wantErr bool
err string
req *ethpb.GetValidatorRequest
res *ethpb.Validator
wantedErr string
}{
{
req: &ethpb.GetValidatorRequest{
@@ -1024,8 +1021,7 @@ func TestServer_GetValidator(t *testing.T) {
Index: 0,
},
},
res: validators[0],
wantErr: false,
res: validators[0],
},
{
req: &ethpb.GetValidatorRequest{
@@ -1033,8 +1029,7 @@ func TestServer_GetValidator(t *testing.T) {
Index: uint64(count - 1),
},
},
res: validators[count-1],
wantErr: false,
res: validators[count-1],
},
{
req: &ethpb.GetValidatorRequest{
@@ -1042,8 +1037,7 @@ func TestServer_GetValidator(t *testing.T) {
PublicKey: pubKey(5),
},
},
res: validators[5],
wantErr: false,
res: validators[5],
},
{
req: &ethpb.GetValidatorRequest{
@@ -1051,9 +1045,8 @@ func TestServer_GetValidator(t *testing.T) {
PublicKey: []byte("bad-keyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"),
},
},
res: nil,
wantErr: true,
err: "No validator matched filter criteria",
res: nil,
wantedErr: "No validator matched filter criteria",
},
{
req: &ethpb.GetValidatorRequest{
@@ -1061,20 +1054,17 @@ func TestServer_GetValidator(t *testing.T) {
Index: uint64(len(validators)),
},
},
res: nil,
wantErr: true,
err: fmt.Sprintf("there are only %d validators", len(validators)),
res: nil,
wantedErr: fmt.Sprintf("there are only %d validators", len(validators)),
},
}
for _, test := range tests {
res, err := bs.GetValidator(context.Background(), test.req)
if test.wantErr && err != nil {
if !strings.Contains(err.Error(), test.err) {
t.Fatalf("Wanted %v, received %v", test.err, err)
}
} else if err != nil {
t.Fatal(err)
if test.wantedErr != "" {
require.ErrorContains(t, test.wantedErr, err)
} else {
require.NoError(t, err)
}
assert.DeepEqual(t, test.res, res)
}
@@ -1431,7 +1421,7 @@ func TestServer_GetValidatorParticipation_DoesntExist(t *testing.T) {
QueryFilter: &ethpb.GetValidatorParticipationRequest_Epoch{Epoch: 0},
})
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"
"encoding/binary"
"fmt"
"strings"
"testing"
"time"
@@ -72,8 +71,8 @@ func TestGetDuties_NextEpoch_CantFindValidatorIdx(t *testing.T) {
PublicKeys: [][]byte{pubKey},
}
want := fmt.Sprintf("validator %#x does not exist", req.PublicKeys[0])
if _, err := vs.GetDuties(ctx, req); err != nil && !strings.Contains(err.Error(), want) {
t.Errorf("Expected %v, received %v", want, err)
if _, err := vs.GetDuties(ctx, req); err != nil {
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
// one unaggregated attestation.
if atts, err := testutil.GenerateAttestations(beaconState, privKeys, 300, 1, true); err != nil {
t.Fatal(err)
} else {
found := false
for _, a := range atts {
if !helpers.IsAggregated(a) {
found = true
require.NoError(t, proposerServer.AttPool.SaveUnaggregatedAttestation(a))
}
}
if !found {
t.Fatal("No unaggregated attestations were generated")
atts, err = testutil.GenerateAttestations(beaconState, privKeys, 300, 1, true)
require.NoError(t, err)
found := false
for _, a := range atts {
if !helpers.IsAggregated(a) {
found = true
require.NoError(t, proposerServer.AttPool.SaveUnaggregatedAttestation(a))
}
}
require.Equal(t, true, found, "No unaggregated attestations were generated")
randaoReveal, err := testutil.RandaoReveal(beaconState, 0, privKeys)
assert.NoError(t, err)

View File

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

View File

@@ -35,27 +35,23 @@ func TestInitializeFromProto(t *testing.T) {
Slot: 4,
Validators: nil,
},
error: "",
},
{
name: "empty state",
state: &pbp2p.BeaconState{},
error: "",
},
{
name: "full state",
state: testState.InnerStateUnsafe(),
error: "",
},
}
for _, tt := range initTests {
t.Run(tt.name, func(t *testing.T) {
_, err := state.InitializeFromProto(tt.state)
if err != nil && err.Error() != tt.error {
t.Errorf("Unexpected error, expected %v, recevied %v", tt.error, err)
}
if err == nil && tt.error != "" {
t.Errorf("Expected error, expected %v, recevied %v", tt.error, err)
if tt.error != "" {
assert.ErrorContains(t, tt.error, err)
} else {
assert.NoError(t, err)
}
})
}
@@ -81,27 +77,23 @@ func TestInitializeFromProtoUnsafe(t *testing.T) {
Slot: 4,
Validators: nil,
},
error: "",
},
{
name: "empty state",
state: &pbp2p.BeaconState{},
error: "",
},
{
name: "full state",
state: testState.InnerStateUnsafe(),
error: "",
},
}
for _, tt := range initTests {
t.Run(tt.name, func(t *testing.T) {
_, err := state.InitializeFromProtoUnsafe(tt.state)
if err != nil && err.Error() != tt.error {
t.Errorf("Unexpected error, expected %v, recevied %v", tt.error, err)
}
if err == nil && tt.error != "" {
t.Errorf("Expected error, expected %v, recevied %v", tt.error, err)
if tt.error != "" {
assert.ErrorContains(t, tt.error, err)
} else {
assert.NoError(t, err)
}
})
}
@@ -255,13 +247,8 @@ func TestBeaconState_AppendValidator_DoesntMutateCopy(t *testing.T) {
originalCount := st1.NumValidators()
val := &eth.Validator{Slashed: true}
if err := st0.AppendValidator(val); err != nil {
t.Error(err)
}
if count := st1.NumValidators(); count != originalCount {
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")
}
assert.NoError(t, st0.AppendValidator(val))
assert.Equal(t, originalCount, st1.NumValidators(), "st1 NumValidators mutated")
_, ok := st1.ValidatorIndexByPubkey(bytesutil.ToBytes48(val.PublicKey))
assert.Equal(t, false, ok, "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.SaveBlock(ctx, blk))
require.NoError(t, service.beaconDB.SaveState(ctx, beaconState, blkRoot))
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Root: blkRoot[:],
Slot: 100,
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: blkRoot[:], Slot: 100}))
loadedState, err := service.StateByRoot(ctx, blkRoot)
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.SaveGenesisBlockRoot(ctx, bRoot))
r := [32]byte{'a'}
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Root: r[:],
Slot: 1,
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Root: r[:], Slot: 1}))
loadedState, err := service.StateByRoot(ctx, r)
require.NoError(t, err)
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))
targetRoot, err := stateutil.BlockRoot(targetBlock.Block)
require.NoError(t, err)
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: targetSlot,
Root: targetRoot[:],
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: targetSlot, Root: targetRoot[:]}))
loadedState, err := service.StateByRoot(ctx, targetRoot)
require.NoError(t, err)
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)
require.NoError(t, err)
require.NoError(t, service.beaconDB.SaveBlock(ctx, targetBlk))
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: targetSlot,
Root: targetRoot[:],
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: targetSlot, Root: targetRoot[:]}))
loadedState, err := service.StateByRootInitialSync(ctx, targetRoot)
require.NoError(t, err)
@@ -194,12 +179,7 @@ func TestStateBySlot_ColdState(t *testing.T) {
require.NoError(t, db.SaveGenesisBlockRoot(ctx, bRoot))
r := [32]byte{}
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: service.slotsPerArchivedPoint,
Root: r[:],
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: service.slotsPerArchivedPoint, Root: r[:]}))
slot := uint64(20)
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))
blkRoot, err := stateutil.BlockRoot(blk.Block)
require.NoError(t, err)
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: 10,
Root: blkRoot[:],
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: 10, Root: blkRoot[:]}))
// This tests where hot state was not cached and needs processing.
loadedState, err := service.loadHotStateByRoot(ctx, blkRoot)
@@ -136,12 +131,7 @@ func TestLoadHoteStateByRoot_FromDBBoundaryCase(t *testing.T) {
require.NoError(t, err)
require.NoError(t, service.epochBoundaryStateCache.put(blkRoot, beaconState))
targetSlot := uint64(0)
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: targetSlot,
Root: blkRoot[:],
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: targetSlot, Root: blkRoot[:]}))
// This tests where hot state was not cached but doesn't need processing
// 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, service.beaconDB.SaveBlock(ctx, blk))
require.NoError(t, service.beaconDB.SaveGenesisBlockRoot(ctx, fRoot))
if err := service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{
Slot: 1,
Root: fRoot[:],
}); err != nil {
t.Fatal(err)
}
require.NoError(t, service.beaconDB.SaveStateSummary(ctx, &pb.StateSummary{Slot: 1, Root: fRoot[:]}))
service.finalizedInfo = &finalizedInfo{
slot: 1,
root: fRoot,

View File

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

View File

@@ -19,9 +19,8 @@ func TestRegularSync_generateErrorResponse(t *testing.T) {
buf := bytes.NewBuffer(data)
b := make([]byte, 1)
if _, err := buf.Read(b); err != nil {
t.Fatal(err)
}
_, err = buf.Read(b)
require.NoError(t, err)
assert.Equal(t, responseCodeServerError, b[0], "The first byte was not the status code")
msg := &pb.ErrorResponse{}
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 {
t.Run(tt.name, func(t *testing.T) {
got, err := fetcher.selectFailOverPeer(tt.args.excludedPID, tt.args.peers)
if err != nil && err != tt.wantErr {
t.Errorf("selectFailOverPeer() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("selectFailOverPeer() got = %v, want %v", got, tt.want)
if tt.wantErr != nil {
assert.ErrorContains(t, tt.wantErr.Error(), err)
} else {
assert.Equal(t, tt.want, got)
}
})
}
@@ -995,8 +993,8 @@ func TestBlocksFetcher_RequestBlocksRateLimitingLocks(t *testing.T) {
})
}
_, err := fetcher.requestBlocks(ctx, req, p2.PeerID())
if err != nil && err != errFetcherCtxIsDone {
t.Error(err)
if err != nil {
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.SetStreamHandler(topic, func(stream network.Stream) {
defer func() {
if err := stream.Close(); err != nil {
t.Log(err)
}
assert.NoError(t, stream.Close())
}()
req := &p2ppb.BeaconBlocksByRangeRequest{}
@@ -182,12 +180,10 @@ func connectPeer(t *testing.T, host *p2pt.TestP2P, datum *peerData, peerStatus *
// Expected failure range
if len(sliceutil.IntersectionUint64(datum.failureSlots, requestedBlocks)) > 0 {
if _, err := stream.Write([]byte{0x01}); err != nil {
t.Error(err)
}
if _, err := p.Encoding().EncodeWithMaxLength(stream, "bad"); err != nil {
t.Error(err)
}
_, err := stream.Write([]byte{0x01})
assert.NoError(t, err)
_, err = p.Encoding().EncodeWithMaxLength(stream, "bad")
assert.NoError(t, err)
return
}

View File

@@ -54,10 +54,10 @@ func TestService_beaconBlockSubscriber(t *testing.T) {
msg proto.Message
}
tests := []struct {
name string
args args
wantErr bool
check func(*testing.T, *Service)
name string
args args
wantedErr string
check func(*testing.T, *Service)
}{
{
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) {
if s.attPool.AggregatedAttestationCount() == 0 {
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.
if err := s.beaconBlockSubscriber(context.Background(), tt.args.msg); (err != nil) != tt.wantErr {
t.Errorf("beaconBlockSubscriber(ctx, msg) error = %v, wantErr %v", err, tt.wantErr)
err := s.beaconBlockSubscriber(context.Background(), tt.args.msg)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
}
// Perform any test check.
if tt.check != nil {
tt.check(t, s)
}

View File

@@ -35,6 +35,8 @@ go_test(
deps = [
"//shared/interop: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",
"@com_github_ethereum_go_ethereum//:go_default_library",
"@com_github_ethereum_go_ethereum//accounts/abi/bind:go_default_library",

View File

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

View File

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

View File

@@ -39,5 +39,7 @@ go_test(
"@com_github_gogo_protobuf//types:go_default_library",
"@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1: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/shared/params"
"github.com/prysmaticlabs/prysm/shared/slotutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"google.golang.org/grpc"
)
@@ -46,9 +48,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
if config.UsePprof {
defer func() {
for i := 0; i < e2e.TestParams.BeaconNodeCount; i++ {
if err := helpers.WritePprofFiles(e2e.TestParams.LogPath, i); err != nil {
t.Error(err)
}
assert.NoError(t, helpers.WritePprofFiles(e2e.TestParams.LogPath, i))
}
}()
}
@@ -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.
time.Sleep(time.Duration(params.BeaconConfig().GenesisDelay) * time.Second)
beaconLogFile, err := os.Open(path.Join(e2e.TestParams.LogPath, fmt.Sprintf(e2e.BeaconNodeLogFileName, 0)))
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
t.Run("chain started", func(t *testing.T) {
if err := helpers.WaitForTextInFile(beaconLogFile, "Chain started within the last epoch"); err != nil {
t.Fatalf("failed to find chain start in logs, this means the chain did not start: %v", err)
}
require.NoError(t, helpers.WaitForTextInFile(beaconLogFile, "Chain started within the last epoch"), "Chain did not 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)
for i := 0; i < len(conns); i++ {
conn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", e2e.TestParams.BeaconNodeRPCPort+i), grpc.WithInsecure())
if err != nil {
t.Fatalf("Failed to dial: %v", err)
}
require.NoError(t, err, "Failed to dial")
conns[i] = conn
defer func() {
if err := conn.Close(); err != nil {
@@ -93,9 +87,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
}
nodeClient := eth.NewNodeClient(conns[0])
genesis, err := nodeClient.GetGenesis(context.Background(), &ptypes.Empty{})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
epochSeconds := params.BeaconConfig().SecondsPerSlot * params.BeaconConfig().SlotsPerEpoch
epochSecondsHalf := time.Duration(int64(epochSeconds*1000)/2) * time.Millisecond
@@ -113,9 +105,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
continue
}
t.Run(fmt.Sprintf(evaluator.Name, currentEpoch), func(t *testing.T) {
if err := evaluator.Evaluation(conns...); err != nil {
t.Errorf("evaluation failed for epoch %d: %v", currentEpoch, err)
}
assert.NoError(t, evaluator.Evaluation(conns...), "Evaluation failed for epoch %d: %v", currentEpoch, err)
})
}
@@ -135,9 +125,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
index := e2e.TestParams.BeaconNodeCount
components.StartNewBeaconNode(t, config, index, bootnodeENR)
syncConn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", e2e.TestParams.BeaconNodeRPCPort+index), grpc.WithInsecure())
if err != nil {
t.Fatalf("Failed to dial: %v", err)
}
require.NoError(t, err, "Failed to dial")
conns = append(conns, syncConn)
// 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))
syncLogFile, err := os.Open(path.Join(e2e.TestParams.LogPath, fmt.Sprintf(e2e.BeaconNodeLogFileName, index)))
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
defer helpers.LogErrorOutput(t, syncLogFile, "beacon chain node", index)
t.Run("sync completed", func(t *testing.T) {
if err := helpers.WaitForTextInFile(syncLogFile, "Synced up to"); err != nil {
t.Errorf("Failed to sync: %v", err)
}
assert.NoError(t, helpers.WaitForTextInFile(syncLogFile, "Synced up to"), "Failed to sync")
})
if t.Failed() {
return
@@ -164,9 +148,7 @@ func runEndToEndTest(t *testing.T, config *types.E2EConfig) {
syncEvaluators := []types.Evaluator{ev.FinishedSyncing, ev.AllNodesHaveSameHead}
for _, evaluator := range syncEvaluators {
t.Run(evaluator.Name, func(t *testing.T) {
if err := evaluator.Evaluation(conns...); err != nil {
t.Errorf("evaluation failed for sync node: %v", err)
}
assert.NoError(t, evaluator.Evaluation(conns...), "Evaluation failed for sync node")
})
}
}

View File

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

View File

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

View File

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

View File

@@ -9,6 +9,8 @@ import (
"github.com/prysmaticlabs/go-ssz"
sszspectest "github.com/prysmaticlabs/go-ssz/spectests"
"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
@@ -69,29 +71,17 @@ func TestBlockHeaderSigningRoot(t *testing.T) {
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
root1, err := ssz.HashTreeRoot(tt.header1)
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
root2, err := ssz.HashTreeRoot(tt.header2)
if err != nil {
t.Error(err)
}
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)
}
assert.NoError(t, err)
assert.Equal(t, root1, root2)
assert.Equal(t, tt.expectedRoot, root1)
})
}
}
func hexDecodeOrDie(t *testing.T, h string) []byte {
b, err := hex.DecodeString(h)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
return b
}

View File

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

View File

@@ -8,6 +8,8 @@ import (
"testing"
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) {
@@ -16,36 +18,20 @@ func TestSSZTagSize(t *testing.T) {
rootSize := 32
sizes, err := sszTagSizes(pb.Attestation{}, "Signature")
if err != nil {
t.Fatal(err)
}
if sizes[0] != sigSize {
t.Errorf("wanted signature size: %d, got: %d", sigSize, sizes[0])
}
require.NoError(t, err)
assert.Equal(t, sigSize, sizes[0], "Unexpected signature size")
sizes, err = sszTagSizes(pb.SignedBeaconBlock{}, "Signature")
if err != nil {
t.Fatal(err)
}
if sizes[0] != sigSize {
t.Errorf("wanted signature size: %d, got: %d", sigSize, sizes[0])
}
require.NoError(t, err)
assert.Equal(t, sigSize, sizes[0], "Unexpected signature size")
sizes, err = sszTagSizes(pb.Checkpoint{}, "Root")
if err != nil {
t.Fatal(err)
}
if sizes[0] != rootSize {
t.Errorf("wanted signature size: %d, got: %d", rootSize, sizes[0])
}
require.NoError(t, err)
assert.Equal(t, rootSize, sizes[0], "Unexpected signature size")
sizes, err = sszTagSizes(pb.Validator{}, "PublicKey")
if err != nil {
t.Fatal(err)
}
if sizes[0] != pubKeySize {
t.Errorf("wanted signature size: %d, got: %d", pubKeySize, sizes[0])
}
require.NoError(t, err)
assert.Equal(t, pubKeySize, sizes[0], "Unexpected signature size")
}
func sszTagSizes(i interface{}, fName string) ([]int, error) {

View File

@@ -14,5 +14,8 @@ go_test(
size = "small",
srcs = ["service_registry_test.go"],
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
import (
"errors"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
@@ -15,29 +14,24 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
atts []*ethpb.Attestation
}
tests := []struct {
name string
args args
want *aggregation.MaxCoverProblem
wantErr bool
expectedErr error
name string
args args
want *aggregation.MaxCoverProblem
wantedErr string
}{
{
name: "nil attestations",
args: args{
atts: nil,
},
want: nil,
wantErr: true,
expectedErr: ErrInvalidAttestationCount,
wantedErr: ErrInvalidAttestationCount.Error(),
},
{
name: "no attestations",
args: args{
atts: []*ethpb.Attestation{},
},
want: nil,
wantErr: true,
expectedErr: ErrInvalidAttestationCount,
wantedErr: ErrInvalidAttestationCount.Error(),
},
{
name: "attestations of different bitlist length",
@@ -47,9 +41,7 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
{AggregationBits: bitfield.NewBitlist(128)},
},
},
want: nil,
wantErr: true,
expectedErr: aggregation.ErrBitsDifferentLen,
wantedErr: aggregation.ErrBitsDifferentLen.Error(),
},
{
name: "single attestation",
@@ -63,7 +55,6 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
aggregation.NewMaxCoverCandidate(0, &bitfield.Bitlist{0b00001010, 0b1}),
},
},
wantErr: false,
},
{
name: "multiple attestations",
@@ -85,17 +76,17 @@ func TestAggregateAttestations_MaxCover_NewMaxCover(t *testing.T) {
aggregation.NewMaxCoverCandidate(4, &bitfield.Bitlist{0b00000001, 0b1}),
},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewMaxCover(tt.args.atts)
if (err != nil) != tt.wantErr || !errors.Is(err, tt.expectedErr) {
t.Errorf("NewMaxCoverProblem() unexpected error, got: %v, want: %v", err, tt.expectedErr)
return
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} 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
import (
"errors"
"reflect"
"sort"
"testing"
@@ -551,17 +550,15 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
allowDuplicates bool
}
tests := []struct {
name string
args args
want *Aggregation
wantErr bool
expectedErr error
name string
args args
want *Aggregation
wantedErr string
}{
{
name: "nil problem",
args: args{},
wantErr: true,
expectedErr: ErrInvalidMaxCoverProblem,
name: "nil problem",
args: args{},
wantedErr: ErrInvalidMaxCoverProblem.Error(),
},
{
name: "different bitlengths",
@@ -570,8 +567,7 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
{2, &bitfield.Bitlist{0b00000001, 0b11100000, 0b1}, 0, false},
{3, &bitfield.Bitlist{0b00000110, 0b00000000, 0b1}, 0, false},
}},
wantErr: true,
expectedErr: ErrInvalidMaxCoverProblem,
wantedErr: ErrInvalidMaxCoverProblem.Error(),
},
{
name: "k=0",
@@ -580,7 +576,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0000000, 0b1},
Keys: []int{},
},
wantErr: false,
},
{
name: "k=1",
@@ -589,7 +584,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011011, 0b1},
Keys: []int{1},
},
wantErr: false,
},
{
name: "k=2",
@@ -598,7 +592,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0},
},
wantErr: false,
},
{
name: "k=3",
@@ -607,7 +600,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0},
},
wantErr: false,
},
{
name: "k=5",
@@ -616,7 +608,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0},
},
wantErr: false,
},
{
name: "k=50",
@@ -625,7 +616,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b0011111, 0b1},
Keys: []int{1, 0},
},
wantErr: false,
},
{
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},
Keys: []int{0, 2, 3},
},
wantErr: false,
},
{
name: "allow overlaps",
@@ -658,7 +647,6 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Coverage: bitfield.Bitlist{0b00001111, 0xff, 0b11111110, 0b1},
Keys: []int{0, 3, 1, 2, 6},
},
wantErr: false,
},
}
for _, tt := range tests {
@@ -667,11 +655,12 @@ func TestMaxCover_MaxCoverProblem_cover(t *testing.T) {
Candidates: tt.args.candidates,
}
got, err := mc.Cover(tt.args.k, tt.args.allowOverlaps, tt.args.allowDuplicates)
if (err != nil) != tt.wantErr || !errors.Is(err, tt.expectedErr) {
t.Errorf("newMaxCoverProblem() unexpected error, got: %v, want: %v", err, tt.expectedErr)
return
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} 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 (
"context"
"strings"
"testing"
eth "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
@@ -49,9 +48,9 @@ func TestAttestingIndices(t *testing.T) {
func TestIsValidAttestationIndices(t *testing.T) {
tests := []struct {
name string
att *eth.IndexedAttestation
want string
name string
att *eth.IndexedAttestation
wantedErr string
}{
{
name: "Indices should be non-empty",
@@ -62,7 +61,7 @@ func TestIsValidAttestationIndices(t *testing.T) {
},
Signature: nil,
},
want: "expected non-empty",
wantedErr: "expected non-empty",
},
{
name: "Greater than max validators per committee",
@@ -73,7 +72,7 @@ func TestIsValidAttestationIndices(t *testing.T) {
},
Signature: nil,
},
want: "indices count exceeds",
wantedErr: "indices count exceeds",
},
{
name: "Needs to be sorted",
@@ -84,7 +83,7 @@ func TestIsValidAttestationIndices(t *testing.T) {
},
Signature: nil,
},
want: "not uniquely sorted",
wantedErr: "not uniquely sorted",
},
{
name: "Valid indices",
@@ -100,11 +99,10 @@ func TestIsValidAttestationIndices(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := attestationutil.IsValidAttestationIndices(context.Background(), tt.att)
if tt.want == "" && err != nil {
t.Fatal(err)
}
if tt.want != "" && !strings.Contains(err.Error(), tt.want) {
t.Errorf("IsValidAttestationIndices() got = %v, want %v", err, tt.want)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
} else {
assert.NoError(t, err)
}
})
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -23,5 +23,8 @@ go_test(
"subscription_test.go",
],
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"
"testing"
"time"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
)
func TestFeedPanics(t *testing.T) {
@@ -29,38 +31,28 @@ func TestFeedPanics(t *testing.T) {
var f Feed
f.Send(2)
want := feedTypeError{op: "Send", got: reflect.TypeOf(uint64(0)), want: reflect.TypeOf(0)}
if err := checkPanic(want, func() { f.Send(uint64(2)) }); err != nil {
t.Error(err)
}
assert.NoError(t, checkPanic(want, func() { f.Send(uint64(2)) }))
}
{
var f Feed
ch := make(chan int)
f.Subscribe(ch)
want := feedTypeError{op: "Send", got: reflect.TypeOf(uint64(0)), want: reflect.TypeOf(0)}
if err := checkPanic(want, func() { f.Send(uint64(2)) }); err != nil {
t.Error(err)
}
assert.NoError(t, checkPanic(want, func() { f.Send(uint64(2)) }))
}
{
var f Feed
f.Send(2)
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 {
t.Error(err)
}
assert.NoError(t, checkPanic(want, func() { f.Subscribe(make(chan uint64)) }))
}
{
var f Feed
if err := checkPanic(errBadChannel, func() { f.Subscribe(make(<-chan int)) }); err != nil {
t.Error(err)
}
assert.NoError(t, checkPanic(errBadChannel, func() { f.Subscribe(make(<-chan int)) }))
}
{
var f Feed
if err := checkPanic(errBadChannel, func() { f.Subscribe(0) }); err != nil {
t.Error(err)
}
assert.NoError(t, checkPanic(errBadChannel, func() { f.Subscribe(0) }))
}
}
@@ -283,22 +275,14 @@ func TestFeedUnsubscribeFromInbox(t *testing.T) {
sub2 = feed.Subscribe(ch1)
sub3 = feed.Subscribe(ch2)
)
if len(feed.inbox) != 3 {
t.Errorf("inbox length != 3 after subscribe")
}
if len(feed.sendCases) != 1 {
t.Errorf("sendCases is non-empty after unsubscribe")
}
assert.Equal(t, 3, len(feed.inbox))
assert.Equal(t, 1, len(feed.sendCases), "sendCases is non-empty after unsubscribe")
sub1.Unsubscribe()
sub2.Unsubscribe()
sub3.Unsubscribe()
if len(feed.inbox) != 0 {
t.Errorf("inbox is non-empty after unsubscribe")
}
if len(feed.sendCases) != 1 {
t.Errorf("sendCases is non-empty after unsubscribe")
}
assert.Equal(t, 0, len(feed.inbox), "Inbox is non-empty after unsubscribe")
assert.Equal(t, 1, len(feed.sendCases), "sendCases is non-empty after unsubscribe")
}
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")
return tempDir, func() {
if err := os.RemoveAll(tempDir); err != nil {
t.Logf("unable to remove temporary files: %v", err)
}
assert.NoError(t, os.RemoveAll(tempDir))
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -100,9 +100,12 @@ go_test(
deps = [
"//shared/iputils: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_ethereum_go_ethereum//p2p/discover: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_sirupsen_logrus//:go_default_library",
],
)

View File

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

View File

@@ -40,6 +40,8 @@ go_test(
"//shared/interop:go_default_library",
"//shared/params: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",
"@com_github_ethereum_go_ethereum//:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",

View File

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

View File

@@ -25,5 +25,9 @@ go_test(
name = "go_default_test",
srcs = ["main_test.go"],
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 (
"bytes"
"encoding/json"
"reflect"
"testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/tools/unencrypted-keys-gen/keygen"
)
@@ -14,15 +15,9 @@ func TestSavesUnencryptedKeys(t *testing.T) {
numKeys = &keys
ctnr := generateUnencryptedKeys(0 /* start index */)
buf := new(bytes.Buffer)
if err := keygen.SaveUnencryptedKeysToFile(buf, ctnr); err != nil {
t.Fatal(err)
}
require.NoError(t, keygen.SaveUnencryptedKeysToFile(buf, ctnr))
enc := buf.Bytes()
dec := &keygen.UnencryptedKeysContainer{}
if err := json.Unmarshal(enc, dec); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(ctnr, dec) {
t.Errorf("Wanted %v, received %v", ctnr, dec)
}
require.NoError(t, json.Unmarshal(enc, dec))
assert.DeepEqual(t, ctnr, dec)
}

View File

@@ -62,9 +62,7 @@ func TestNewValidatorAccount_CreateValidatorAccount(t *testing.T) {
t.Run("empty existing dir", func(t *testing.T) {
directory := testutil.TempDir() + "/testkeystore"
defer func() {
if err := os.RemoveAll(directory); err != nil {
t.Logf("Could not remove directory: %v", err)
}
assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
}()
// 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) {
directory := testutil.TempDir() + "/testkeystore"
defer func() {
if err := os.RemoveAll(directory); err != nil {
t.Logf("Could not remove directory: %v", err)
}
assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
}()
require.NoError(t, os.Mkdir(directory, 0777))
_, _, err := CreateValidatorAccount(directory, "")
@@ -106,9 +102,7 @@ func TestHandleEmptyFlags_FlagsSet(t *testing.T) {
func TestChangePassword_KeyEncryptedWithNewPassword(t *testing.T) {
directory := testutil.TempDir() + "/testkeystore"
defer func() {
if err := os.RemoveAll(directory); err != nil {
t.Logf("Could not remove directory: %v", err)
}
assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
}()
oldPassword := "old"
@@ -132,9 +126,7 @@ func TestChangePassword_KeyEncryptedWithNewPassword(t *testing.T) {
func TestChangePassword_KeyNotMatchingOldPasswordNotEncryptedWithNewPassword(t *testing.T) {
directory := testutil.TempDir() + "/testkeystore"
defer func() {
if err := os.RemoveAll(directory); err != nil {
t.Logf("Could not remove directory: %v", err)
}
assert.NoError(t, os.RemoveAll(directory), "Could not remove directory")
}()
oldPassword := "old"

View File

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

View File

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

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.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[:])
if otherKeyProposalsBucket != nil {
t.Fatalf("Store for public key %v contains proposals for another key", encodedKey2)
}
require.Equal(t, (*bolt.Bucket)(nil), otherKeyProposalsBucket, "Store for public key %v contains proposals for another key", encodedKey2)
otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey2[:])
if otherKeyAttestationsBucket != nil {
t.Fatalf("Store for public key %v contains attestations for another key", encodedKey2)
}
require.Equal(t, (*bolt.Bucket)(nil), otherKeyAttestationsBucket, "Store for public key %v contains attestations for another key", encodedKey2)
return nil
}); err != nil {
t.Fatalf("Failed to close store: %v", err)
}
if err := keyStore2.view(func(tx *bolt.Tx) error {
})
require.NoError(t, err)
err = keyStore2.view(func(tx *bolt.Tx) error {
otherKeyProposalsBucket := tx.Bucket(historicProposalsBucket).Bucket(pubKey1[:])
if otherKeyProposalsBucket != nil {
t.Fatalf("Store for public key %v contains proposals for another key", encodedKey1)
}
require.Equal(t, (*bolt.Bucket)(nil), otherKeyProposalsBucket, "Store for public key %v contains proposals for another key", encodedKey1)
otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey1[:])
if otherKeyAttestationsBucket != nil {
t.Fatalf("Store for public key %v contains attestations for another key", encodedKey1)
}
require.Equal(t, (*bolt.Bucket)(nil), otherKeyAttestationsBucket, "Store for public key %v contains attestations for another key", encodedKey1)
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, keyStore2, [][48]byte{pubKey2}, storeHistory2)
@@ -151,20 +140,14 @@ func TestSplit_AttestationsWithoutMatchingProposalsAreSplit(t *testing.T) {
require.NoError(t, err, "Retrieving the store failed")
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[:])
if otherKeyProposalsBucket != nil {
t.Fatalf("Store for public key %v contains proposals for another key", encodedKey1)
}
require.Equal(t, (*bolt.Bucket)(nil), otherKeyProposalsBucket, "Store for public key %v contains proposals for another key", encodedKey1)
otherKeyAttestationsBucket := tx.Bucket(historicAttestationsBucket).Bucket(pubKey1[:])
if otherKeyAttestationsBucket != nil {
t.Fatalf("Store for public key %v contains attestations for another key", encodedKey1)
}
require.Equal(t, (*bolt.Bucket)(nil), otherKeyAttestationsBucket, "Store for public key %v contains attestations for another key", encodedKey1)
return nil
}); err != nil {
t.Fatalf("Failed to retrieve attestations: %v", err)
}
})
require.NoError(t, err)
splitAttestationsHistory, err :=
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) {
path := SetupWallet(t)
defer func() {
if err := os.RemoveAll(path); err != nil {
t.Log(err)
}
assert.NoError(t, os.RemoveAll(path))
}()
tests := []struct {
name string
@@ -92,9 +90,7 @@ func TestMultiplePassphrases(t *testing.T) {
func TestEnvPassphrases(t *testing.T) {
path := SetupWallet(t)
defer func() {
if err := os.RemoveAll(path); err != nil {
t.Log(err)
}
assert.NoError(t, os.RemoveAll(path))
}()
err := os.Setenv("TESTENVPASSPHRASES_NEITHER", "neither")

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,6 +6,7 @@ import (
"testing"
"github.com/prysmaticlabs/prysm/shared/testutil"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
v1 "github.com/prysmaticlabs/prysm/validator/accounts/v1"
"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")
dir := testutil.TempDir() + "/keystore1"
defer func() {
if err := os.RemoveAll(dir); err != nil {
t.Log(err)
}
assert.NoError(t, os.RemoveAll(dir))
}()
defer func() {
if err := os.RemoveAll(testutil.TempDir() + "/datadir"); err != nil {
t.Log(err)
}
assert.NoError(t, os.RemoveAll(testutil.TempDir()+"/datadir"))
}()
set.String("keystore-path", dir, "path to keystore")
set.String("password", "1234", "validator account password")

View File

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