Fix reported anti patterns (#7501)

* merge var decl

* single append

* replace bytes.Compare -> bytes.Equal

* remove redundant spritnf

* remove redundant spritnf

* trimprefix

* remove redundant nil check

* remove redundant return

* plain channel or unblock on context closing

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
This commit is contained in:
Victor Farazdagi 2020-10-12 19:12:00 +03:00 committed by GitHub
parent a019a0db4c
commit ac1a4a078c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 45 additions and 56 deletions

View File

@ -2,7 +2,6 @@ package blocks_test
import (
"context"
"fmt"
"testing"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
@ -71,9 +70,8 @@ func TestProcessAttesterSlashings_DataNotSlashable(t *testing.T) {
AttesterSlashings: slashings,
},
}
want := fmt.Sprint("attestations are not slashable")
_, err = blocks.ProcessAttesterSlashings(context.Background(), beaconState, b)
assert.ErrorContains(t, want, err)
assert.ErrorContains(t, "attestations are not slashable", err)
}
func TestProcessAttesterSlashings_IndexedAttestationFailedToVerify(t *testing.T) {
@ -116,9 +114,8 @@ func TestProcessAttesterSlashings_IndexedAttestationFailedToVerify(t *testing.T)
},
}
want := fmt.Sprint("validator indices count exceeds MAX_VALIDATORS_PER_COMMITTEE")
_, err = blocks.ProcessAttesterSlashings(context.Background(), beaconState, b)
assert.ErrorContains(t, want, err)
assert.ErrorContains(t, "validator indices count exceeds MAX_VALIDATORS_PER_COMMITTEE", err)
}
func TestProcessAttesterSlashings_AppliesCorrectStatus(t *testing.T) {

View File

@ -21,9 +21,7 @@ func convertWspInput(wsp string) ([]byte, uint64, error) {
}
// Strip prefix "0x" if it's part of the input string.
if strings.HasPrefix(wsp, "0x") {
wsp = wsp[2:]
}
wsp = strings.TrimPrefix(wsp, "0x")
// Get the hexadecimal block root from input string.
s := strings.Split(wsp, ":")

View File

@ -386,6 +386,9 @@ func (s *Service) awaitStateInitialized() {
s.genesisValidatorsRoot = data.GenesisValidatorsRoot
return
}
case <-s.ctx.Done():
log.Debug("Context closed, exiting goroutine")
return
}
}
}

View File

@ -62,14 +62,11 @@ func (p *FakeP2P) FindPeersWithSubnet(_ context.Context, _ uint64) (bool, error)
}
// RefreshENR mocks the p2p func.
func (p *FakeP2P) RefreshENR() {
return
}
func (p *FakeP2P) RefreshENR() {}
// LeaveTopic -- fake.
func (p *FakeP2P) LeaveTopic(_ string) error {
return nil
}
// Metadata -- fake.

View File

@ -57,6 +57,7 @@ go_test(
"block_reader_test.go",
"deposit_test.go",
"log_processing_test.go",
"powchain_test.go",
"service_test.go",
],
embed = [":go_default_library"],

View File

@ -4,7 +4,6 @@ import (
"context"
"encoding/binary"
"fmt"
"io/ioutil"
"math/big"
"testing"
"time"
@ -26,16 +25,10 @@ import (
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
"github.com/prysmaticlabs/prysm/shared/testutil/require"
"github.com/prysmaticlabs/prysm/shared/trieutil"
"github.com/sirupsen/logrus"
logTest "github.com/sirupsen/logrus/hooks/test"
"gopkg.in/d4l3k/messagediff.v1"
)
func init() {
logrus.SetLevel(logrus.DebugLevel)
logrus.SetOutput(ioutil.Discard)
}
func TestProcessDepositLog_OK(t *testing.T) {
hook := logTest.NewGlobal()
testutil.ResetCache()
@ -354,11 +347,9 @@ func TestProcessETH2GenesisLog(t *testing.T) {
// Receive the chain started event.
for started := false; !started; {
select {
case event := <-stateChannel:
if event.Type == statefeed.ChainStarted {
started = true
}
event := <-stateChannel
if event.Type == statefeed.ChainStarted {
started = true
}
}
@ -449,11 +440,9 @@ func TestProcessETH2GenesisLog_CorrectNumOfDeposits(t *testing.T) {
// Receive the chain started event.
for started := false; !started; {
select {
case event := <-stateChannel:
if event.Type == statefeed.ChainStarted {
started = true
}
event := <-stateChannel
if event.Type == statefeed.ChainStarted {
started = true
}
}

View File

@ -0,0 +1,16 @@
package powchain
import (
"io/ioutil"
"os"
"testing"
"github.com/sirupsen/logrus"
)
func TestMain(m *testing.M) {
logrus.SetLevel(logrus.DebugLevel)
logrus.SetOutput(ioutil.Discard)
os.Exit(m.Run())
}

View File

@ -722,6 +722,6 @@ func (s *Service) logTillChainStart() {
log.WithFields(logrus.Fields{
"Extra validators needed": valNeeded,
"Time till minimum genesis": fmt.Sprintf("%s", time.Duration(secondsLeft)*time.Second),
"Time till minimum genesis": time.Duration(secondsLeft) * time.Second,
}).Infof("Currently waiting for chainstart")
}

View File

@ -3,7 +3,6 @@ package rpc
import (
"context"
"errors"
"fmt"
"io/ioutil"
"testing"
"time"
@ -69,7 +68,7 @@ func TestRPC_InsecureEndpoint(t *testing.T) {
rpcService.Start()
require.LogsContain(t, hook, fmt.Sprint("listening on port"))
require.LogsContain(t, hook, "listening on port")
require.LogsContain(t, hook, "You are using an insecure gRPC server")
assert.NoError(t, rpcService.Stop())
}

View File

@ -1685,9 +1685,7 @@ func TestProposer_Eth1Data_MajorityVote(t *testing.T) {
hash := majorityVoteEth1Data.BlockHash
expectedHash := []byte("second")
if bytes.Compare(hash, expectedHash) != 0 {
t.Errorf("Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
}
assert.Equal(t, true, bytes.Equal(hash, expectedHash), "Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
})
t.Run("only one block at earliest valid time - choose this block", func(t *testing.T) {
@ -1717,9 +1715,7 @@ func TestProposer_Eth1Data_MajorityVote(t *testing.T) {
hash := majorityVoteEth1Data.BlockHash
expectedHash := []byte("earliest")
if bytes.Compare(hash, expectedHash) != 0 {
t.Errorf("Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
}
assert.Equal(t, true, bytes.Equal(hash, expectedHash), "Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
})
t.Run("vote on last block before range - choose next block", func(t *testing.T) {
@ -1754,9 +1750,7 @@ func TestProposer_Eth1Data_MajorityVote(t *testing.T) {
expectedHash := make([]byte, 32)
copy(expectedHash, "first")
if bytes.Compare(hash, expectedHash) != 0 {
t.Errorf("Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
}
assert.Equal(t, true, bytes.Equal(hash, expectedHash), "Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
})
t.Run("no deposits - choose chain start eth1data", func(t *testing.T) {
@ -1794,9 +1788,7 @@ func TestProposer_Eth1Data_MajorityVote(t *testing.T) {
hash := majorityVoteEth1Data.BlockHash
expectedHash := []byte("eth1data")
if bytes.Compare(hash, expectedHash) != 0 {
t.Errorf("Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
}
assert.Equal(t, true, bytes.Equal(hash, expectedHash), "Chosen eth1data for block hash %v vs expected %v", hash, expectedHash)
})
}

View File

@ -311,6 +311,9 @@ func TestBlocksFetcher_RoundRobin(t *testing.T) {
}
wg.Done()
case <-ctx.Done():
log.Debug("Context closed, exiting goroutine")
return unionRespBlocks, nil
}
}
}

View File

@ -83,8 +83,7 @@ func TestServer_IsSlashableAttestation(t *testing.T) {
iatt.Data.Slot += j
root, err := helpers.ComputeSigningRoot(iatt.Data, domain)
require.NoError(t, err)
var validatorSig bls.Signature
validatorSig = keys[iatt.AttestingIndices[0]].Sign(root[:])
validatorSig := keys[iatt.AttestingIndices[0]].Sign(root[:])
marshalledSig := validatorSig.Marshal()
iatt.Signature = marshalledSig
slashings, err := server.IsSlashableAttestation(ctx, iatt)

View File

@ -3,7 +3,6 @@ package rpc
import (
"context"
"errors"
"fmt"
"testing"
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
@ -40,6 +39,6 @@ func TestRPC_InsecureEndpoint(t *testing.T) {
rpcService.Start()
require.LogsContain(t, hook, fmt.Sprint("listening on port"))
require.LogsContain(t, hook, "listening on port")
require.NoError(t, rpcService.Stop())
}

View File

@ -302,7 +302,7 @@ func (w *Wallet) InitializeKeymanager(
if err != nil {
return nil, err
}
if keys == nil || len(keys) == 0 {
if len(keys) == 0 {
return nil, errors.New("please recreate your wallet with wallet-v2 create")
}
if err := w.SaveHashedPassword(ctx); err != nil {

View File

@ -59,9 +59,7 @@ func NewUnencrypted(input string) (*Unencrypted, string, error) {
return nil, unencryptedOptsHelp, err
}
sks := make([]bls.SecretKey, 0, len(keyMap))
for _, key := range keyMap {
sks = append(sks, key)
}
sks = append(sks, keyMap...)
km := &Unencrypted{
Direct: &Direct{

View File

@ -309,9 +309,7 @@ func pathsToVerificationRegexes(paths []string) []*regexp.Regexp {
if len(parts) == 1 {
parts = append(parts, ".*")
}
if strings.HasPrefix(parts[1], "^") {
parts[1] = parts[1][1:]
}
parts[1] = strings.TrimPrefix(parts[1], "^")
var specifier string
if strings.HasSuffix(parts[1], "$") {
specifier = fmt.Sprintf("^%s/%s", parts[0], parts[1])

View File

@ -154,7 +154,7 @@ func (s *Server) BackupAccounts(
return nil, status.Errorf(codes.Internal, "Could not backup accounts for derived keymanager: %v", err)
}
}
if keystoresToBackup == nil || len(keystoresToBackup) == 0 {
if len(keystoresToBackup) == 0 {
return nil, status.Error(codes.InvalidArgument, "No keystores to backup")
}