Assert no side effects occur on test (#5714)

* add reset funcs
* init -> TestMain for beacon config params
* fixes build file
* core/epoch spectests updated
* core/blocks spectests updated
* fix the rest of spectests
* SetupTestConfigCleanup
* revert copy() api
* rever all cases of copy()
* fixes spectests
* updates fork_test
* config_test update
* fixes spectest/config_test
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge branch 'master' into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge branch 'master' into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
* Merge refs/heads/master into assert-no-side-effects-occur-in-tests
This commit is contained in:
Victor Farazdagi
2020-05-05 11:39:38 +03:00
committed by GitHub
parent 0b8ee54076
commit bbde2a6820
46 changed files with 173 additions and 244 deletions

View File

@@ -56,6 +56,7 @@ func TestEth1DataHasEnoughSupport(t *testing.T) {
},
}
params.SetupTestConfigCleanup(t)
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
c := params.BeaconConfig()

View File

@@ -12,7 +12,7 @@ import (
)
func runAttestationTest(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -12,7 +12,7 @@ import (
)
func runAttesterSlashingTest(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -19,7 +19,7 @@ import (
)
func runBlockHeaderTest(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -28,7 +28,7 @@ func init() {
}
func runBlockProcessingTest(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -12,7 +12,7 @@ import (
)
func runDepositTest(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -12,7 +12,7 @@ import (
)
func runProposerSlashingTest(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -12,7 +12,7 @@ import (
)
func runVoluntaryExitTest(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -13,13 +13,6 @@ import (
"github.com/prysmaticlabs/prysm/shared/params"
)
func init() {
// TODO(2312): remove this and use the mainnet count.
c := params.BeaconConfig()
c.MinGenesisActiveValidatorCount = 16384
params.OverrideBeaconConfig(c)
}
func TestUnslashedAttestingIndices_CanSortAndFilter(t *testing.T) {
// Generate 2 attestations.
atts := make([]*pb.PendingAttestation, 2)

View File

@@ -31,6 +31,7 @@ go_test(
"//beacon-chain/state:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/params/spectest:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_prysmaticlabs_go_ssz//:go_default_library",
@@ -62,6 +63,7 @@ go_test(
"//beacon-chain/state:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/params/spectest:go_default_library",
"//shared/params:go_default_library",
"//shared/testutil:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@in_gopkg_d4l3k_messagediff_v1//:go_default_library",

View File

@@ -11,7 +11,7 @@ import (
)
func runFinalUpdatesTests(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -12,7 +12,7 @@ import (
)
func runJustificationAndFinalizationTests(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -11,7 +11,7 @@ import (
)
func runRegistryUpdatesTests(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -13,7 +13,7 @@ import (
)
func runSlashingsTests(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -0,0 +1,20 @@
package spectest
import (
"os"
"testing"
"github.com/prysmaticlabs/prysm/shared/params"
)
func TestMain(m *testing.M) {
prevConfig := params.BeaconConfig().Copy()
c := params.BeaconConfig()
// TODO(2312): remove this and use the mainnet count.
c.MinGenesisActiveValidatorCount = 16384
params.OverrideBeaconConfig(c)
retVal := m.Run()
params.OverrideBeaconConfig(prevConfig)
os.Exit(retVal)
}

View File

@@ -25,7 +25,7 @@ func TestShufflingMainnet(t *testing.T) {
}
func runShuffleTests(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -120,6 +120,7 @@ func TestIsSlashableValidator_InactiveSlashed(t *testing.T) {
}
func TestBeaconProposerIndex_OK(t *testing.T) {
params.SetupTestConfigCleanup(t)
ClearCache()
c := params.BeaconConfig()
c.MinGenesisActiveValidatorCount = 16384

View File

@@ -20,7 +20,7 @@ func init() {
}
func runSlotProcessingTests(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -885,6 +885,7 @@ func TestProcessBlk_AttsBasedOnValidatorCount(t *testing.T) {
}
blk.Signature = sig.Marshal()
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config.MinAttestationInclusionDelay = 0
params.OverrideBeaconConfig(config)

View File

@@ -237,6 +237,7 @@ func TestPool_InsertAttesterSlashing(t *testing.T) {
}
func TestPool_InsertAttesterSlashing_SigFailsVerify_ClearPool(t *testing.T) {
params.SetupTestConfigCleanup(t)
conf := params.BeaconConfig()
conf.MaxAttesterSlashings = 2
params.OverrideBeaconConfig(conf)
@@ -423,6 +424,7 @@ func TestPool_PendingAttesterSlashings(t *testing.T) {
type fields struct {
pending []*PendingAttesterSlashing
}
params.SetupTestConfigCleanup(t)
conf := params.BeaconConfig()
conf.MaxAttesterSlashings = 1
params.OverrideBeaconConfig(conf)
@@ -482,6 +484,7 @@ func TestPool_PendingAttesterSlashings(t *testing.T) {
}
func TestPool_PendingAttesterSlashings_NoDuplicates(t *testing.T) {
params.SetupTestConfigCleanup(t)
conf := params.BeaconConfig()
conf.MaxAttesterSlashings = 2
params.OverrideBeaconConfig(conf)

View File

@@ -213,6 +213,7 @@ func TestPool_InsertProposerSlashing(t *testing.T) {
}
func TestPool_InsertProposerSlashing_SigFailsVerify_ClearPool(t *testing.T) {
params.SetupTestConfigCleanup(t)
conf := params.BeaconConfig()
conf.MaxAttesterSlashings = 2
params.OverrideBeaconConfig(conf)

View File

@@ -125,8 +125,7 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
UDPPort: uint(port),
}
originalBeaconConfig := params.BeaconConfig()
params.SetupTestConfigCleanup(t)
var listeners []*discover.UDPv5
for i := 1; i <= 5; i++ {
port = 3000 + i
@@ -173,7 +172,6 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
// bootnode given all nodes provided by discv5 will have different fork digests.
cfg.UDPPort = 14000
cfg.TCPPort = 14001
params.OverrideBeaconConfig(originalBeaconConfig)
s, err := NewService(cfg)
if err != nil {
t.Fatal(err)
@@ -194,8 +192,8 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
}
func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.BeaconConfig()
originalConfig := c
c.ForkVersionSchedule = map[uint64][]byte{
0: params.BeaconConfig().GenesisForkVersion,
1: {0, 0, 0, 1},
@@ -205,7 +203,6 @@ func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) {
c.NextForkEpoch = nextForkEpoch
c.NextForkVersion = nextForkVersion
params.OverrideBeaconConfig(c)
defer params.OverrideBeaconConfig(originalConfig)
genesisTime := time.Now()
genesisValidatorsRoot := make([]byte, 32)

View File

@@ -285,6 +285,7 @@ func TestProcessETH2GenesisLog_8DuplicatePubkeys(t *testing.T) {
t.Fatal(err)
}
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)
@@ -368,6 +369,7 @@ func TestProcessETH2GenesisLog(t *testing.T) {
if err != nil {
t.Fatal(err)
}
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)
@@ -488,6 +490,7 @@ func TestProcessETH2GenesisLog_CorrectNumOfDeposits(t *testing.T) {
web3Service.httpLogger = testAcc.Backend
web3Service.latestEth1Data.LastRequestedBlock = 0
web3Service.latestEth1Data.BlockHeight = 0
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)
@@ -588,6 +591,7 @@ func TestWeb3ServiceProcessDepositLog_RequestMissedDeposits(t *testing.T) {
t.Fatal(err)
}
web3Service.httpLogger = testAcc.Backend
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)
@@ -775,6 +779,7 @@ func newPowchainService(t *testing.T, eth1Backend *contracts.TestAccount, beacon
web3Service.blockFetcher = &goodFetcher{backend: eth1Backend.Backend}
web3Service.httpLogger = &goodLogger{backend: eth1Backend.Backend}
web3Service.logger = &goodLogger{backend: eth1Backend.Backend}
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)

View File

@@ -569,10 +569,10 @@ func TestServer_mapAttestationToTargetRoot(t *testing.T) {
func TestServer_ListIndexedAttestations_NewStateManagnmentDisabled(t *testing.T) {
resetCfg := featureconfig.InitWithReset(&featureconfig.Flags{NewStateMgmt: false})
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
db := dbTest.SetupDB(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
ctx := context.Background()
numValidators := uint64(128)
state, _ := testutil.DeterministicGenesisState(t, numValidators)
@@ -600,10 +600,10 @@ func TestServer_ListIndexedAttestations_NewStateManagnmentDisabled(t *testing.T)
}
func TestServer_ListIndexedAttestations_GenesisEpoch(t *testing.T) {
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
resetCfg := featureconfig.InitWithReset(&featureconfig.Flags{NewStateMgmt: true})
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
db := dbTest.SetupDB(t)
helpers.ClearCache()
ctx := context.Background()
@@ -736,10 +736,10 @@ func TestServer_ListIndexedAttestations_GenesisEpoch(t *testing.T) {
}
func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) {
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
resetCfg := featureconfig.InitWithReset(&featureconfig.Flags{NewStateMgmt: true})
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
db := dbTest.SetupDB(t)
helpers.ClearCache()
ctx := context.Background()
@@ -1006,8 +1006,8 @@ func TestServer_StreamIndexedAttestations_ContextCanceled(t *testing.T) {
}
func TestServer_StreamIndexedAttestations_OK(t *testing.T) {
resetCfg := params.OverrideBeaconConfigWithReset(params.MainnetConfig())
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
db := dbTest.SetupDB(t)
exitRoutine := make(chan bool)
ctrl := gomock.NewController(t)

View File

@@ -10,11 +10,15 @@ import (
func TestMain(m *testing.M) {
// Use minimal config to reduce test setup time.
reset := params.OverrideBeaconConfigWithReset(params.MinimalSpecConfig())
prevConfig := params.BeaconConfig().Copy()
params.OverrideBeaconConfig(params.MinimalSpecConfig())
flags.Init(&flags.GlobalFlags{
MaxPageSize: 250,
})
retVal := m.Run()
reset()
// Reset configuration.
params.OverrideBeaconConfig(prevConfig)
os.Exit(retVal)
}

View File

@@ -10,8 +10,8 @@ import (
)
func TestInfostream_EpochToTimestamp(t *testing.T) {
resetCfg := params.OverrideBeaconConfigWithReset(params.MainnetConfig())
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
tests := []struct {
name string
epoch uint64
@@ -49,8 +49,8 @@ func TestInfostream_EpochToTimestamp(t *testing.T) {
}
func TestInfostream_HandleSetValidatorKeys(t *testing.T) {
resetCfg := params.OverrideBeaconConfigWithReset(params.MainnetConfig())
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
tests := []struct {
name string
reqPubKeys [][]byte
@@ -88,8 +88,8 @@ func TestInfostream_HandleSetValidatorKeys(t *testing.T) {
}
func TestInfostream_HandleAddValidatorKeys(t *testing.T) {
resetCfg := params.OverrideBeaconConfigWithReset(params.MainnetConfig())
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
tests := []struct {
name string
initialPubKeys [][]byte
@@ -140,8 +140,8 @@ func TestInfostream_HandleAddValidatorKeys(t *testing.T) {
}
func TestInfostream_HandleRemoveValidatorKeys(t *testing.T) {
resetCfg := params.OverrideBeaconConfigWithReset(params.MainnetConfig())
defer resetCfg()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
tests := []struct {
name string
initialPubKeys [][]byte

View File

@@ -66,6 +66,7 @@ go_test(
"proposer_test.go",
"server_test.go",
"status_test.go",
"validator_test.go",
],
embed = [":go_default_library"],
deps = [

View File

@@ -22,11 +22,6 @@ import (
"github.com/prysmaticlabs/prysm/shared/testutil"
)
func init() {
// Use minimal config to reduce test setup time.
params.OverrideBeaconConfig(params.MinimalSpecConfig())
}
func TestSubmitAggregateAndProof_Syncing(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
@@ -109,11 +104,10 @@ func TestSubmitAggregateAndProof_IsAggregatorAndNoAtts(t *testing.T) {
}
func TestSubmitAggregateAndProof_AggregateOk(t *testing.T) {
params.UseMinimalConfig()
params.SetupTestConfigCleanup(t)
c := params.MinimalSpecConfig()
c.TargetAggregatorsPerCommittee = 16
params.OverrideBeaconConfig(c)
defer params.UseMinimalConfig()
db := dbutil.SetupDB(t)
ctx := context.Background()
@@ -172,11 +166,10 @@ func TestSubmitAggregateAndProof_AggregateOk(t *testing.T) {
}
func TestSubmitAggregateAndProof_AggregateNotOk(t *testing.T) {
params.UseMinimalConfig()
params.SetupTestConfigCleanup(t)
c := params.MinimalSpecConfig()
c.TargetAggregatorsPerCommittee = 16
params.OverrideBeaconConfig(c)
defer params.UseMinimalConfig()
db := dbutil.SetupDB(t)
ctx := context.Background()

View File

@@ -28,11 +28,6 @@ import (
"google.golang.org/grpc/status"
)
func init() {
// Use minimal config to reduce test setup time.
params.OverrideBeaconConfig(params.MinimalSpecConfig())
}
func TestProposeAttestation_OK(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
@@ -242,11 +237,9 @@ func TestAttestationDataAtSlot_HandlesFarAwayJustifiedEpoch(t *testing.T) {
// This test breaks if it doesnt use mainnet config
db := dbutil.SetupDB(t)
ctx := context.Background()
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
// Ensure HistoricalRootsLimit matches scenario
cfg := params.BeaconConfig()
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig()
cfg.HistoricalRootsLimit = 8192
params.OverrideBeaconConfig(cfg)

View File

@@ -36,18 +36,13 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
)
func init() {
// Use minimal config to reduce test setup time.
params.OverrideBeaconConfig(params.MinimalSpecConfig())
}
func TestGetBlock_OK(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
testutil.ResetCache()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
beaconState, privKeys := testutil.DeterministicGenesisState(t, 64)
stateRoot, err := beaconState.HashTreeRoot(ctx)
@@ -153,8 +148,8 @@ func TestGetBlock_AddsUnaggregatedAtts(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
beaconState, privKeys := testutil.DeterministicGenesisState(t, params.BeaconConfig().MinGenesisActiveValidatorCount)
stateRoot, err := beaconState.HashTreeRoot(ctx)
@@ -276,8 +271,8 @@ func TestGetBlock_AddsUnaggregatedAtts(t *testing.T) {
func TestProposeBlock_OK(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
genesis := b.NewGenesisBlock([]byte{})
if err := db.SaveBlock(context.Background(), genesis); err != nil {
@@ -324,8 +319,8 @@ func TestComputeStateRoot_OK(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
beaconState, privKeys := testutil.DeterministicGenesisState(t, 100)
stateRoot, err := beaconState.HashTreeRoot(ctx)
@@ -1288,8 +1283,8 @@ func TestFilterAttestation_OK(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
genesis := b.NewGenesisBlock([]byte{})
if err := db.SaveBlock(context.Background(), genesis); err != nil {
t.Fatalf("Could not save genesis block: %v", err)

View File

@@ -32,11 +32,6 @@ import (
logTest "github.com/sirupsen/logrus/hooks/test"
)
func init() {
// Use minimal config to reduce test setup time.
params.OverrideBeaconConfig(params.MinimalSpecConfig())
}
func TestValidatorIndex_OK(t *testing.T) {
db := dbutil.SetupDB(t)
ctx := context.Background()
@@ -121,8 +116,8 @@ func TestWaitForActivation_ContextClosed(t *testing.T) {
func TestWaitForActivation_ValidatorOriginallyExists(t *testing.T) {
db := dbutil.SetupDB(t)
// This test breaks if it doesnt use mainnet config
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
ctx := context.Background()
priv1 := bls.RandKey()

View File

@@ -209,8 +209,8 @@ func TestValidatorStatus_Pending(t *testing.T) {
func TestValidatorStatus_Active(t *testing.T) {
db := dbutil.SetupDB(t)
// This test breaks if it doesnt use mainnet config
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
ctx := context.Background()
pubKey := pubKey(1)
@@ -448,8 +448,8 @@ func TestValidatorStatus_Exited(t *testing.T) {
if err != nil {
t.Fatalf("Could not get signing root %v", err)
}
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
defer params.OverrideBeaconConfig(params.MinimalSpecConfig())
numDeposits := uint64(64)
beaconState, _ := testutil.DeterministicGenesisState(t, numDeposits)
if err := db.SaveState(ctx, beaconState, genesisRoot); err != nil {

View File

@@ -0,0 +1,20 @@
package validator
import (
"os"
"testing"
"github.com/prysmaticlabs/prysm/shared/params"
)
func TestMain(m *testing.M) {
// Use minimal config to reduce test setup time.
prevConfig := params.BeaconConfig().Copy()
params.OverrideBeaconConfig(params.MinimalSpecConfig())
retVal := m.Run()
// Reset configuration.
params.OverrideBeaconConfig(prevConfig)
os.Exit(retVal)
}

View File

@@ -47,6 +47,7 @@ go_test(
"blocks_test.go",
"state_root_cache_fuzz_test.go",
"state_root_test.go",
"stateutil_test.go",
"trie_helpers_test.go",
],
embed = [":go_default_library"],

View File

@@ -1,7 +1,6 @@
package stateutil_test
import (
"os"
"reflect"
"strconv"
"strings"
@@ -11,17 +10,10 @@ import (
"github.com/prysmaticlabs/go-ssz"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/interop"
"github.com/prysmaticlabs/prysm/shared/params"
)
func TestMain(m *testing.M) {
resetCfg := featureconfig.InitWithReset(&featureconfig.Flags{EnableSSZCache: true})
defer resetCfg()
os.Exit(m.Run())
}
func TestState_FieldCount(t *testing.T) {
count := 21
typ := reflect.TypeOf(pb.BeaconState{})

View File

@@ -0,0 +1,14 @@
package stateutil_test
import (
"os"
"testing"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
)
func TestMain(m *testing.M) {
resetCfg := featureconfig.InitWithReset(&featureconfig.Flags{EnableSSZCache: true})
defer resetCfg()
os.Exit(m.Run())
}

View File

@@ -92,6 +92,7 @@ func TestSubscribe_ReceivesAttesterSlashing(t *testing.T) {
topic := "/eth2/%x/attester_slashing"
var wg sync.WaitGroup
wg.Add(1)
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
r.subscribe(topic, r.noopValidator, func(ctx context.Context, msg proto.Message) error {
if err := r.attesterSlashingSubscriber(ctx, msg); err != nil {
@@ -154,6 +155,7 @@ func TestSubscribe_ReceivesProposerSlashing(t *testing.T) {
topic := "/eth2/%x/proposer_slashing"
var wg sync.WaitGroup
wg.Add(1)
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
r.subscribe(topic, r.noopValidator, func(ctx context.Context, msg proto.Message) error {
if err := r.proposerSlashingSubscriber(ctx, msg); err != nil {

View File

@@ -23,7 +23,7 @@ type SSZRoots struct {
}
func runSSZStaticTests(t *testing.T, config string) {
if err := spectest.SetConfig(config); err != nil {
if err := spectest.SetConfig(t, config); err != nil {
t.Fatal(err)
}

View File

@@ -96,45 +96,6 @@ func InitWithReset(c *Flags) func() {
return resetFunc
}
// Copy returns copy of the config object.
func (c *Flags) Copy() *Flags {
return &Flags{
MinimalConfig: c.MinimalConfig,
WriteSSZStateTransitions: c.WriteSSZStateTransitions,
InitSyncNoVerify: c.InitSyncNoVerify,
DisableDynamicCommitteeSubnets: c.DisableDynamicCommitteeSubnets,
SkipBLSVerify: c.SkipBLSVerify,
EnableBackupWebhook: c.EnableStateRefCopy,
PruneEpochBoundaryStates: c.PruneEpochBoundaryStates,
EnableSnappyDBCompression: c.EnableSnappyDBCompression,
ProtectProposer: c.ProtectProposer,
ProtectAttester: c.ProtectAttester,
DisableStrictAttestationPubsubVerification: c.DisableStrictAttestationPubsubVerification,
DisableUpdateHeadPerAttestation: c.DisableUpdateHeadPerAttestation,
EnableByteMempool: c.EnableByteMempool,
EnableDomainDataCache: c.EnableDomainDataCache,
EnableStateGenSigVerify: c.EnableStateGenSigVerify,
CheckHeadState: c.CheckHeadState,
EnableNoise: c.EnableNoise,
DontPruneStateStartUp: c.DontPruneStateStartUp,
NewStateMgmt: c.NewStateMgmt,
DisableInitSyncQueue: c.DisableInitSyncQueue,
EnableFieldTrie: c.EnableFieldTrie,
EnableBlockHTR: c.EnableBlockHTR,
NoInitSyncBatchSaveBlocks: c.NoInitSyncBatchSaveBlocks,
EnableStateRefCopy: c.EnableStateRefCopy,
WaitForSynced: c.WaitForSynced,
DisableForkChoice: c.DisableForkChoice,
BroadcastSlashings: c.BroadcastSlashings,
EnableSSZCache: c.EnableSSZCache,
EnableEth1DataVoteCache: c.EnableEth1DataVoteCache,
EnableSlasherConnection: c.EnableSlasherConnection,
EnableBlockTreeCache: c.EnableBlockTreeCache,
KafkaBootstrapServers: c.KafkaBootstrapServers,
CustomGenesisDelay: c.CustomGenesisDelay,
}
}
// ConfigureBeaconChain sets the global config based
// on what flags are enabled for the beacon-chain client.
func ConfigureBeaconChain(ctx *cli.Context) {

View File

@@ -9,7 +9,10 @@ go_library(
],
importpath = "github.com/prysmaticlabs/prysm/shared/params",
visibility = ["//visibility:public"],
deps = ["//shared/bytesutil:go_default_library"],
deps = [
"//shared/bytesutil:go_default_library",
"@com_github_mohae_deepcopy//:go_default_library",
],
)
go_test(

View File

@@ -2,8 +2,10 @@
package params
import (
"testing"
"time"
"github.com/mohae/deepcopy"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
)
@@ -308,7 +310,7 @@ func UseMinimalConfig() {
// UseMainnetConfig for beacon chain services.
func UseMainnetConfig() {
beaconConfig = defaultBeaconConfig
beaconConfig = MainnetConfig()
}
// OverrideBeaconConfig by replacing the config. The preferred pattern is to
@@ -319,94 +321,22 @@ func OverrideBeaconConfig(c *BeaconChainConfig) {
beaconConfig = c
}
// OverrideBeaconConfigWithReset replaces config and returns reset function
// that helps returning back to the previous state. Useful in tests.
func OverrideBeaconConfigWithReset(c *BeaconChainConfig) func() {
origConfig := beaconConfig.Copy()
OverrideBeaconConfig(c)
return func() {
OverrideBeaconConfig(origConfig)
}
// SetupTestConfigCleanup preserves configurations allowing to modify them within tests without any
// restrictions, everything is restored after the test.
func SetupTestConfigCleanup(t *testing.T) {
prevDefaultBeaconConfig := defaultBeaconConfig.Copy()
prevBeaconConfig := beaconConfig.Copy()
t.Cleanup(func() {
defaultBeaconConfig = prevDefaultBeaconConfig
beaconConfig = prevBeaconConfig
})
}
// Copy returns copy of the config object.
// Copy returns Copy of the config object.
func (c *BeaconChainConfig) Copy() *BeaconChainConfig {
return &BeaconChainConfig{
FarFutureEpoch: c.FarFutureEpoch,
BaseRewardsPerEpoch: c.BaseRewardsPerEpoch,
DepositContractTreeDepth: c.DepositContractTreeDepth,
MinGenesisDelay: c.MinGenesisDelay,
TargetCommitteeSize: c.TargetCommitteeSize,
MaxValidatorsPerCommittee: c.MaxValidatorsPerCommittee,
MaxCommitteesPerSlot: c.MaxCommitteesPerSlot,
MinPerEpochChurnLimit: c.MinPerEpochChurnLimit,
ChurnLimitQuotient: c.ChurnLimitQuotient,
ShuffleRoundCount: c.ShuffleRoundCount,
MinGenesisActiveValidatorCount: c.MinGenesisActiveValidatorCount,
MinGenesisTime: c.MinGenesisTime,
TargetAggregatorsPerCommittee: c.TargetAggregatorsPerCommittee,
HysteresisQuotient: c.HysteresisQuotient,
HysteresisDownwardMultiplier: c.HysteresisDownwardMultiplier,
HysteresisUpwardMultiplier: c.HysteresisUpwardMultiplier,
MinDepositAmount: c.MinDepositAmount,
MaxEffectiveBalance: c.MaxEffectiveBalance,
EjectionBalance: c.EjectionBalance,
EffectiveBalanceIncrement: c.EffectiveBalanceIncrement,
BLSWithdrawalPrefixByte: c.BLSWithdrawalPrefixByte,
ZeroHash: c.ZeroHash,
MinAttestationInclusionDelay: c.MinAttestationInclusionDelay,
SecondsPerSlot: c.SecondsPerSlot,
SlotsPerEpoch: c.SlotsPerEpoch,
MinSeedLookahead: c.MinSeedLookahead,
MaxSeedLookahead: c.MaxSeedLookahead,
EpochsPerEth1VotingPeriod: c.EpochsPerEth1VotingPeriod,
SlotsPerHistoricalRoot: c.SlotsPerHistoricalRoot,
MinValidatorWithdrawabilityDelay: c.MinValidatorWithdrawabilityDelay,
PersistentCommitteePeriod: c.PersistentCommitteePeriod,
MinEpochsToInactivityPenalty: c.MinEpochsToInactivityPenalty,
Eth1FollowDistance: c.Eth1FollowDistance,
SafeSlotsToUpdateJustified: c.SafeSlotsToUpdateJustified,
SecondsPerETH1Block: c.SecondsPerETH1Block,
EpochsPerHistoricalVector: c.EpochsPerHistoricalVector,
EpochsPerSlashingsVector: c.EpochsPerSlashingsVector,
HistoricalRootsLimit: c.HistoricalRootsLimit,
ValidatorRegistryLimit: c.ValidatorRegistryLimit,
BaseRewardFactor: c.BaseRewardFactor,
WhistleBlowerRewardQuotient: c.WhistleBlowerRewardQuotient,
ProposerRewardQuotient: c.ProposerRewardQuotient,
InactivityPenaltyQuotient: c.InactivityPenaltyQuotient,
MinSlashingPenaltyQuotient: c.MinSlashingPenaltyQuotient,
MaxProposerSlashings: c.MaxProposerSlashings,
MaxAttesterSlashings: c.MaxAttesterSlashings,
MaxAttestations: c.MaxAttestations,
MaxDeposits: c.MaxDeposits,
MaxVoluntaryExits: c.MaxVoluntaryExits,
DomainBeaconProposer: c.DomainBeaconProposer,
DomainRandao: c.DomainRandao,
DomainBeaconAttester: c.DomainBeaconAttester,
DomainDeposit: c.DomainDeposit,
DomainVoluntaryExit: c.DomainVoluntaryExit,
DomainSelectionProof: c.DomainSelectionProof,
DomainAggregateAndProof: c.DomainAggregateAndProof,
GweiPerEth: c.GweiPerEth,
LogBlockDelay: c.LogBlockDelay,
BLSSecretKeyLength: c.BLSSecretKeyLength,
BLSPubkeyLength: c.BLSPubkeyLength,
BLSSignatureLength: c.BLSSignatureLength,
DefaultBufferSize: c.DefaultBufferSize,
ValidatorPrivkeyFileName: c.ValidatorPrivkeyFileName,
WithdrawalPrivkeyFileName: c.WithdrawalPrivkeyFileName,
RPCSyncCheck: c.RPCSyncCheck,
GoerliBlockTime: c.GoerliBlockTime,
EmptySignature: c.EmptySignature,
DefaultPageSize: c.DefaultPageSize,
MaxPeersToSync: c.MaxPeersToSync,
SlotsPerArchivedPoint: c.SlotsPerArchivedPoint,
WeakSubjectivityPeriod: c.WeakSubjectivityPeriod,
PruneSlasherStoragePeriod: c.PruneSlasherStoragePeriod,
GenesisForkVersion: c.GenesisForkVersion,
NextForkVersion: c.NextForkVersion,
NextForkEpoch: c.NextForkEpoch,
ForkVersionSchedule: c.ForkVersionSchedule,
config, ok := deepcopy.Copy(*c).(BeaconChainConfig)
if !ok {
config = *defaultBeaconConfig
}
return &config
}

View File

@@ -6,28 +6,29 @@ import (
"github.com/prysmaticlabs/prysm/shared/params"
)
// Test cases can be executed in an arbitrary order. TestOverrideBeaconConfigTestTeardown checks
// that there's no state mutation leak from the previous test, therefore we need a sentinel flag,
// to make sure that previous test case has already been completed and check can be run.
var testOverrideBeaconConfigExecuted bool
func TestOverrideBeaconConfig(t *testing.T) {
// Ensure that param modifications are safe.
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg.SlotsPerEpoch = 5
params.OverrideBeaconConfig(cfg)
if c := params.BeaconConfig(); c.SlotsPerEpoch != 5 {
t.Errorf("Shardcount in BeaconConfig incorrect. Wanted %d, got %d", 5, c.SlotsPerEpoch)
}
testOverrideBeaconConfigExecuted = true
}
func TestOverrideBeaconConfigWithReset(t *testing.T) {
cfg := params.BeaconConfig().Copy()
origSlotsPerEpoch := cfg.SlotsPerEpoch
newSlotsPerEpoch := origSlotsPerEpoch + 42
cfg.SlotsPerEpoch = newSlotsPerEpoch
resetFunc := params.OverrideBeaconConfigWithReset(cfg)
if c := params.BeaconConfig(); c.SlotsPerEpoch != newSlotsPerEpoch {
t.Errorf("Config value is incorrect, want: %d, got %d", newSlotsPerEpoch, c.SlotsPerEpoch)
func TestOverrideBeaconConfigTestTeardown(t *testing.T) {
if !testOverrideBeaconConfigExecuted {
t.Skip("State leak can occur only if state mutating test has already completed")
}
resetFunc()
if c := params.BeaconConfig(); c.SlotsPerEpoch != origSlotsPerEpoch {
t.Errorf("Config value is incorrect, want: %d, got %d", origSlotsPerEpoch, c.SlotsPerEpoch)
cfg := params.BeaconConfig()
if cfg.SlotsPerEpoch == 5 {
t.Fatal("Parameter update has been leaked out of previous test")
}
}

View File

@@ -5,20 +5,21 @@ package spectest
import (
"errors"
"fmt"
"testing"
"github.com/prysmaticlabs/prysm/shared/params"
)
// SetConfig sets the global params for spec tests depending on the option chosen.
func SetConfig(config string) error {
// Provides reset function allowing to get back to the previous configuration at the end of a test.
func SetConfig(t *testing.T, config string) error {
params.SetupTestConfigCleanup(t)
switch config {
case "minimal":
newConfig := params.MinimalSpecConfig()
params.OverrideBeaconConfig(newConfig)
params.OverrideBeaconConfig(params.MinimalSpecConfig())
return nil
case "mainnet":
newConfig := params.MainnetConfig()
params.OverrideBeaconConfig(newConfig)
params.OverrideBeaconConfig(params.MainnetConfig())
return nil
case "":
return errors.New("no config provided")

View File

@@ -7,17 +7,15 @@ import (
)
func TestConfig(t *testing.T) {
err := SetConfig("minimal")
if err != nil {
t.Error(err)
if err := SetConfig(t, "minimal"); err != nil {
t.Fatal(err)
}
if params.BeaconConfig().SlotsPerEpoch != 8 {
t.Errorf("Expected minimal config to be set, but got %d slots per epoch", params.BeaconConfig().SlotsPerEpoch)
}
err = SetConfig("mainnet")
if err != nil {
t.Error(err)
if err := SetConfig(t, "mainnet"); err != nil {
t.Fatal(err)
}
if params.BeaconConfig().SlotsPerEpoch != 32 {
t.Errorf("Expected mainnet config to be set, but got %d slots per epoch", params.BeaconConfig().SlotsPerEpoch)

View File

@@ -26,8 +26,8 @@ func TestGenerateFullBlock_PassesStateTransition(t *testing.T) {
}
func TestGenerateFullBlock_ThousandValidators(t *testing.T) {
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MinimalSpecConfig())
defer params.OverrideBeaconConfig(params.MainnetConfig())
beaconState, privs := DeterministicGenesisState(t, 1024)
conf := &BlockGenConfig{
NumAttestations: 4,
@@ -44,8 +44,8 @@ func TestGenerateFullBlock_ThousandValidators(t *testing.T) {
func TestGenerateFullBlock_Passes4Epochs(t *testing.T) {
// Changing to minimal config as this will process 4 epochs of blocks.
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MinimalSpecConfig())
defer params.OverrideBeaconConfig(params.MainnetConfig())
beaconState, privs := DeterministicGenesisState(t, 64)
conf := &BlockGenConfig{
@@ -76,8 +76,8 @@ func TestGenerateFullBlock_Passes4Epochs(t *testing.T) {
}
func TestGenerateFullBlock_ValidProposerSlashings(t *testing.T) {
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MinimalSpecConfig())
defer params.OverrideBeaconConfig(params.MainnetConfig())
beaconState, privs := DeterministicGenesisState(t, 32)
conf := &BlockGenConfig{
NumProposerSlashings: 1,
@@ -101,8 +101,8 @@ func TestGenerateFullBlock_ValidProposerSlashings(t *testing.T) {
}
func TestGenerateFullBlock_ValidAttesterSlashings(t *testing.T) {
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MinimalSpecConfig())
defer params.OverrideBeaconConfig(params.MainnetConfig())
beaconState, privs := DeterministicGenesisState(t, 32)
conf := &BlockGenConfig{
NumAttesterSlashings: 1,
@@ -126,8 +126,8 @@ func TestGenerateFullBlock_ValidAttesterSlashings(t *testing.T) {
}
func TestGenerateFullBlock_ValidAttestations(t *testing.T) {
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MinimalSpecConfig())
defer params.OverrideBeaconConfig(params.MainnetConfig())
beaconState, privs := DeterministicGenesisState(t, 256)
conf := &BlockGenConfig{

View File

@@ -16,6 +16,7 @@ import (
)
func TestService_RequestHistoricalAttestations(t *testing.T) {
params.SetupTestConfigCleanup(t)
hook := logTest.NewGlobal()
ctrl := gomock.NewController(t)
defer ctrl.Finish()