Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coverage for common package #5294

Merged
merged 7 commits into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
513 changes: 470 additions & 43 deletions common/configParser_test.go

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions common/converters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,3 +330,35 @@ func TestShardAssignment(t *testing.T) {
fmt.Printf("Shard %d:\n\t\t%d accounts\n", sh, cnt)
}
}

func TestProcessDestinationShardAsObserver(t *testing.T) {
t.Parallel()

t.Run("empty shard should error", testProcessDestinationShardAsObserver("", 0, "option DestinationShardAsObserver is not set in prefs.toml"))
t.Run("disabled shard should return disabled",
testProcessDestinationShardAsObserver(common.NotSetDestinationShardID, common.DisabledShardIDAsObserver, ""))
t.Run("metachain should return metachain",
testProcessDestinationShardAsObserver("metachain", common.MetachainShardId, ""))
t.Run("MeTaChAiN should return metachain",
testProcessDestinationShardAsObserver("MeTaChAiN", common.MetachainShardId, ""))
t.Run("METACHAIN should return metachain",
testProcessDestinationShardAsObserver("METACHAIN", common.MetachainShardId, ""))
t.Run("invalid uint should error",
testProcessDestinationShardAsObserver("not uint", 0, "error parsing DestinationShardAsObserver"))
t.Run("should work",
testProcessDestinationShardAsObserver("1", 1, ""))
}

func testProcessDestinationShardAsObserver(providedShard string, expectedShard uint32, expectedError string) func(t *testing.T) {
return func(t *testing.T) {
t.Parallel()

shard, err := common.ProcessDestinationShardAsObserver(providedShard)
if len(expectedError) == 0 {
require.NoError(t, err)
} else {
require.True(t, strings.Contains(err.Error(), expectedError))
}
require.Equal(t, expectedShard, shard)
}
}
66 changes: 63 additions & 3 deletions common/enablers/enableEpochsHandler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ func TestNewEnableEpochsHandler_EpochConfirmed(t *testing.T) {

handler.EpochConfirmed(math.MaxUint32, 0)

assert.Equal(t, cfg.BlockGasAndFeesReCheckEnableEpoch, handler.BlockGasAndFeesReCheckEnableEpoch())
assert.True(t, handler.IsSCDeployFlagEnabled())
assert.True(t, handler.IsBuiltInFunctionsFlagEnabled())
assert.True(t, handler.IsRelayedTransactionsFlagEnabled())
Expand Down Expand Up @@ -234,6 +233,15 @@ func TestNewEnableEpochsHandler_EpochConfirmed(t *testing.T) {
assert.True(t, handler.IsMultiClaimOnDelegationEnabled())
assert.True(t, handler.IsChangeUsernameEnabled())
assert.True(t, handler.IsConsistentTokensValuesLengthCheckEnabled())
assert.True(t, handler.IsFixAsyncCallbackCheckFlagEnabled())
assert.True(t, handler.IsSaveToSystemAccountFlagEnabled())
assert.True(t, handler.IsCheckFrozenCollectionFlagEnabled())
assert.True(t, handler.IsSendAlwaysFlagEnabled())
assert.True(t, handler.IsValueLengthCheckFlagEnabled())
assert.True(t, handler.IsCheckTransferFlagEnabled())
assert.True(t, handler.IsTransferToMetaFlagEnabled())
assert.True(t, handler.IsESDTNFTImprovementV1FlagEnabled())

})
t.Run("flags with == condition should be set, along with all >=", func(t *testing.T) {
t.Parallel()
Expand All @@ -250,7 +258,6 @@ func TestNewEnableEpochsHandler_EpochConfirmed(t *testing.T) {

handler.EpochConfirmed(epoch, 0)

assert.Equal(t, cfg.BlockGasAndFeesReCheckEnableEpoch, handler.BlockGasAndFeesReCheckEnableEpoch())
assert.True(t, handler.IsSCDeployFlagEnabled())
assert.True(t, handler.IsBuiltInFunctionsFlagEnabled())
assert.True(t, handler.IsRelayedTransactionsFlagEnabled())
Expand Down Expand Up @@ -343,6 +350,14 @@ func TestNewEnableEpochsHandler_EpochConfirmed(t *testing.T) {
assert.True(t, handler.IsMultiClaimOnDelegationEnabled())
assert.True(t, handler.IsChangeUsernameEnabled())
assert.True(t, handler.IsConsistentTokensValuesLengthCheckEnabled())
assert.True(t, handler.IsFixAsyncCallbackCheckFlagEnabled())
assert.True(t, handler.IsSaveToSystemAccountFlagEnabled())
assert.True(t, handler.IsCheckFrozenCollectionFlagEnabled())
assert.True(t, handler.IsSendAlwaysFlagEnabled())
assert.True(t, handler.IsValueLengthCheckFlagEnabled())
assert.True(t, handler.IsCheckTransferFlagEnabled())
assert.True(t, handler.IsTransferToMetaFlagEnabled())
assert.True(t, handler.IsESDTNFTImprovementV1FlagEnabled())
})
t.Run("flags with < should be set", func(t *testing.T) {
t.Parallel()
Expand All @@ -354,7 +369,6 @@ func TestNewEnableEpochsHandler_EpochConfirmed(t *testing.T) {

handler.EpochConfirmed(epoch, 0)

assert.Equal(t, cfg.BlockGasAndFeesReCheckEnableEpoch, handler.BlockGasAndFeesReCheckEnableEpoch())
assert.False(t, handler.IsSCDeployFlagEnabled())
assert.False(t, handler.IsBuiltInFunctionsFlagEnabled())
assert.False(t, handler.IsRelayedTransactionsFlagEnabled())
Expand Down Expand Up @@ -447,5 +461,51 @@ func TestNewEnableEpochsHandler_EpochConfirmed(t *testing.T) {
assert.False(t, handler.IsMultiClaimOnDelegationEnabled())
assert.False(t, handler.IsChangeUsernameEnabled())
assert.False(t, handler.IsConsistentTokensValuesLengthCheckEnabled())
assert.False(t, handler.IsFixAsyncCallbackCheckFlagEnabled())
assert.False(t, handler.IsSaveToSystemAccountFlagEnabled())
assert.False(t, handler.IsCheckFrozenCollectionFlagEnabled())
assert.False(t, handler.IsSendAlwaysFlagEnabled())
assert.False(t, handler.IsValueLengthCheckFlagEnabled())
assert.False(t, handler.IsCheckTransferFlagEnabled())
assert.False(t, handler.IsTransferToMetaFlagEnabled())
assert.False(t, handler.IsESDTNFTImprovementV1FlagEnabled())
})
}

func TestNewEnableEpochsHandler_Getters(t *testing.T) {
t.Parallel()

cfg := createEnableEpochsConfig()
handler, _ := NewEnableEpochsHandler(cfg, &epochNotifier.EpochNotifierStub{})
require.NotNil(t, handler)

require.Equal(t, cfg.ScheduledMiniBlocksEnableEpoch, handler.ScheduledMiniBlocksEnableEpoch())
assert.Equal(t, cfg.BlockGasAndFeesReCheckEnableEpoch, handler.BlockGasAndFeesReCheckEnableEpoch())
require.Equal(t, cfg.StakingV2EnableEpoch, handler.StakingV2EnableEpoch())
require.Equal(t, cfg.SwitchJailWaitingEnableEpoch, handler.SwitchJailWaitingEnableEpoch())
require.Equal(t, cfg.BalanceWaitingListsEnableEpoch, handler.BalanceWaitingListsEnableEpoch())
require.Equal(t, cfg.WaitingListFixEnableEpoch, handler.WaitingListFixEnableEpoch())
require.Equal(t, cfg.MultiESDTTransferFixOnCallBackOnEnableEpoch, handler.MultiESDTTransferAsyncCallBackEnableEpoch())
require.Equal(t, cfg.FixOOGReturnCodeEnableEpoch, handler.FixOOGReturnCodeEnableEpoch())
require.Equal(t, cfg.RemoveNonUpdatedStorageEnableEpoch, handler.RemoveNonUpdatedStorageEnableEpoch())
require.Equal(t, cfg.CreateNFTThroughExecByCallerEnableEpoch, handler.CreateNFTThroughExecByCallerEnableEpoch())
require.Equal(t, cfg.FailExecutionOnEveryAPIErrorEnableEpoch, handler.FixFailExecutionOnErrorEnableEpoch())
require.Equal(t, cfg.ManagedCryptoAPIsEnableEpoch, handler.ManagedCryptoAPIEnableEpoch())
require.Equal(t, cfg.DisableExecByCallerEnableEpoch, handler.DisableExecByCallerEnableEpoch())
require.Equal(t, cfg.RefactorContextEnableEpoch, handler.RefactorContextEnableEpoch())
require.Equal(t, cfg.CheckExecuteOnReadOnlyEnableEpoch, handler.CheckExecuteReadOnlyEnableEpoch())
require.Equal(t, cfg.StorageAPICostOptimizationEnableEpoch, handler.StorageAPICostOptimizationEnableEpoch())
require.Equal(t, cfg.MiniBlockPartialExecutionEnableEpoch, handler.MiniBlockPartialExecutionEnableEpoch())
require.Equal(t, cfg.RefactorPeersMiniBlocksEnableEpoch, handler.RefactorPeersMiniBlocksEnableEpoch())
require.Equal(t, cfg.RelayedNonceFixEnableEpoch, handler.RelayedNonceFixEnableEpoch())
}

func TestEnableEpochsHandler_IsInterfaceNil(t *testing.T) {
t.Parallel()

var handler *enableEpochsHandler
require.True(t, handler.IsInterfaceNil())

handler, _ = NewEnableEpochsHandler(createEnableEpochsConfig(), &epochNotifier.EpochNotifierStub{})
require.False(t, handler.IsInterfaceNil())
}
29 changes: 23 additions & 6 deletions common/forking/gasSchedule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"time"

"github.com/multiversx/mx-chain-core-go/core"
"github.com/multiversx/mx-chain-core-go/core/check"
"github.com/multiversx/mx-chain-go/common"
"github.com/multiversx/mx-chain-go/common/mock"
"github.com/multiversx/mx-chain-go/config"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -40,19 +40,25 @@ func TestNewGasScheduleNotifierConstructorErrors(t *testing.T) {
args.GasScheduleConfig = config.GasScheduleConfig{}
g, err := NewGasScheduleNotifier(args)
assert.Equal(t, err, core.ErrInvalidGasScheduleConfig)
assert.True(t, check.IfNil(g))
assert.Nil(t, g)

args = createGasScheduleNotifierArgs()
args.EpochNotifier = nil
g, err = NewGasScheduleNotifier(args)
assert.Equal(t, err, core.ErrNilEpochStartNotifier)
assert.True(t, check.IfNil(g))
assert.Nil(t, g)

args = createGasScheduleNotifierArgs()
args.ConfigDir = ""
g, err = NewGasScheduleNotifier(args)
assert.NotNil(t, err)
assert.True(t, check.IfNil(g))
assert.Nil(t, g)

args = createGasScheduleNotifierArgs()
args.WasmVMChangeLocker = nil
g, err = NewGasScheduleNotifier(args)
assert.Equal(t, err, common.ErrNilWasmChangeLocker)
assert.Nil(t, g)
}

func TestNewGasScheduleNotifier(t *testing.T) {
Expand All @@ -61,7 +67,7 @@ func TestNewGasScheduleNotifier(t *testing.T) {
args := createGasScheduleNotifierArgs()
g, err := NewGasScheduleNotifier(args)
assert.Nil(t, err)
assert.False(t, check.IfNil(g))
assert.NotNil(t, g)
}

func TestGasScheduleNotifier_RegisterNotifyHandlerNilHandlerShouldNotAdd(t *testing.T) {
Expand Down Expand Up @@ -154,7 +160,8 @@ func TestGasScheduleNotifier_CheckEpochShouldCall(t *testing.T) {

assert.Equal(t, uint32(2), atomic.LoadUint32(&numCalled))
assert.Equal(t, newEpoch, g.currentEpoch)
assert.Equal(t, g.LatestGasSchedule()["BaseOperationCost"]["AoTPreparePerByte"], uint64(300))
assert.Equal(t, uint64(300), g.LatestGasSchedule()["BaseOperationCost"]["AoTPreparePerByte"])
assert.Equal(t, uint64(300), g.LatestGasScheduleCopy()["BaseOperationCost"]["AoTPreparePerByte"])
}

func TestGasScheduleNotifier_CheckEpochInSyncShouldWork(t *testing.T) {
Expand Down Expand Up @@ -219,3 +226,13 @@ func testGasScheduleNotifierDeadlock(t *testing.T) {
require.Fail(t, "deadlock detected in EpochConfirmed function")
}
}

func TestGasScheduleNotifier_IsInterfaceNil(t *testing.T) {
t.Parallel()

var g *gasScheduleNotifier
require.True(t, g.IsInterfaceNil())

g, _ = NewGasScheduleNotifier(createGasScheduleNotifierArgs())
require.False(t, g.IsInterfaceNil())
}
10 changes: 10 additions & 0 deletions common/holders/receiptsHolder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,13 @@ func TestNewReceiptsHolder(t *testing.T) {
holder = NewReceiptsHolder([]*block.MiniBlock{{SenderShardID: 42}, {SenderShardID: 43}})
require.Equal(t, []*block.MiniBlock{{SenderShardID: 42}, {SenderShardID: 43}}, holder.GetMiniblocks())
}

func TestReceiptsHolder_IsInterfaceNil(t *testing.T) {
t.Parallel()

var holder *receiptsHolder
require.True(t, holder.IsInterfaceNil())

holder = NewReceiptsHolder([]*block.MiniBlock{})
require.False(t, holder.IsInterfaceNil())
}
10 changes: 10 additions & 0 deletions common/holders/rootHashHolder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,13 @@ func TestNewRootHashHolder_String(t *testing.T) {
expectedString := "root hash rootHash, epoch 5, has value true"
assert.Equal(t, expectedString, holder.String())
}

func TestNewRootHashHolder_IsInterfaceNil(t *testing.T) {
t.Parallel()

var holder *rootHashHolder
require.True(t, holder.IsInterfaceNil())

holder = NewRootHashHolder([]byte("rootHash"), core.OptionalUint32{})
require.False(t, holder.IsInterfaceNil())
}
10 changes: 5 additions & 5 deletions common/logging/errorLogging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestLogErrAsLevelExceptAsDebugIfClosingError(t *testing.T) {
},
}

logErrAsLevelExceptAsDebugIfClosingError(log, logger.LogWarning, testError, "test",
LogErrAsWarnExceptAsDebugIfClosingError(log, testError, "test",
"a", 7,
"b", []byte("hash"),
"err", testError.Error(),
Expand All @@ -45,7 +45,7 @@ func TestLogErrAsLevelExceptAsDebugIfClosingError(t *testing.T) {
},
}

logErrAsLevelExceptAsDebugIfClosingError(log, logger.LogWarning, dbError, "test",
LogErrAsWarnExceptAsDebugIfClosingError(log, dbError, "test",
"a", 7,
"b", []byte("hash"),
"err", dbError.Error(),
Expand All @@ -56,8 +56,8 @@ func TestLogErrAsLevelExceptAsDebugIfClosingError(t *testing.T) {
t.Run("no panic on bad input", func(t *testing.T) {
log := logger.GetOrCreate("test")

logErrAsLevelExceptAsDebugIfClosingError(log, logger.LogError, testError, "", "a", nil)
logErrAsLevelExceptAsDebugIfClosingError(log, logger.LogError, nil, "", "a", nil)
logErrAsLevelExceptAsDebugIfClosingError(nil, logger.LogError, testError, "")
LogErrAsErrorExceptAsDebugIfClosingError(log, testError, "", "a", nil)
LogErrAsErrorExceptAsDebugIfClosingError(log, nil, "", "a", nil)
LogErrAsErrorExceptAsDebugIfClosingError(nil, testError, "")
})
}
13 changes: 13 additions & 0 deletions common/pidQueue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ func TestPidQueue_PromoteTwoElementsShouldWork(t *testing.T) {
pq.Push(pid0)
pq.Push(pid1)

pq.Promote(-1) // early return
pq.Promote(2) // early return

pq.Promote(0)

assert.Equal(t, 0, pq.IndexOf(pid1))
Expand Down Expand Up @@ -236,3 +239,13 @@ func TestPidQueue_TestConcurrency(t *testing.T) {

wg.Wait()
}

func TestPidQueue_IsInterfaceNil(t *testing.T) {
t.Parallel()

var pq *pidQueue
assert.True(t, pq.IsInterfaceNil())

pq = NewPidQueue()
assert.False(t, pq.IsInterfaceNil())
}
23 changes: 23 additions & 0 deletions common/reflectcommon/structFieldsUpdate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ func TestAdaptStructureValueBasedOnPath(t *testing.T) {
require.Equal(t, "invalid structure name: InvalidFieldName", err.Error())
})

t.Run("empty path, should not panic, but catch the error", func(t *testing.T) {
t.Parallel()

expectedNewValue := "%5050"
cfg := &config.Config{}

err := AdaptStructureValueBasedOnPath(cfg, "", expectedNewValue)

require.Equal(t, "empty path to update", err.Error())
})

t.Run("should error when invalid field during multiple levels depth", func(t *testing.T) {
t.Parallel()

Expand All @@ -57,6 +68,18 @@ func TestAdaptStructureValueBasedOnPath(t *testing.T) {
require.Equal(t, "invalid structure name: FilePath2", err.Error())
})

t.Run("should error when setting on unsupported type", func(t *testing.T) {
t.Parallel()

path := "TrieSyncStorage.DB"
expectedNewValue := "provided value"
cfg := &config.Config{}

err := AdaptStructureValueBasedOnPath(cfg, path, expectedNewValue)

require.ErrorContains(t, err, "unsupported type <struct> when trying to set the value <provided value>")
})

t.Run("should error when setting invalid uint32", func(t *testing.T) {
t.Parallel()

Expand Down
2 changes: 2 additions & 0 deletions common/statistics/disabled/netStatistics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,6 @@ func TestNetStatistics_MethodsShouldNotPanic(t *testing.T) {
assert.Equal(t, notAvailable, message)

stats.EpochConfirmed(0, 0)

assert.Nil(t, stats.Close())
}
2 changes: 2 additions & 0 deletions common/statistics/machine/netStatistics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,9 @@ func TestNetStatistics_EpochConfirmed(t *testing.T) {
ns.EpochConfirmed(0, 0)

assert.Equal(t, uint64(0), ns.TotalBytesSentInCurrentEpoch())
assert.Equal(t, "0 B", ns.TotalSentInCurrentEpoch())
assert.Equal(t, uint64(0), ns.TotalBytesReceivedInCurrentEpoch())
assert.Equal(t, "0 B", ns.TotalReceivedInCurrentEpoch())
assert.Equal(t, uint64(0), ns.BpsRecvPeak())
assert.Equal(t, uint64(0), ns.BpsSentPeak())
}
Expand Down
32 changes: 32 additions & 0 deletions common/statistics/resourceMonitor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
errorsGo "errors"
"fmt"
"testing"
"time"

stats "github.com/multiversx/mx-chain-go/common/statistics"
"github.com/multiversx/mx-chain-go/common/statistics/disabled"
Expand Down Expand Up @@ -84,3 +85,34 @@ func TestResourceMonitor_SaveStatisticsShouldNotPanic(t *testing.T) {
assert.Nil(t, err)
resourceMonitor.LogStatistics()
}

func TestResourceMonitor_StartMonitoringShouldNotPanic(t *testing.T) {
t.Parallel()

defer func() {
r := recover()
if r != nil {
assert.Fail(t, fmt.Sprintf("test should not have paniced: %v", r))
}
}()

cfg := generateMockConfig()
resourceMonitor, err := stats.NewResourceMonitor(cfg, disabled.NewDisabledNetStatistics())

assert.Nil(t, err)
resourceMonitor.StartMonitoring()
threshold := time.Millisecond * 300
time.Sleep(time.Second*time.Duration(cfg.ResourceStats.RefreshIntervalInSec) + threshold) // allow one loop

assert.Nil(t, resourceMonitor.Close())
}

func TestResourceMonitor_IsInterfaceNil(t *testing.T) {
t.Parallel()

resourceMonitor, _ := stats.NewResourceMonitor(generateMockConfig(), nil)
assert.True(t, resourceMonitor.IsInterfaceNil())

resourceMonitor, _ = stats.NewResourceMonitor(generateMockConfig(), disabled.NewDisabledNetStatistics())
assert.False(t, resourceMonitor.IsInterfaceNil())
}