From c2f1f460477d3c6add29c57aea2f3967522642ba Mon Sep 17 00:00:00 2001 From: Arran Schlosberg <519948+ARR4N@users.noreply.github.com> Date: Fri, 2 Aug 2024 16:29:14 +0100 Subject: [PATCH] refactor: introduce `*test` packages in lieu of `//go:build test` (#3238) --- .golangci.yml | 2 +- cache/{test_cacher.go => cachetest/cacher.go} | 11 +- cache/lru_cache_test.go | 9 +- cache/lru_sized_cache_test.go | 13 +- cache/metercacher/cache_test.go | 5 +- .../shared_memory.go} | 77 ++++---- .../gsharedmemory/shared_memory_test.go | 3 +- chains/atomic/shared_memory_test.go | 7 +- .../{test_codec.go => codectest/codectest.go} | 178 +++++++++--------- codec/hierarchycodec/codec_test.go | 8 +- codec/linearcodec/codec_test.go | 8 +- database/corruptabledb/db_test.go | 9 +- .../benchmark.go} | 25 ++- .../{test_database.go => dbtest/dbtest.go} | 177 +++++++++-------- database/encdb/db_test.go | 15 +- database/leveldb/db_test.go | 15 +- database/memdb/db_test.go | 16 +- database/meterdb/db_test.go | 15 +- database/pebbledb/db_test.go | 16 +- database/prefixdb/db_test.go | 16 +- database/rpcdb/db_test.go | 16 +- database/versiondb/db_test.go | 15 +- go.mod | 2 +- go.sum | 4 +- ids/aliases_test.go | 8 +- ids/galiasreader/alias_reader_test.go | 3 +- ids/{test_aliases.go => idstest/aliases.go} | 42 +++-- network/p2p/gossip/gossip_test.go | 11 +- network/p2p/network_test.go | 36 ++-- network/p2p/validators_test.go | 6 +- scripts/lint.sh | 5 +- .../{test_snowflake.go => snowflake_test.go} | 2 - .../avalanche/bootstrap/bootstrapper_test.go | 12 +- .../queue/{test_job.go => job_test.go} | 2 - .../queue/{test_parser.go => parser_test.go} | 2 - .../avalanche/state/unique_vertex_test.go | 3 +- .../builder.go} | 7 +- .../manager.go} | 10 +- .../{test_parser.go => vertextest/parser.go} | 7 +- .../storage.go} | 7 +- .../vertex/{test_vm.go => vertextest/vm.go} | 11 +- .../bootstrap_tracker.go} | 4 +- .../bootstrapper.go} | 8 +- .../test_engine.go => enginetest/engine.go} | 21 +-- .../test_sender.go => enginetest/sender.go} | 21 +-- .../test_timer.go => enginetest/timer.go} | 8 +- .../{common/test_vm.go => enginetest/vm.go} | 23 ++- snow/engine/snowman/block/batched_vm_test.go | 9 +- .../batched_vm.go} | 7 +- .../state_summary.go} | 13 +- .../state_syncable_vm.go} | 24 +-- .../block/{test_vm.go => blocktest/vm.go} | 11 +- .../snowman/bootstrap/bootstrapper_test.go | 34 ++-- snow/engine/snowman/config_test.go | 8 +- snow/engine/snowman/engine_test.go | 63 ++++--- snow/engine/snowman/getter/getter_test.go | 10 +- .../snowman/syncer/state_syncer_test.go | 38 ++-- snow/engine/snowman/syncer/utils_test.go | 17 +- .../{test_benchable.go => benchable_test.go} | 2 - snow/networking/handler/handler_test.go | 33 ++-- snow/networking/handler/health_test.go | 8 +- snow/networking/router/chain_router_test.go | 41 ++-- snow/networking/sender/sender_test.go | 24 ++- .../external.go} | 7 +- snow/snowtest/context.go | 4 +- .../state.go} | 12 +- vms/avm/environment_test.go | 3 +- vms/avm/network/network_test.go | 5 +- vms/platformvm/block/builder/helpers_test.go | 5 +- vms/platformvm/block/executor/helpers_test.go | 6 +- vms/platformvm/validator_set_property_test.go | 3 +- vms/platformvm/vm_test.go | 10 +- vms/platformvm/warp/gwarp/signer_test.go | 3 +- vms/platformvm/warp/signer_test.go | 8 +- .../signertest.go} | 19 +- vms/platformvm/warp/validator_test.go | 3 +- vms/proposervm/batched_vm_test.go | 14 +- vms/proposervm/proposer/windower_test.go | 7 +- vms/proposervm/state_syncable_vm_test.go | 20 +- vms/proposervm/vm_test.go | 47 ++--- vms/rpcchainvm/state_syncable_vm_test.go | 3 +- wallet/chain/p/builder_test.go | 24 +-- wallet/chain/x/builder_test.go | 18 +- .../{test_utxos.go => utxotest/utxotest.go} | 11 +- x/merkledb/db_test.go | 9 +- 85 files changed, 769 insertions(+), 735 deletions(-) rename cache/{test_cacher.go => cachetest/cacher.go} (91%) rename chains/atomic/{test_shared_memory.go => atomictest/shared_memory.go} (76%) rename codec/{test_codec.go => codectest/codectest.go} (84%) rename database/{benchmark_database.go => dbtest/benchmark.go} (82%) rename database/{test_database.go => dbtest/dbtest.go} (85%) rename ids/{test_aliases.go => idstest/aliases.go} (54%) rename snow/consensus/snowball/{test_snowflake.go => snowflake_test.go} (99%) rename snow/engine/avalanche/bootstrap/queue/{test_job.go => job_test.go} (99%) rename snow/engine/avalanche/bootstrap/queue/{test_parser.go => parser_test.go} (97%) rename snow/engine/avalanche/vertex/{test_builder.go => vertextest/builder.go} (87%) rename snow/engine/avalanche/vertex/{test_manager.go => vertextest/manager.go} (76%) rename snow/engine/avalanche/vertex/{test_parser.go => vertextest/parser.go} (86%) rename snow/engine/avalanche/vertex/{test_storage.go => vertextest/storage.go} (93%) rename snow/engine/avalanche/vertex/{test_vm.go => vertextest/vm.go} (83%) rename snow/engine/{common/test_bootstrap_tracker.go => enginetest/bootstrap_tracker.go} (98%) rename snow/engine/{common/test_bootstrapper.go => enginetest/bootstrapper.go} (83%) rename snow/engine/{common/test_engine.go => enginetest/engine.go} (97%) rename snow/engine/{common/test_sender.go => enginetest/sender.go} (97%) rename snow/engine/{common/test_timer.go => enginetest/timer.go} (85%) rename snow/engine/{common/test_vm.go => enginetest/vm.go} (93%) rename snow/engine/snowman/block/{test_batched_vm.go => blocktest/batched_vm.go} (93%) rename snow/engine/snowman/block/{test_state_summary.go => blocktest/state_summary.go} (69%) rename snow/engine/snowman/block/{test_state_syncable_vm.go => blocktest/state_syncable_vm.go} (81%) rename snow/engine/snowman/block/{test_vm.go => blocktest/vm.go} (94%) rename snow/networking/benchlist/{test_benchable.go => benchable_test.go} (98%) rename snow/networking/sender/{test_external_sender.go => sendertest/external.go} (89%) rename snow/validators/{test_state.go => validatorstest/state.go} (89%) rename vms/platformvm/warp/{test_signer.go => signertest/signertest.go} (71%) rename wallet/subnet/primary/common/{test_utxos.go => utxotest/utxotest.go} (83%) diff --git a/.golangci.yml b/.golangci.yml index b0b348a11e12..f7a313a1d596 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -120,9 +120,9 @@ linters-settings: - standard - default - blank - - dot - prefix(github.com/ava-labs/avalanchego) - alias + - dot skip-generated: true custom-order: true gosec: diff --git a/cache/test_cacher.go b/cache/cachetest/cacher.go similarity index 91% rename from cache/test_cacher.go rename to cache/cachetest/cacher.go index 35b1ad9c1711..92fd72635c02 100644 --- a/cache/test_cacher.go +++ b/cache/cachetest/cacher.go @@ -1,15 +1,14 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package cache +package cachetest import ( "testing" "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/avalanchego/ids" ) @@ -22,13 +21,13 @@ func TestIntSizeFunc(ids.ID, int64) int { // CacherTests is a list of all Cacher tests var CacherTests = []struct { Size int - Func func(t *testing.T, c Cacher[ids.ID, int64]) + Func func(t *testing.T, c cache.Cacher[ids.ID, int64]) }{ {Size: 1, Func: TestBasic}, {Size: 2, Func: TestEviction}, } -func TestBasic(t *testing.T, cache Cacher[ids.ID, int64]) { +func TestBasic(t *testing.T, cache cache.Cacher[ids.ID, int64]) { require := require.New(t) id1 := ids.ID{1} @@ -63,7 +62,7 @@ func TestBasic(t *testing.T, cache Cacher[ids.ID, int64]) { require.Equal(expectedValue2, value) } -func TestEviction(t *testing.T, cache Cacher[ids.ID, int64]) { +func TestEviction(t *testing.T, cache cache.Cacher[ids.ID, int64]) { require := require.New(t) id1 := ids.ID{1} diff --git a/cache/lru_cache_test.go b/cache/lru_cache_test.go index e8f0b2883c1c..0878b35ae8a3 100644 --- a/cache/lru_cache_test.go +++ b/cache/lru_cache_test.go @@ -1,26 +1,29 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package cache +package cache_test import ( "testing" "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/cache/cachetest" "github.com/ava-labs/avalanchego/ids" + + . "github.com/ava-labs/avalanchego/cache" ) func TestLRU(t *testing.T) { cache := &LRU[ids.ID, int64]{Size: 1} - TestBasic(t, cache) + cachetest.TestBasic(t, cache) } func TestLRUEviction(t *testing.T) { cache := &LRU[ids.ID, int64]{Size: 2} - TestEviction(t, cache) + cachetest.TestEviction(t, cache) } func TestLRUResize(t *testing.T) { diff --git a/cache/lru_sized_cache_test.go b/cache/lru_sized_cache_test.go index ad1c8b403362..8993408c1507 100644 --- a/cache/lru_sized_cache_test.go +++ b/cache/lru_sized_cache_test.go @@ -1,26 +1,29 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package cache +package cache_test import ( "testing" "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/cache/cachetest" "github.com/ava-labs/avalanchego/ids" + + . "github.com/ava-labs/avalanchego/cache" ) func TestSizedLRU(t *testing.T) { - cache := NewSizedLRU[ids.ID, int64](TestIntSize, TestIntSizeFunc) + cache := NewSizedLRU[ids.ID, int64](cachetest.TestIntSize, cachetest.TestIntSizeFunc) - TestBasic(t, cache) + cachetest.TestBasic(t, cache) } func TestSizedLRUEviction(t *testing.T) { - cache := NewSizedLRU[ids.ID, int64](2*TestIntSize, TestIntSizeFunc) + cache := NewSizedLRU[ids.ID, int64](2*cachetest.TestIntSize, cachetest.TestIntSizeFunc) - TestEviction(t, cache) + cachetest.TestEviction(t, cache) } func TestSizedLRUWrongKeyEvictionRegression(t *testing.T) { diff --git a/cache/metercacher/cache_test.go b/cache/metercacher/cache_test.go index 81f4eb722b06..609210c68a79 100644 --- a/cache/metercacher/cache_test.go +++ b/cache/metercacher/cache_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/cache" + "github.com/ava-labs/avalanchego/cache/cachetest" "github.com/ava-labs/avalanchego/ids" ) @@ -29,13 +30,13 @@ func TestInterface(t *testing.T) { { description: "sized cache LRU", setup: func(size int) cache.Cacher[ids.ID, int64] { - return cache.NewSizedLRU[ids.ID, int64](size*cache.TestIntSize, cache.TestIntSizeFunc) + return cache.NewSizedLRU[ids.ID, int64](size*cachetest.TestIntSize, cachetest.TestIntSizeFunc) }, }, } for _, scenario := range scenarios { - for _, test := range cache.CacherTests { + for _, test := range cachetest.CacherTests { baseCache := scenario.setup(test.Size) c, err := New("", prometheus.NewRegistry(), baseCache) require.NoError(t, err) diff --git a/chains/atomic/test_shared_memory.go b/chains/atomic/atomictest/shared_memory.go similarity index 76% rename from chains/atomic/test_shared_memory.go rename to chains/atomic/atomictest/shared_memory.go index f1c7b44ae30c..215fb8945e3e 100644 --- a/chains/atomic/test_shared_memory.go +++ b/chains/atomic/atomictest/shared_memory.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package atomic +package atomictest import ( "math/rand" @@ -11,13 +9,14 @@ import ( "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/units" ) // SharedMemoryTests is a list of all shared memory tests -var SharedMemoryTests = []func(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 SharedMemory, db database.Database){ +var SharedMemoryTests = []func(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 atomic.SharedMemory, db database.Database){ TestSharedMemoryPutAndGet, TestSharedMemoryLargePutGetAndRemove, TestSharedMemoryIndexed, @@ -30,10 +29,10 @@ var SharedMemoryTests = []func(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 TestPutAndRemoveBatch, } -func TestSharedMemoryPutAndGet(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 SharedMemory, _ database.Database) { +func TestSharedMemoryPutAndGet(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 atomic.SharedMemory, _ database.Database) { require := require.New(t) - require.NoError(sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{ + require.NoError(sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {PutRequests: []*atomic.Element{{ Key: []byte{0}, Value: []byte{1}, }}}})) @@ -45,7 +44,7 @@ func TestSharedMemoryPutAndGet(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 // TestSharedMemoryLargePutGetAndRemove tests to make sure that the interface // can support large values. -func TestSharedMemoryLargePutGetAndRemove(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 SharedMemory, _ database.Database) { +func TestSharedMemoryLargePutGetAndRemove(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 atomic.SharedMemory, _ database.Database) { require := require.New(t) rand.Seed(0) @@ -57,7 +56,7 @@ func TestSharedMemoryLargePutGetAndRemove(t *testing.T, chainID0, chainID1 ids.I _, err := rand.Read(b) // #nosec G404 require.NoError(err) - elems := []*Element{} + elems := []*atomic.Element{} keys := [][]byte{} for len(b) > pairSize { key := b[:elementSize] @@ -66,14 +65,14 @@ func TestSharedMemoryLargePutGetAndRemove(t *testing.T, chainID0, chainID1 ids.I value := b[:elementSize] b = b[elementSize:] - elems = append(elems, &Element{ + elems = append(elems, &atomic.Element{ Key: key, Value: value, }) keys = append(keys, key) } - require.NoError(sm0.Apply(map[ids.ID]*Requests{ + require.NoError(sm0.Apply(map[ids.ID]*atomic.Requests{ chainID1: { PutRequests: elems, }, @@ -88,17 +87,17 @@ func TestSharedMemoryLargePutGetAndRemove(t *testing.T, chainID0, chainID1 ids.I require.Equal(elems[i].Value, value) } - require.NoError(sm1.Apply(map[ids.ID]*Requests{ + require.NoError(sm1.Apply(map[ids.ID]*atomic.Requests{ chainID0: { RemoveRequests: keys, }, })) } -func TestSharedMemoryIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 SharedMemory, _ database.Database) { +func TestSharedMemoryIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 atomic.SharedMemory, _ database.Database) { require := require.New(t) - require.NoError(sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{ + require.NoError(sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {PutRequests: []*atomic.Element{{ Key: []byte{0}, Value: []byte{1}, Traits: [][]byte{ @@ -107,7 +106,7 @@ func TestSharedMemoryIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 S }, }}}})) - require.NoError(sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{ + require.NoError(sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {PutRequests: []*atomic.Element{{ Key: []byte{4}, Value: []byte{5}, Traits: [][]byte{ @@ -145,7 +144,7 @@ func TestSharedMemoryIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 S require.Equal([][]byte{{5}, {1}}, values, "wrong indexed values returned") } -func TestSharedMemoryLargeIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 SharedMemory, _ database.Database) { +func TestSharedMemoryLargeIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, sm1 atomic.SharedMemory, _ database.Database) { require := require.New(t) totalSize := 8 * units.MiB // 8 MiB @@ -156,7 +155,7 @@ func TestSharedMemoryLargeIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, _, err := rand.Read(b) // #nosec G404 require.NoError(err) - elems := []*Element{} + elems := []*atomic.Element{} allTraits := [][]byte{} for len(b) > pairSize { key := b[:elementSize] @@ -171,24 +170,24 @@ func TestSharedMemoryLargeIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0, allTraits = append(allTraits, traits...) b = b[elementSize:] - elems = append(elems, &Element{ + elems = append(elems, &atomic.Element{ Key: key, Value: value, Traits: traits, }) } - require.NoError(sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: elems}})) + require.NoError(sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {PutRequests: elems}})) values, _, _, err := sm1.Indexed(chainID0, allTraits, nil, nil, len(elems)+1) require.NoError(err) require.Len(values, len(elems), "wrong number of values returned") } -func TestSharedMemoryCantDuplicatePut(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, _ database.Database) { +func TestSharedMemoryCantDuplicatePut(t *testing.T, _, chainID1 ids.ID, sm0, _ atomic.SharedMemory, _ database.Database) { require := require.New(t) - err := sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{ + err := sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {PutRequests: []*atomic.Element{ { Key: []byte{0}, Value: []byte{1}, @@ -201,12 +200,12 @@ func TestSharedMemoryCantDuplicatePut(t *testing.T, _, chainID1 ids.ID, sm0, _ S // TODO: require error to be errDuplicatedOperation require.Error(err) //nolint:forbidigo // currently returns grpc errors too - require.NoError(sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{ + require.NoError(sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {PutRequests: []*atomic.Element{{ Key: []byte{0}, Value: []byte{1}, }}}})) - err = sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{ + err = sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {PutRequests: []*atomic.Element{{ Key: []byte{0}, Value: []byte{1}, }}}}) @@ -214,17 +213,17 @@ func TestSharedMemoryCantDuplicatePut(t *testing.T, _, chainID1 ids.ID, sm0, _ S require.Error(err) //nolint:forbidigo // currently returns grpc errors too } -func TestSharedMemoryCantDuplicateRemove(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, _ database.Database) { +func TestSharedMemoryCantDuplicateRemove(t *testing.T, _, chainID1 ids.ID, sm0, _ atomic.SharedMemory, _ database.Database) { require := require.New(t) - require.NoError(sm0.Apply(map[ids.ID]*Requests{chainID1: {RemoveRequests: [][]byte{{0}}}})) + require.NoError(sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {RemoveRequests: [][]byte{{0}}}})) - err := sm0.Apply(map[ids.ID]*Requests{chainID1: {RemoveRequests: [][]byte{{0}}}}) + err := sm0.Apply(map[ids.ID]*atomic.Requests{chainID1: {RemoveRequests: [][]byte{{0}}}}) // TODO: require error to be errDuplicatedOperation require.Error(err) //nolint:forbidigo // currently returns grpc errors too } -func TestSharedMemoryCommitOnPut(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, db database.Database) { +func TestSharedMemoryCommitOnPut(t *testing.T, _, chainID1 ids.ID, sm0, _ atomic.SharedMemory, db database.Database) { require := require.New(t) require.NoError(db.Put([]byte{1}, []byte{2})) @@ -236,7 +235,7 @@ func TestSharedMemoryCommitOnPut(t *testing.T, _, chainID1 ids.ID, sm0, _ Shared require.NoError(batch.Delete([]byte{1})) require.NoError(sm0.Apply( - map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{ + map[ids.ID]*atomic.Requests{chainID1: {PutRequests: []*atomic.Element{{ Key: []byte{0}, Value: []byte{1}, }}}}, @@ -252,7 +251,7 @@ func TestSharedMemoryCommitOnPut(t *testing.T, _, chainID1 ids.ID, sm0, _ Shared require.False(has) } -func TestSharedMemoryCommitOnRemove(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, db database.Database) { +func TestSharedMemoryCommitOnRemove(t *testing.T, _, chainID1 ids.ID, sm0, _ atomic.SharedMemory, db database.Database) { require := require.New(t) require.NoError(db.Put([]byte{1}, []byte{2})) @@ -264,7 +263,7 @@ func TestSharedMemoryCommitOnRemove(t *testing.T, _, chainID1 ids.ID, sm0, _ Sha require.NoError(batch.Delete([]byte{1})) require.NoError(sm0.Apply( - map[ids.ID]*Requests{chainID1: {RemoveRequests: [][]byte{{0}}}}, + map[ids.ID]*atomic.Requests{chainID1: {RemoveRequests: [][]byte{{0}}}}, batch, )) @@ -278,19 +277,19 @@ func TestSharedMemoryCommitOnRemove(t *testing.T, _, chainID1 ids.ID, sm0, _ Sha } // TestPutAndRemoveBatch tests to make sure multiple put and remove requests work properly -func TestPutAndRemoveBatch(t *testing.T, chainID0, _ ids.ID, _, sm1 SharedMemory, db database.Database) { +func TestPutAndRemoveBatch(t *testing.T, chainID0, _ ids.ID, _, sm1 atomic.SharedMemory, db database.Database) { require := require.New(t) batch := db.NewBatch() require.NoError(batch.Put([]byte{0}, []byte{1})) - batchChainsAndInputs := make(map[ids.ID]*Requests) + batchChainsAndInputs := make(map[ids.ID]*atomic.Requests) byteArr := [][]byte{{0}, {1}, {5}} - batchChainsAndInputs[chainID0] = &Requests{ - PutRequests: []*Element{{ + batchChainsAndInputs[chainID0] = &atomic.Requests{ + PutRequests: []*atomic.Element{{ Key: []byte{2}, Value: []byte{9}, }}, @@ -306,7 +305,7 @@ func TestPutAndRemoveBatch(t *testing.T, chainID0, _ ids.ID, _, sm1 SharedMemory // TestSharedMemoryLargeBatchSize tests to make sure that the interface can // support large batches. -func TestSharedMemoryLargeBatchSize(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, db database.Database) { +func TestSharedMemoryLargeBatchSize(t *testing.T, _, chainID1 ids.ID, sm0, _ atomic.SharedMemory, db database.Database) { require := require.New(t) rand.Seed(0) @@ -339,7 +338,7 @@ func TestSharedMemoryLargeBatchSize(t *testing.T, _, chainID1 ids.ID, sm0, _ Sha require.NoError(batch.Delete([]byte{1})) require.NoError(sm0.Apply( - map[ids.ID]*Requests{chainID1: {RemoveRequests: [][]byte{{0}}}}, + map[ids.ID]*atomic.Requests{chainID1: {RemoveRequests: [][]byte{{0}}}}, batch, )) @@ -362,7 +361,7 @@ func TestSharedMemoryLargeBatchSize(t *testing.T, _, chainID1 ids.ID, sm0, _ Sha } require.NoError(sm0.Apply( - map[ids.ID]*Requests{chainID1: {RemoveRequests: [][]byte{{1}}}}, + map[ids.ID]*atomic.Requests{chainID1: {RemoveRequests: [][]byte{{1}}}}, batch, )) @@ -376,12 +375,12 @@ func TestSharedMemoryLargeBatchSize(t *testing.T, _, chainID1 ids.ID, sm0, _ Sha require.NoError(batch.Delete(key)) } - batchChainsAndInputs := make(map[ids.ID]*Requests) + batchChainsAndInputs := make(map[ids.ID]*atomic.Requests) byteArr := [][]byte{{30}, {40}, {50}} - batchChainsAndInputs[chainID1] = &Requests{ - PutRequests: []*Element{{ + batchChainsAndInputs[chainID1] = &atomic.Requests{ + PutRequests: []*atomic.Element{{ Key: []byte{2}, Value: []byte{9}, }}, diff --git a/chains/atomic/gsharedmemory/shared_memory_test.go b/chains/atomic/gsharedmemory/shared_memory_test.go index 02dfb7324a78..ffd325054f2e 100644 --- a/chains/atomic/gsharedmemory/shared_memory_test.go +++ b/chains/atomic/gsharedmemory/shared_memory_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/chains/atomic" + "github.com/ava-labs/avalanchego/chains/atomic/atomictest" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/prefixdb" @@ -25,7 +26,7 @@ func TestInterface(t *testing.T) { chainID0 := ids.GenerateTestID() chainID1 := ids.GenerateTestID() - for _, test := range atomic.SharedMemoryTests { + for _, test := range atomictest.SharedMemoryTests { baseDB := memdb.New() memoryDB := prefixdb.New([]byte{0}, baseDB) testDB := prefixdb.New([]byte{1}, baseDB) diff --git a/chains/atomic/shared_memory_test.go b/chains/atomic/shared_memory_test.go index 1597d662131a..24aae9f8b928 100644 --- a/chains/atomic/shared_memory_test.go +++ b/chains/atomic/shared_memory_test.go @@ -1,21 +1,24 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package atomic +package atomic_test import ( "testing" + "github.com/ava-labs/avalanchego/chains/atomic/atomictest" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" + + . "github.com/ava-labs/avalanchego/chains/atomic" ) func TestSharedMemory(t *testing.T) { chainID0 := ids.GenerateTestID() chainID1 := ids.GenerateTestID() - for _, test := range SharedMemoryTests { + for _, test := range atomictest.SharedMemoryTests { baseDB := memdb.New() memoryDB := prefixdb.New([]byte{0}, baseDB) diff --git a/codec/test_codec.go b/codec/codectest/codectest.go similarity index 84% rename from codec/test_codec.go rename to codec/codectest/codectest.go index 974168dd4829..172d61f4e453 100644 --- a/codec/test_codec.go +++ b/codec/codectest/codectest.go @@ -1,19 +1,19 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package codec +package codectest import ( "math" "testing" "github.com/stretchr/testify/require" + + codecpkg "github.com/ava-labs/avalanchego/codec" ) var ( - Tests = []func(c GeneralCodec, t testing.TB){ + Tests = []func(c codecpkg.GeneralCodec, t testing.TB){ TestStruct, TestRegisterStructTwice, TestUInt32, @@ -49,7 +49,7 @@ var ( TestCanMarshalLargeSlices, } - MultipleTagsTests = []func(c GeneralCodec, t testing.TB){ + MultipleTagsTests = []func(c codecpkg.GeneralCodec, t testing.TB){ TestMultipleTags, } ) @@ -127,7 +127,7 @@ type myStruct struct { } // Test marshaling/unmarshaling a complicated struct -func TestStruct(codec GeneralCodec, t testing.TB) { +func TestStruct(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) temp := Foo(&MyInnerStruct{}) @@ -215,7 +215,7 @@ func TestStruct(codec GeneralCodec, t testing.TB) { MyMap7: myMap7, } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() // Register the types that may be unmarshaled into interfaces require.NoError(codec.RegisterType(&MyInnerStruct{})) require.NoError(codec.RegisterType(&MyInnerStruct2{})) @@ -243,20 +243,20 @@ func TestStruct(codec GeneralCodec, t testing.TB) { require.Equal(myStructInstance, *myStructUnmarshaled) } -func TestRegisterStructTwice(codec GeneralCodec, t testing.TB) { +func TestRegisterStructTwice(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) require.NoError(codec.RegisterType(&MyInnerStruct{})) err := codec.RegisterType(&MyInnerStruct{}) - require.ErrorIs(err, ErrDuplicateType) + require.ErrorIs(err, codecpkg.ErrDuplicateType) } -func TestUInt32(codec GeneralCodec, t testing.TB) { +func TestUInt32(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) number := uint32(500) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, number) @@ -273,23 +273,23 @@ func TestUInt32(codec GeneralCodec, t testing.TB) { require.Equal(number, numberUnmarshaled) } -func TestUIntPtr(codec GeneralCodec, t testing.TB) { +func TestUIntPtr(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) number := uintptr(500) _, err := manager.Marshal(0, number) - require.ErrorIs(err, ErrUnsupportedType) + require.ErrorIs(err, codecpkg.ErrUnsupportedType) } -func TestSlice(codec GeneralCodec, t testing.TB) { +func TestSlice(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) mySlice := []bool{true, false, true, true} - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, mySlice) @@ -307,13 +307,13 @@ func TestSlice(codec GeneralCodec, t testing.TB) { } // Test marshalling/unmarshalling largest possible slice -func TestMaxSizeSlice(codec GeneralCodec, t testing.TB) { +func TestMaxSizeSlice(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) mySlice := make([]string, math.MaxUint16) mySlice[0] = "first!" mySlice[math.MaxUint16-1] = "last!" - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, mySlice) @@ -331,11 +331,11 @@ func TestMaxSizeSlice(codec GeneralCodec, t testing.TB) { } // Test marshalling a bool -func TestBool(codec GeneralCodec, t testing.TB) { +func TestBool(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) myBool := true - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, myBool) @@ -353,11 +353,11 @@ func TestBool(codec GeneralCodec, t testing.TB) { } // Test marshalling an array -func TestArray(codec GeneralCodec, t testing.TB) { +func TestArray(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) myArr := [5]uint64{5, 6, 7, 8, 9} - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, myArr) @@ -375,11 +375,11 @@ func TestArray(codec GeneralCodec, t testing.TB) { } // Test marshalling a really big array -func TestBigArray(codec GeneralCodec, t testing.TB) { +func TestBigArray(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) myArr := [30000]uint64{5, 6, 7, 8, 9} - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, myArr) @@ -397,11 +397,11 @@ func TestBigArray(codec GeneralCodec, t testing.TB) { } // Test marshalling a pointer to a struct -func TestPointerToStruct(codec GeneralCodec, t testing.TB) { +func TestPointerToStruct(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) myPtr := &MyInnerStruct{Str: "Hello!"} - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, myPtr) @@ -419,7 +419,7 @@ func TestPointerToStruct(codec GeneralCodec, t testing.TB) { } // Test marshalling a slice of structs -func TestSliceOfStruct(codec GeneralCodec, t testing.TB) { +func TestSliceOfStruct(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) mySlice := []MyInnerStruct3{ { @@ -435,7 +435,7 @@ func TestSliceOfStruct(codec GeneralCodec, t testing.TB) { } require.NoError(codec.RegisterType(&MyInnerStruct{})) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, mySlice) @@ -453,12 +453,12 @@ func TestSliceOfStruct(codec GeneralCodec, t testing.TB) { } // Test marshalling an interface -func TestInterface(codec GeneralCodec, t testing.TB) { +func TestInterface(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) require.NoError(codec.RegisterType(&MyInnerStruct2{})) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) var f Foo = &MyInnerStruct2{true} @@ -477,7 +477,7 @@ func TestInterface(codec GeneralCodec, t testing.TB) { } // Test marshalling a slice of interfaces -func TestSliceOfInterface(codec GeneralCodec, t testing.TB) { +func TestSliceOfInterface(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) mySlice := []Foo{ @@ -490,7 +490,7 @@ func TestSliceOfInterface(codec GeneralCodec, t testing.TB) { } require.NoError(codec.RegisterType(&MyInnerStruct{})) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, mySlice) @@ -508,7 +508,7 @@ func TestSliceOfInterface(codec GeneralCodec, t testing.TB) { } // Test marshalling an array of interfaces -func TestArrayOfInterface(codec GeneralCodec, t testing.TB) { +func TestArrayOfInterface(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) myArray := [2]Foo{ @@ -521,7 +521,7 @@ func TestArrayOfInterface(codec GeneralCodec, t testing.TB) { } require.NoError(codec.RegisterType(&MyInnerStruct{})) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, myArray) @@ -539,7 +539,7 @@ func TestArrayOfInterface(codec GeneralCodec, t testing.TB) { } // Test marshalling a pointer to an interface -func TestPointerToInterface(codec GeneralCodec, t testing.TB) { +func TestPointerToInterface(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) var myinnerStruct Foo = &MyInnerStruct{Str: "Hello!"} @@ -547,7 +547,7 @@ func TestPointerToInterface(codec GeneralCodec, t testing.TB) { require.NoError(codec.RegisterType(&MyInnerStruct{})) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, &myPtr) @@ -565,11 +565,11 @@ func TestPointerToInterface(codec GeneralCodec, t testing.TB) { } // Test marshalling a string -func TestString(codec GeneralCodec, t testing.TB) { +func TestString(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) myString := "Ayy" - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, myString) @@ -587,7 +587,7 @@ func TestString(codec GeneralCodec, t testing.TB) { } // Ensure a nil slice is unmarshaled to slice with length 0 -func TestNilSlice(codec GeneralCodec, t testing.TB) { +func TestNilSlice(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type structWithSlice struct { @@ -595,7 +595,7 @@ func TestNilSlice(codec GeneralCodec, t testing.TB) { } myStruct := structWithSlice{Slice: nil} - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, myStruct) @@ -614,7 +614,7 @@ func TestNilSlice(codec GeneralCodec, t testing.TB) { // Ensure that trying to serialize a struct with an unexported member // that has `serialize:"true"` returns error -func TestSerializeUnexportedField(codec GeneralCodec, t testing.TB) { +func TestSerializeUnexportedField(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type s struct { @@ -627,17 +627,17 @@ func TestSerializeUnexportedField(codec GeneralCodec, t testing.TB) { unexportedField: "world!", } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) _, err := manager.Marshal(0, myS) - require.ErrorIs(err, ErrUnexportedField) + require.ErrorIs(err, codecpkg.ErrUnexportedField) _, err = manager.Size(0, myS) - require.ErrorIs(err, ErrUnexportedField) + require.ErrorIs(err, codecpkg.ErrUnexportedField) } -func TestSerializeOfNoSerializeField(codec GeneralCodec, t testing.TB) { +func TestSerializeOfNoSerializeField(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type s struct { @@ -650,7 +650,7 @@ func TestSerializeOfNoSerializeField(codec GeneralCodec, t testing.TB) { UnserializedField: "Do not serialize me", UnmarkedField: "No declared serialize", } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) marshalled, err := manager.Marshal(0, myS) @@ -670,14 +670,14 @@ func TestSerializeOfNoSerializeField(codec GeneralCodec, t testing.TB) { } // Test marshalling of nil slice -func TestNilSliceSerialization(codec GeneralCodec, t testing.TB) { +func TestNilSliceSerialization(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type simpleSliceStruct struct { Arr []uint32 `serialize:"true"` } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) val := &simpleSliceStruct{} @@ -698,14 +698,14 @@ func TestNilSliceSerialization(codec GeneralCodec, t testing.TB) { } // Test marshaling a slice that has 0 elements (but isn't nil) -func TestEmptySliceSerialization(codec GeneralCodec, t testing.TB) { +func TestEmptySliceSerialization(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type simpleSliceStruct struct { Arr []uint32 `serialize:"true"` } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) val := &simpleSliceStruct{Arr: make([]uint32, 0, 1)} @@ -726,7 +726,7 @@ func TestEmptySliceSerialization(codec GeneralCodec, t testing.TB) { } // Test marshaling empty slice of zero length structs -func TestSliceWithEmptySerialization(codec GeneralCodec, t testing.TB) { +func TestSliceWithEmptySerialization(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type emptyStruct struct{} @@ -735,7 +735,7 @@ func TestSliceWithEmptySerialization(codec GeneralCodec, t testing.TB) { Arr []emptyStruct `serialize:"true"` } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) val := &nestedSliceStruct{ @@ -757,7 +757,7 @@ func TestSliceWithEmptySerialization(codec GeneralCodec, t testing.TB) { require.Empty(unmarshaled.Arr) } -func TestSliceWithEmptySerializationError(codec GeneralCodec, t testing.TB) { +func TestSliceWithEmptySerializationError(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type emptyStruct struct{} @@ -766,32 +766,32 @@ func TestSliceWithEmptySerializationError(codec GeneralCodec, t testing.TB) { Arr []emptyStruct `serialize:"true"` } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) val := &nestedSliceStruct{ Arr: make([]emptyStruct, 1), } _, err := manager.Marshal(0, val) - require.ErrorIs(err, ErrMarshalZeroLength) + require.ErrorIs(err, codecpkg.ErrMarshalZeroLength) _, err = manager.Size(0, val) - require.ErrorIs(err, ErrMarshalZeroLength) + require.ErrorIs(err, codecpkg.ErrMarshalZeroLength) b := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x01} // codec version (0x00, 0x00) then (0x00, 0x00, 0x00, 0x01) for numElts unmarshaled := nestedSliceStruct{} _, err = manager.Unmarshal(b, &unmarshaled) - require.ErrorIs(err, ErrUnmarshalZeroLength) + require.ErrorIs(err, codecpkg.ErrUnmarshalZeroLength) } // Test marshaling empty map of zero length structs -func TestMapWithEmptySerialization(codec GeneralCodec, t testing.TB) { +func TestMapWithEmptySerialization(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type emptyStruct struct{} - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) val := make(map[emptyStruct]emptyStruct) @@ -811,44 +811,44 @@ func TestMapWithEmptySerialization(codec GeneralCodec, t testing.TB) { require.Empty(unmarshaled) } -func TestMapWithEmptySerializationError(codec GeneralCodec, t testing.TB) { +func TestMapWithEmptySerializationError(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type emptyStruct struct{} - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) val := map[emptyStruct]emptyStruct{ {}: {}, } _, err := manager.Marshal(0, val) - require.ErrorIs(err, ErrMarshalZeroLength) + require.ErrorIs(err, codecpkg.ErrMarshalZeroLength) _, err = manager.Size(0, val) - require.ErrorIs(err, ErrMarshalZeroLength) + require.ErrorIs(err, codecpkg.ErrMarshalZeroLength) b := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x01} // codec version (0x00, 0x00) then (0x00, 0x00, 0x00, 0x01) for numElts var unmarshaled map[emptyStruct]emptyStruct _, err = manager.Unmarshal(b, &unmarshaled) - require.ErrorIs(err, ErrUnmarshalZeroLength) + require.ErrorIs(err, codecpkg.ErrUnmarshalZeroLength) } -func TestSliceTooLarge(codec GeneralCodec, t testing.TB) { +func TestSliceTooLarge(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) val := []struct{}{} b := []byte{0x00, 0x00, 0xff, 0xff, 0xff, 0xff} _, err := manager.Unmarshal(b, &val) - require.ErrorIs(err, ErrMaxSliceLenExceeded) + require.ErrorIs(err, codecpkg.ErrMaxSliceLenExceeded) } // Ensure serializing structs with negative number members works -func TestNegativeNumbers(codec GeneralCodec, t testing.TB) { +func TestNegativeNumbers(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type s struct { @@ -858,7 +858,7 @@ func TestNegativeNumbers(codec GeneralCodec, t testing.TB) { MyInt64 int64 `serialize:"true"` } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) myS := s{-1, -2, -3, -4} @@ -877,7 +877,7 @@ func TestNegativeNumbers(codec GeneralCodec, t testing.TB) { } // Ensure deserializing structs with too many bytes errors correctly -func TestTooLargeUnmarshal(codec GeneralCodec, t testing.TB) { +func TestTooLargeUnmarshal(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type inner struct { @@ -885,12 +885,12 @@ func TestTooLargeUnmarshal(codec GeneralCodec, t testing.TB) { } bytes := []byte{0, 0, 0, 0} - manager := NewManager(3) + manager := codecpkg.NewManager(3) require.NoError(manager.RegisterCodec(0, codec)) s := inner{} _, err := manager.Unmarshal(bytes, &s) - require.ErrorIs(err, ErrUnmarshalTooBig) + require.ErrorIs(err, codecpkg.ErrUnmarshalTooBig) } type outerInterface interface { @@ -910,10 +910,10 @@ func (*innerInterface) ToInt() int { type innerNoInterface struct{} // Ensure deserializing structs into the wrong interface errors gracefully -func TestUnmarshalInvalidInterface(codec GeneralCodec, t testing.TB) { +func TestUnmarshalInvalidInterface(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(codec.RegisterType(&innerInterface{})) require.NoError(codec.RegisterType(&innerNoInterface{})) require.NoError(manager.RegisterCodec(0, codec)) @@ -929,26 +929,26 @@ func TestUnmarshalInvalidInterface(codec GeneralCodec, t testing.TB) { bytes := []byte{0, 0, 0, 0, 0, 1} s := outer{} _, err := manager.Unmarshal(bytes, &s) - require.ErrorIs(err, ErrDoesNotImplementInterface) + require.ErrorIs(err, codecpkg.ErrDoesNotImplementInterface) } } // Test unmarshaling something with extra data -func TestExtraSpace(codec GeneralCodec, t testing.TB) { +func TestExtraSpace(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) // codec version 0x0000 then 0x01 for b then 0x02 as extra data. byteSlice := []byte{0x00, 0x00, 0x01, 0x02} var b byte _, err := manager.Unmarshal(byteSlice, &b) - require.ErrorIs(err, ErrExtraSpace) + require.ErrorIs(err, codecpkg.ErrExtraSpace) } // Ensure deserializing slices whose lengths exceed MaxInt32 error correctly -func TestSliceLengthOverflow(codec GeneralCodec, t testing.TB) { +func TestSliceLengthOverflow(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) type inner struct { @@ -961,12 +961,12 @@ func TestSliceLengthOverflow(codec GeneralCodec, t testing.TB) { 0xff, 0xff, 0xff, 0xff, } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) s := inner{} _, err := manager.Unmarshal(bytes, &s) - require.ErrorIs(err, ErrMaxSliceLenExceeded) + require.ErrorIs(err, codecpkg.ErrMaxSliceLenExceeded) } type MultipleVersionsStruct struct { @@ -978,7 +978,7 @@ type MultipleVersionsStruct struct { NoTags string `tag1:"false" tag2:"false"` } -func TestMultipleTags(codec GeneralCodec, t testing.TB) { +func TestMultipleTags(codec codecpkg.GeneralCodec, t testing.TB) { // received codec is expected to have both v1 and v2 registered as tags inputs := MultipleVersionsStruct{ BothTags: "both Tags", @@ -989,7 +989,7 @@ func TestMultipleTags(codec GeneralCodec, t testing.TB) { NoTags: "Neither Tag", } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() for _, codecVersion := range []uint16{0, 1, 2022} { require := require.New(t) @@ -1011,7 +1011,7 @@ func TestMultipleTags(codec GeneralCodec, t testing.TB) { } } -func TestMap(codec GeneralCodec, t testing.TB) { +func TestMap(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) data1 := map[string]MyInnerStruct2{ @@ -1038,7 +1038,7 @@ func TestMap(codec GeneralCodec, t testing.TB) { data3, } - manager := NewDefaultManager() + manager := codecpkg.NewDefaultManager() require.NoError(manager.RegisterCodec(0, codec)) data1Bytes, err := manager.Marshal(0, data1) @@ -1080,12 +1080,12 @@ func TestMap(codec GeneralCodec, t testing.TB) { require.Len(outerArrayBytes, outerArraySize) } -func TestCanMarshalLargeSlices(codec GeneralCodec, t testing.TB) { +func TestCanMarshalLargeSlices(codec codecpkg.GeneralCodec, t testing.TB) { require := require.New(t) data := make([]uint16, 1_000_000) - manager := NewManager(math.MaxInt) + manager := codecpkg.NewManager(math.MaxInt) require.NoError(manager.RegisterCodec(0, codec)) bytes, err := manager.Marshal(0, data) @@ -1097,8 +1097,8 @@ func TestCanMarshalLargeSlices(codec GeneralCodec, t testing.TB) { require.Equal(data, unmarshalledData) } -func FuzzStructUnmarshal(codec GeneralCodec, f *testing.F) { - manager := NewDefaultManager() +func FuzzStructUnmarshal(codec codecpkg.GeneralCodec, f *testing.F) { + manager := codecpkg.NewDefaultManager() // Register the types that may be unmarshaled into interfaces require.NoError(f, codec.RegisterType(&MyInnerStruct{})) require.NoError(f, codec.RegisterType(&MyInnerStruct2{})) diff --git a/codec/hierarchycodec/codec_test.go b/codec/hierarchycodec/codec_test.go index a5dd8b5fd546..fc7c9e4d7696 100644 --- a/codec/hierarchycodec/codec_test.go +++ b/codec/hierarchycodec/codec_test.go @@ -6,18 +6,18 @@ package hierarchycodec import ( "testing" - "github.com/ava-labs/avalanchego/codec" + "github.com/ava-labs/avalanchego/codec/codectest" ) func TestVectors(t *testing.T) { - for _, test := range codec.Tests { + for _, test := range codectest.Tests { c := NewDefault() test(c, t) } } func TestMultipleTags(t *testing.T) { - for _, test := range codec.MultipleTagsTests { + for _, test := range codectest.MultipleTagsTests { c := New([]string{"tag1", "tag2"}) test(c, t) } @@ -25,5 +25,5 @@ func TestMultipleTags(t *testing.T) { func FuzzStructUnmarshalHierarchyCodec(f *testing.F) { c := NewDefault() - codec.FuzzStructUnmarshal(c, f) + codectest.FuzzStructUnmarshal(c, f) } diff --git a/codec/linearcodec/codec_test.go b/codec/linearcodec/codec_test.go index 20b886f9cb62..bc9d5fb42dd5 100644 --- a/codec/linearcodec/codec_test.go +++ b/codec/linearcodec/codec_test.go @@ -6,18 +6,18 @@ package linearcodec import ( "testing" - "github.com/ava-labs/avalanchego/codec" + "github.com/ava-labs/avalanchego/codec/codectest" ) func TestVectors(t *testing.T) { - for _, test := range codec.Tests { + for _, test := range codectest.Tests { c := NewDefault() test(c, t) } } func TestMultipleTags(t *testing.T) { - for _, test := range codec.MultipleTagsTests { + for _, test := range codectest.MultipleTagsTests { c := New([]string{"tag1", "tag2"}) test(c, t) } @@ -25,5 +25,5 @@ func TestMultipleTags(t *testing.T) { func FuzzStructUnmarshalLinearCodec(f *testing.F) { c := NewDefault() - codec.FuzzStructUnmarshal(c, f) + codectest.FuzzStructUnmarshal(c, f) } diff --git a/database/corruptabledb/db_test.go b/database/corruptabledb/db_test.go index 2de4d67a64c5..4a9c74d171c0 100644 --- a/database/corruptabledb/db_test.go +++ b/database/corruptabledb/db_test.go @@ -12,6 +12,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" ) @@ -23,7 +24,7 @@ func newDB() *Database { } func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { test(t, newDB()) }) @@ -31,15 +32,15 @@ func TestInterface(t *testing.T) { } func FuzzKeyValue(f *testing.F) { - database.FuzzKeyValue(f, newDB()) + dbtest.FuzzKeyValue(f, newDB()) } func FuzzNewIteratorWithPrefix(f *testing.F) { - database.FuzzNewIteratorWithPrefix(f, newDB()) + dbtest.FuzzNewIteratorWithPrefix(f, newDB()) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { - database.FuzzNewIteratorWithStartAndPrefix(f, newDB()) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, newDB()) } // TestCorruption tests to make sure corruptabledb wrapper works as expected. diff --git a/database/benchmark_database.go b/database/dbtest/benchmark.go similarity index 82% rename from database/benchmark_database.go rename to database/dbtest/benchmark.go index 479035c126cb..94b763c29239 100644 --- a/database/benchmark_database.go +++ b/database/dbtest/benchmark.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package database +package dbtest import ( "math/rand" @@ -11,12 +9,13 @@ import ( "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils/units" ) var ( // Benchmarks is a list of all database benchmarks - Benchmarks = map[string]func(b *testing.B, db Database, keys, values [][]byte){ + Benchmarks = map[string]func(b *testing.B, db database.Database, keys, values [][]byte){ "Get": BenchmarkGet, "Put": BenchmarkPut, "Delete": BenchmarkDelete, @@ -57,7 +56,7 @@ func SetupBenchmark(b *testing.B, count int, keySize, valueSize int) ([][]byte, } // BenchmarkGet measures the time it takes to get an operation from a database. -func BenchmarkGet(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkGet(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) count := len(keys) @@ -78,7 +77,7 @@ func BenchmarkGet(b *testing.B, db Database, keys, values [][]byte) { } // BenchmarkPut measures the time it takes to write an operation to a database. -func BenchmarkPut(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkPut(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) count := len(keys) @@ -89,7 +88,7 @@ func BenchmarkPut(b *testing.B, db Database, keys, values [][]byte) { } // BenchmarkDelete measures the time it takes to delete a (k, v) from a database. -func BenchmarkDelete(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkDelete(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) count := len(keys) @@ -110,7 +109,7 @@ func BenchmarkDelete(b *testing.B, db Database, keys, values [][]byte) { } // BenchmarkBatchPut measures the time it takes to batch put. -func BenchmarkBatchPut(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkBatchPut(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) count := len(keys) @@ -121,7 +120,7 @@ func BenchmarkBatchPut(b *testing.B, db Database, keys, values [][]byte) { } // BenchmarkBatchDelete measures the time it takes to batch delete. -func BenchmarkBatchDelete(b *testing.B, db Database, keys, _ [][]byte) { +func BenchmarkBatchDelete(b *testing.B, db database.Database, keys, _ [][]byte) { require.NotEmpty(b, keys) count := len(keys) @@ -132,7 +131,7 @@ func BenchmarkBatchDelete(b *testing.B, db Database, keys, _ [][]byte) { } // BenchmarkBatchWrite measures the time it takes to batch write. -func BenchmarkBatchWrite(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkBatchWrite(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) require := require.New(b) @@ -151,7 +150,7 @@ func BenchmarkBatchWrite(b *testing.B, db Database, keys, values [][]byte) { } // BenchmarkParallelGet measures the time it takes to read in parallel. -func BenchmarkParallelGet(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkParallelGet(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) count := len(keys) @@ -173,7 +172,7 @@ func BenchmarkParallelGet(b *testing.B, db Database, keys, values [][]byte) { } // BenchmarkParallelPut measures the time it takes to write to the db in parallel. -func BenchmarkParallelPut(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkParallelPut(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) count := len(keys) @@ -186,7 +185,7 @@ func BenchmarkParallelPut(b *testing.B, db Database, keys, values [][]byte) { } // BenchmarkParallelDelete measures the time it takes to delete a (k, v) from the db. -func BenchmarkParallelDelete(b *testing.B, db Database, keys, values [][]byte) { +func BenchmarkParallelDelete(b *testing.B, db database.Database, keys, values [][]byte) { require.NotEmpty(b, keys) count := len(keys) diff --git a/database/test_database.go b/database/dbtest/dbtest.go similarity index 85% rename from database/test_database.go rename to database/dbtest/dbtest.go index 4e5bc174ae85..b12e921634fe 100644 --- a/database/test_database.go +++ b/database/dbtest/dbtest.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package database +package dbtest import ( "bytes" @@ -18,12 +16,13 @@ import ( "golang.org/x/exp/maps" "golang.org/x/sync/errgroup" + "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/units" ) // Tests is a list of all database tests -var Tests = map[string]func(t *testing.T, db Database){ +var Tests = map[string]func(t *testing.T, db database.Database){ "SimpleKeyValue": TestSimpleKeyValue, "OverwriteKeyValue": TestOverwriteKeyValue, "EmptyKey": TestEmptyKey, @@ -65,7 +64,7 @@ var Tests = map[string]func(t *testing.T, db Database){ // TestSimpleKeyValue tests to make sure that simple Put + Get + Delete + Has // calls return the expected values. -func TestSimpleKeyValue(t *testing.T, db Database) { +func TestSimpleKeyValue(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -76,7 +75,7 @@ func TestSimpleKeyValue(t *testing.T, db Database) { require.False(has) _, err = db.Get(key) - require.Equal(ErrNotFound, err) + require.Equal(database.ErrNotFound, err) require.NoError(db.Delete(key)) require.NoError(db.Put(key, value)) @@ -96,12 +95,12 @@ func TestSimpleKeyValue(t *testing.T, db Database) { require.False(has) _, err = db.Get(key) - require.Equal(ErrNotFound, err) + require.Equal(database.ErrNotFound, err) require.NoError(db.Delete(key)) } -func TestOverwriteKeyValue(t *testing.T, db Database) { +func TestOverwriteKeyValue(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -117,14 +116,14 @@ func TestOverwriteKeyValue(t *testing.T, db Database) { require.Equal(value2, gotValue) } -func TestKeyEmptyValue(t *testing.T, db Database) { +func TestKeyEmptyValue(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") val := []byte(nil) _, err := db.Get(key) - require.Equal(ErrNotFound, err) + require.Equal(database.ErrNotFound, err) require.NoError(db.Put(key, val)) @@ -133,7 +132,7 @@ func TestKeyEmptyValue(t *testing.T, db Database) { require.Empty(value) } -func TestEmptyKey(t *testing.T, db Database) { +func TestEmptyKey(t *testing.T, db database.Database) { require := require.New(t) var ( @@ -145,7 +144,7 @@ func TestEmptyKey(t *testing.T, db Database) { // Test that nil key can be retrieved by empty key _, err := db.Get(nilKey) - require.Equal(ErrNotFound, err) + require.Equal(database.ErrNotFound, err) require.NoError(db.Put(nilKey, val1)) @@ -163,7 +162,7 @@ func TestEmptyKey(t *testing.T, db Database) { // TestSimpleKeyValueClosed tests to make sure that Put + Get + Delete + Has // calls return the correct error when the database has been closed. -func TestSimpleKeyValueClosed(t *testing.T, db Database) { +func TestSimpleKeyValueClosed(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -174,7 +173,7 @@ func TestSimpleKeyValueClosed(t *testing.T, db Database) { require.False(has) _, err = db.Get(key) - require.Equal(ErrNotFound, err) + require.Equal(database.ErrNotFound, err) require.NoError(db.Delete(key)) require.NoError(db.Put(key, value)) @@ -190,19 +189,19 @@ func TestSimpleKeyValueClosed(t *testing.T, db Database) { require.NoError(db.Close()) _, err = db.Has(key) - require.Equal(ErrClosed, err) + require.Equal(database.ErrClosed, err) _, err = db.Get(key) - require.Equal(ErrClosed, err) + require.Equal(database.ErrClosed, err) - require.Equal(ErrClosed, db.Put(key, value)) - require.Equal(ErrClosed, db.Delete(key)) - require.Equal(ErrClosed, db.Close()) + require.Equal(database.ErrClosed, db.Put(key, value)) + require.Equal(database.ErrClosed, db.Delete(key)) + require.Equal(database.ErrClosed, db.Close()) } // TestMemorySafetyDatabase ensures it is safe to modify a key after passing it // to Database.Put and Database.Get. -func TestMemorySafetyDatabase(t *testing.T, db Database) { +func TestMemorySafetyDatabase(t *testing.T, db database.Database) { require := require.New(t) key := []byte("1key") @@ -236,7 +235,7 @@ func TestMemorySafetyDatabase(t *testing.T, db Database) { // TestNewBatchClosed tests to make sure that calling NewBatch on a closed // database returns a batch that errors correctly. -func TestNewBatchClosed(t *testing.T, db Database) { +func TestNewBatchClosed(t *testing.T, db database.Database) { require := require.New(t) require.NoError(db.Close()) @@ -249,11 +248,11 @@ func TestNewBatchClosed(t *testing.T, db Database) { require.NoError(batch.Put(key, value)) require.Positive(batch.Size()) - require.Equal(ErrClosed, batch.Write()) + require.Equal(database.ErrClosed, batch.Write()) } // TestBatchPut tests to make sure that batched writes work as expected. -func TestBatchPut(t *testing.T, db Database) { +func TestBatchPut(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -281,11 +280,11 @@ func TestBatchPut(t *testing.T, db Database) { require.NoError(batch.Put(key, value)) require.NoError(db.Close()) - require.Equal(ErrClosed, batch.Write()) + require.Equal(database.ErrClosed, batch.Write()) } // TestBatchDelete tests to make sure that batched deletes work as expected. -func TestBatchDelete(t *testing.T, db Database) { +func TestBatchDelete(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -304,14 +303,14 @@ func TestBatchDelete(t *testing.T, db Database) { require.False(has) _, err = db.Get(key) - require.Equal(ErrNotFound, err) + require.Equal(database.ErrNotFound, err) require.NoError(db.Delete(key)) } // TestMemorySafetyBatch ensures it is safe to modify a key after passing it // to Batch.Put. -func TestMemorySafetyBatch(t *testing.T, db Database) { +func TestMemorySafetyBatch(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -347,7 +346,7 @@ func TestMemorySafetyBatch(t *testing.T, db Database) { // TestBatchReset tests to make sure that a batch drops un-written operations // when it is reset. -func TestBatchReset(t *testing.T, db Database) { +func TestBatchReset(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -376,7 +375,7 @@ func TestBatchReset(t *testing.T, db Database) { // TestBatchReuse tests to make sure that a batch can be reused once it is // reset. -func TestBatchReuse(t *testing.T, db Database) { +func TestBatchReuse(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -417,7 +416,7 @@ func TestBatchReuse(t *testing.T, db Database) { // TestBatchRewrite tests to make sure that write can be called multiple times // on a batch and the values will be updated correctly. -func TestBatchRewrite(t *testing.T, db Database) { +func TestBatchRewrite(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello1") @@ -447,7 +446,7 @@ func TestBatchRewrite(t *testing.T, db Database) { // TestBatchReplay tests to make sure that batches will correctly replay their // contents. -func TestBatchReplay(t *testing.T, db Database) { +func TestBatchReplay(t *testing.T, db database.Database) { ctrl := gomock.NewController(t) require := require.New(t) @@ -467,7 +466,7 @@ func TestBatchReplay(t *testing.T, db Database) { require.NoError(batch.Put(key1, value2)) for i := 0; i < 2; i++ { - mockBatch := NewMockBatch(ctrl) + mockBatch := database.NewMockBatch(ctrl) gomock.InOrder( mockBatch.EXPECT().Put(key1, value1).Times(1), mockBatch.EXPECT().Put(key2, value2).Times(1), @@ -482,7 +481,7 @@ func TestBatchReplay(t *testing.T, db Database) { // TestBatchReplayPropagateError tests to make sure that batches will correctly // propagate any returned error during Replay. -func TestBatchReplayPropagateError(t *testing.T, db Database) { +func TestBatchReplayPropagateError(t *testing.T, db database.Database) { ctrl := gomock.NewController(t) require := require.New(t) @@ -498,13 +497,13 @@ func TestBatchReplayPropagateError(t *testing.T, db Database) { require.NoError(batch.Put(key1, value1)) require.NoError(batch.Put(key2, value2)) - mockBatch := NewMockBatch(ctrl) + mockBatch := database.NewMockBatch(ctrl) gomock.InOrder( - mockBatch.EXPECT().Put(key1, value1).Return(ErrClosed).Times(1), + mockBatch.EXPECT().Put(key1, value1).Return(database.ErrClosed).Times(1), ) - require.Equal(ErrClosed, batch.Replay(mockBatch)) + require.Equal(database.ErrClosed, batch.Replay(mockBatch)) - mockBatch = NewMockBatch(ctrl) + mockBatch = database.NewMockBatch(ctrl) gomock.InOrder( mockBatch.EXPECT().Put(key1, value1).Return(io.ErrClosedPipe).Times(1), ) @@ -513,7 +512,7 @@ func TestBatchReplayPropagateError(t *testing.T, db Database) { // TestBatchInner tests to make sure that inner can be used to write to the // database. -func TestBatchInner(t *testing.T, db Database) { +func TestBatchInner(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -560,7 +559,7 @@ func TestBatchInner(t *testing.T, db Database) { // TestBatchLargeSize tests to make sure that the batch can support a large // amount of entries. -func TestBatchLargeSize(t *testing.T, db Database) { +func TestBatchLargeSize(t *testing.T, db database.Database) { require := require.New(t) totalSize := 8 * units.MiB @@ -587,7 +586,7 @@ func TestBatchLargeSize(t *testing.T, db Database) { // TestIteratorSnapshot tests to make sure the database iterates over a snapshot // of the database at the time of the iterator creation. -func TestIteratorSnapshot(t *testing.T, db Database) { +func TestIteratorSnapshot(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -616,7 +615,7 @@ func TestIteratorSnapshot(t *testing.T, db Database) { // TestIterator tests to make sure the database iterates over the database // contents lexicographically. -func TestIterator(t *testing.T, db Database) { +func TestIterator(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -649,7 +648,7 @@ func TestIterator(t *testing.T, db Database) { // TestIteratorStart tests to make sure the iterator can be configured to // start mid way through the database. -func TestIteratorStart(t *testing.T, db Database) { +func TestIteratorStart(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -678,7 +677,7 @@ func TestIteratorStart(t *testing.T, db Database) { // TestIteratorPrefix tests to make sure the iterator can be configured to skip // keys missing the provided prefix. -func TestIteratorPrefix(t *testing.T, db Database) { +func TestIteratorPrefix(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello") @@ -711,7 +710,7 @@ func TestIteratorPrefix(t *testing.T, db Database) { // TestIteratorStartPrefix tests to make sure that the iterator can start mid // way through the database while skipping a prefix. -func TestIteratorStartPrefix(t *testing.T, db Database) { +func TestIteratorStartPrefix(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -748,7 +747,7 @@ func TestIteratorStartPrefix(t *testing.T, db Database) { // TestIteratorMemorySafety tests to make sure that keys can values are able to // be modified from the returned iterator. -func TestIteratorMemorySafety(t *testing.T, db Database) { +func TestIteratorMemorySafety(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -799,7 +798,7 @@ func TestIteratorMemorySafety(t *testing.T, db Database) { // TestIteratorClosed tests to make sure that an iterator that was created with // a closed database will report a closed error correctly. -func TestIteratorClosed(t *testing.T, db Database) { +func TestIteratorClosed(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -817,7 +816,7 @@ func TestIteratorClosed(t *testing.T, db Database) { require.False(iterator.Next()) require.Nil(iterator.Key()) require.Nil(iterator.Value()) - require.Equal(ErrClosed, iterator.Error()) + require.Equal(database.ErrClosed, iterator.Error()) } { @@ -829,7 +828,7 @@ func TestIteratorClosed(t *testing.T, db Database) { require.False(iterator.Next()) require.Nil(iterator.Key()) require.Nil(iterator.Value()) - require.Equal(ErrClosed, iterator.Error()) + require.Equal(database.ErrClosed, iterator.Error()) } { @@ -841,7 +840,7 @@ func TestIteratorClosed(t *testing.T, db Database) { require.False(iterator.Next()) require.Nil(iterator.Key()) require.Nil(iterator.Value()) - require.Equal(ErrClosed, iterator.Error()) + require.Equal(database.ErrClosed, iterator.Error()) } { @@ -853,16 +852,16 @@ func TestIteratorClosed(t *testing.T, db Database) { require.False(iterator.Next()) require.Nil(iterator.Key()) require.Nil(iterator.Value()) - require.Equal(ErrClosed, iterator.Error()) + require.Equal(database.ErrClosed, iterator.Error()) } } // TestIteratorError tests to make sure that an iterator on a database will report -// itself as being exhausted and return [ErrClosed] to indicate that the iteration +// itself as being exhausted and return [database.ErrClosed] to indicate that the iteration // was not successful. // Additionally tests that an iterator that has already called Next() can still serve // its current value after the underlying DB was closed. -func TestIteratorError(t *testing.T, db Database) { +func TestIteratorError(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -890,12 +889,12 @@ func TestIteratorError(t *testing.T, db Database) { require.False(iterator.Next()) require.Nil(iterator.Key()) require.Nil(iterator.Value()) - require.Equal(ErrClosed, iterator.Error()) + require.Equal(database.ErrClosed, iterator.Error()) } // TestIteratorErrorAfterRelease tests to make sure that an iterator that was // released still reports the error correctly. -func TestIteratorErrorAfterRelease(t *testing.T, db Database) { +func TestIteratorErrorAfterRelease(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello1") @@ -912,11 +911,11 @@ func TestIteratorErrorAfterRelease(t *testing.T, db Database) { require.False(iterator.Next()) require.Nil(iterator.Key()) require.Nil(iterator.Value()) - require.Equal(ErrClosed, iterator.Error()) + require.Equal(database.ErrClosed, iterator.Error()) } // TestCompactNoPanic tests to make sure compact never panics. -func TestCompactNoPanic(t *testing.T, db Database) { +func TestCompactNoPanic(t *testing.T, db database.Database) { require := require.New(t) key1 := []byte("hello1") @@ -943,23 +942,23 @@ func TestCompactNoPanic(t *testing.T, db Database) { require.NoError(db.Close()) err := db.Compact(nil, nil) - require.ErrorIs(err, ErrClosed) + require.ErrorIs(err, database.ErrClosed) } -func TestAtomicClear(t *testing.T, db Database) { - testClear(t, db, func(db Database) error { - return AtomicClear(db, db) +func TestAtomicClear(t *testing.T, db database.Database) { + testClear(t, db, func(db database.Database) error { + return database.AtomicClear(db, db) }) } -func TestClear(t *testing.T, db Database) { - testClear(t, db, func(db Database) error { - return Clear(db, math.MaxInt) +func TestClear(t *testing.T, db database.Database) { + testClear(t, db, func(db database.Database) error { + return database.Clear(db, math.MaxInt) }) } // testClear tests to make sure the deletion helper works as expected. -func testClear(t *testing.T, db Database, clearF func(Database) error) { +func testClear(t *testing.T, db database.Database, clearF func(database.Database) error) { require := require.New(t) key1 := []byte("hello1") @@ -975,33 +974,33 @@ func testClear(t *testing.T, db Database, clearF func(Database) error) { require.NoError(db.Put(key2, value2)) require.NoError(db.Put(key3, value3)) - count, err := Count(db) + count, err := database.Count(db) require.NoError(err) require.Equal(3, count) require.NoError(clearF(db)) - count, err = Count(db) + count, err = database.Count(db) require.NoError(err) require.Zero(count) require.NoError(db.Close()) } -func TestAtomicClearPrefix(t *testing.T, db Database) { - testClearPrefix(t, db, func(db Database, prefix []byte) error { - return AtomicClearPrefix(db, db, prefix) +func TestAtomicClearPrefix(t *testing.T, db database.Database) { + testClearPrefix(t, db, func(db database.Database, prefix []byte) error { + return database.AtomicClearPrefix(db, db, prefix) }) } -func TestClearPrefix(t *testing.T, db Database) { - testClearPrefix(t, db, func(db Database, prefix []byte) error { - return ClearPrefix(db, prefix, math.MaxInt) +func TestClearPrefix(t *testing.T, db database.Database) { + testClearPrefix(t, db, func(db database.Database, prefix []byte) error { + return database.ClearPrefix(db, prefix, math.MaxInt) }) } // testClearPrefix tests to make sure prefix deletion works as expected. -func testClearPrefix(t *testing.T, db Database, clearF func(Database, []byte) error) { +func testClearPrefix(t *testing.T, db database.Database, clearF func(database.Database, []byte) error) { require := require.New(t) key1 := []byte("hello1") @@ -1017,13 +1016,13 @@ func testClearPrefix(t *testing.T, db Database, clearF func(Database, []byte) er require.NoError(db.Put(key2, value2)) require.NoError(db.Put(key3, value3)) - count, err := Count(db) + count, err := database.Count(db) require.NoError(err) require.Equal(3, count) require.NoError(clearF(db, []byte("hello"))) - count, err = Count(db) + count, err = database.Count(db) require.NoError(err) require.Equal(1, count) @@ -1042,7 +1041,7 @@ func testClearPrefix(t *testing.T, db Database, clearF func(Database, []byte) er require.NoError(db.Close()) } -func TestModifyValueAfterPut(t *testing.T, db Database) { +func TestModifyValueAfterPut(t *testing.T, db database.Database) { require := require.New(t) key := []byte{1} @@ -1059,7 +1058,7 @@ func TestModifyValueAfterPut(t *testing.T, db Database) { require.Equal(originalValue, retrievedValue) } -func TestModifyValueAfterBatchPut(t *testing.T, db Database) { +func TestModifyValueAfterBatchPut(t *testing.T, db database.Database) { require := require.New(t) key := []byte{1} @@ -1081,7 +1080,7 @@ func TestModifyValueAfterBatchPut(t *testing.T, db Database) { require.Equal(originalValue, retrievedValue) } -func TestModifyValueAfterBatchPutReplay(t *testing.T, db Database) { +func TestModifyValueAfterBatchPutReplay(t *testing.T, db database.Database) { require := require.New(t) key := []byte{1} @@ -1107,7 +1106,7 @@ func TestModifyValueAfterBatchPutReplay(t *testing.T, db Database) { require.Equal(originalValue, retrievedValue) } -func TestConcurrentBatches(t *testing.T, db Database) { +func TestConcurrentBatches(t *testing.T, db database.Database) { numBatches := 10 keysPerBatch := 50 keySize := 32 @@ -1122,7 +1121,7 @@ func TestConcurrentBatches(t *testing.T, db Database) { )) } -func TestManySmallConcurrentKVPairBatches(t *testing.T, db Database) { +func TestManySmallConcurrentKVPairBatches(t *testing.T, db database.Database) { numBatches := 100 keysPerBatch := 10 keySize := 10 @@ -1138,13 +1137,13 @@ func TestManySmallConcurrentKVPairBatches(t *testing.T, db Database) { } func runConcurrentBatches( - db Database, + db database.Database, numBatches, keysPerBatch, keySize, valueSize int, ) error { - batches := make([]Batch, 0, numBatches) + batches := make([]database.Batch, 0, numBatches) for i := 0; i < numBatches; i++ { batches = append(batches, db.NewBatch()) } @@ -1166,7 +1165,7 @@ func runConcurrentBatches( return eg.Wait() } -func TestPutGetEmpty(t *testing.T, db Database) { +func TestPutGetEmpty(t *testing.T, db database.Database) { require := require.New(t) key := []byte("hello") @@ -1184,7 +1183,7 @@ func TestPutGetEmpty(t *testing.T, db Database) { require.Empty(value) // May be nil or empty byte slice. } -func FuzzKeyValue(f *testing.F, db Database) { +func FuzzKeyValue(f *testing.F, db database.Database) { f.Fuzz(func(t *testing.T, key []byte, value []byte) { require := require.New(t) @@ -1205,11 +1204,11 @@ func FuzzKeyValue(f *testing.F, db Database) { require.False(exists) _, err = db.Get(key) - require.Equal(ErrNotFound, err) + require.Equal(database.ErrNotFound, err) }) } -func FuzzNewIteratorWithPrefix(f *testing.F, db Database) { +func FuzzNewIteratorWithPrefix(f *testing.F, db database.Database) { const ( maxKeyLen = 32 maxValueLen = 32 @@ -1268,11 +1267,11 @@ func FuzzNewIteratorWithPrefix(f *testing.F, db Database) { require.Len(expectedList, numIterElts) // Clear the database for the next fuzz iteration. - require.NoError(AtomicClear(db, db)) + require.NoError(database.AtomicClear(db, db)) }) } -func FuzzNewIteratorWithStartAndPrefix(f *testing.F, db Database) { +func FuzzNewIteratorWithStartAndPrefix(f *testing.F, db database.Database) { const ( maxKeyLen = 32 maxValueLen = 32 @@ -1335,6 +1334,6 @@ func FuzzNewIteratorWithStartAndPrefix(f *testing.F, db Database) { require.Len(expectedList, numIterElts) // Clear the database for the next fuzz iteration. - require.NoError(AtomicClear(db, db)) + require.NoError(database.AtomicClear(db, db)) }) } diff --git a/database/encdb/db_test.go b/database/encdb/db_test.go index b3dfdfed68e7..54bae29385b8 100644 --- a/database/encdb/db_test.go +++ b/database/encdb/db_test.go @@ -10,13 +10,14 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" ) const testPassword = "lol totally a secure password" //nolint:gosec func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { unencryptedDB := memdb.New() db, err := New([]byte(testPassword), unencryptedDB) @@ -35,21 +36,21 @@ func newDB(t testing.TB) database.Database { } func FuzzKeyValue(f *testing.F) { - database.FuzzKeyValue(f, newDB(f)) + dbtest.FuzzKeyValue(f, newDB(f)) } func FuzzNewIteratorWithPrefix(f *testing.F) { - database.FuzzNewIteratorWithPrefix(f, newDB(f)) + dbtest.FuzzNewIteratorWithPrefix(f, newDB(f)) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { - database.FuzzNewIteratorWithStartAndPrefix(f, newDB(f)) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, newDB(f)) } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("encdb_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { bench(b, newDB(b), keys, values) }) diff --git a/database/leveldb/db_test.go b/database/leveldb/db_test.go index 65214d080846..f1e2bce9c0ca 100644 --- a/database/leveldb/db_test.go +++ b/database/leveldb/db_test.go @@ -11,11 +11,12 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/utils/logging" ) func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { folder := t.TempDir() db, err := New(folder, nil, logging.NoLog{}, prometheus.NewRegistry()) @@ -39,27 +40,27 @@ func FuzzKeyValue(f *testing.F) { db := newDB(f) defer db.Close() - database.FuzzKeyValue(f, db) + dbtest.FuzzKeyValue(f, db) } func FuzzNewIteratorWithPrefix(f *testing.F) { db := newDB(f) defer db.Close() - database.FuzzNewIteratorWithPrefix(f, db) + dbtest.FuzzNewIteratorWithPrefix(f, db) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { db := newDB(f) defer db.Close() - database.FuzzNewIteratorWithStartAndPrefix(f, db) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, db) } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("leveldb_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { db := newDB(b) diff --git a/database/memdb/db_test.go b/database/memdb/db_test.go index 90dc459f3602..cc6e1364a788 100644 --- a/database/memdb/db_test.go +++ b/database/memdb/db_test.go @@ -7,11 +7,11 @@ import ( "fmt" "testing" - "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" ) func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { test(t, New()) }) @@ -19,21 +19,21 @@ func TestInterface(t *testing.T) { } func FuzzKeyValue(f *testing.F) { - database.FuzzKeyValue(f, New()) + dbtest.FuzzKeyValue(f, New()) } func FuzzNewIteratorWithPrefix(f *testing.F) { - database.FuzzNewIteratorWithPrefix(f, New()) + dbtest.FuzzNewIteratorWithPrefix(f, New()) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { - database.FuzzNewIteratorWithStartAndPrefix(f, New()) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, New()) } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("memdb_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { db := New() bench(b, db, keys, values) diff --git a/database/meterdb/db_test.go b/database/meterdb/db_test.go index 57cedc181043..1e68b41aac46 100644 --- a/database/meterdb/db_test.go +++ b/database/meterdb/db_test.go @@ -11,11 +11,12 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" ) func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { baseDB := memdb.New() db, err := New(prometheus.NewRegistry(), baseDB) @@ -34,21 +35,21 @@ func newDB(t testing.TB) database.Database { } func FuzzKeyValue(f *testing.F) { - database.FuzzKeyValue(f, newDB(f)) + dbtest.FuzzKeyValue(f, newDB(f)) } func FuzzNewIteratorWithPrefix(f *testing.F) { - database.FuzzNewIteratorWithPrefix(f, newDB(f)) + dbtest.FuzzNewIteratorWithPrefix(f, newDB(f)) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { - database.FuzzNewIteratorWithStartAndPrefix(f, newDB(f)) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, newDB(f)) } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("meterdb_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { bench(b, newDB(b), keys, values) }) diff --git a/database/pebbledb/db_test.go b/database/pebbledb/db_test.go index 7d48a00c627a..f230152b30b3 100644 --- a/database/pebbledb/db_test.go +++ b/database/pebbledb/db_test.go @@ -10,7 +10,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/utils/logging" ) @@ -22,7 +22,7 @@ func newDB(t testing.TB) *Database { } func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { db := newDB(t) test(t, db) @@ -33,26 +33,26 @@ func TestInterface(t *testing.T) { func FuzzKeyValue(f *testing.F) { db := newDB(f) - database.FuzzKeyValue(f, db) + dbtest.FuzzKeyValue(f, db) _ = db.Close() } func FuzzNewIteratorWithPrefix(f *testing.F) { db := newDB(f) - database.FuzzNewIteratorWithPrefix(f, db) + dbtest.FuzzNewIteratorWithPrefix(f, db) _ = db.Close() } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { db := newDB(f) - database.FuzzNewIteratorWithStartAndPrefix(f, db) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, db) _ = db.Close() } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("pebble_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { db := newDB(b) bench(b, db, keys, values) diff --git a/database/prefixdb/db_test.go b/database/prefixdb/db_test.go index 82b801f22e8f..714acddd5876 100644 --- a/database/prefixdb/db_test.go +++ b/database/prefixdb/db_test.go @@ -9,12 +9,12 @@ import ( "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" ) func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { db := memdb.New() test(t, New([]byte("hello"), db)) @@ -37,21 +37,21 @@ func TestPrefixLimit(t *testing.T) { } func FuzzKeyValue(f *testing.F) { - database.FuzzKeyValue(f, New([]byte(""), memdb.New())) + dbtest.FuzzKeyValue(f, New([]byte(""), memdb.New())) } func FuzzNewIteratorWithPrefix(f *testing.F) { - database.FuzzNewIteratorWithPrefix(f, New([]byte(""), memdb.New())) + dbtest.FuzzNewIteratorWithPrefix(f, New([]byte(""), memdb.New())) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { - database.FuzzNewIteratorWithStartAndPrefix(f, New([]byte(""), memdb.New())) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, New([]byte(""), memdb.New())) } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("prefixdb_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { db := New([]byte("hello"), memdb.New()) bench(b, db, keys, values) diff --git a/database/rpcdb/db_test.go b/database/rpcdb/db_test.go index cc0cca3694b0..82070ed765e8 100644 --- a/database/rpcdb/db_test.go +++ b/database/rpcdb/db_test.go @@ -10,8 +10,8 @@ import ( "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/corruptabledb" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils" @@ -55,7 +55,7 @@ func setupDB(t testing.TB) *testDatabase { } func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { db := setupDB(t) test(t, db.client) @@ -65,23 +65,23 @@ func TestInterface(t *testing.T) { func FuzzKeyValue(f *testing.F) { db := setupDB(f) - database.FuzzKeyValue(f, db.client) + dbtest.FuzzKeyValue(f, db.client) } func FuzzNewIteratorWithPrefix(f *testing.F) { db := setupDB(f) - database.FuzzNewIteratorWithPrefix(f, db.client) + dbtest.FuzzNewIteratorWithPrefix(f, db.client) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { db := setupDB(f) - database.FuzzNewIteratorWithStartAndPrefix(f, db.client) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, db.client) } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("rpcdb_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { db := setupDB(b) bench(b, db.client, keys, values) diff --git a/database/versiondb/db_test.go b/database/versiondb/db_test.go index 0ff801dfe0dd..4a98d82b3258 100644 --- a/database/versiondb/db_test.go +++ b/database/versiondb/db_test.go @@ -10,11 +10,12 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" ) func TestInterface(t *testing.T) { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(name, func(t *testing.T) { baseDB := memdb.New() test(t, New(baseDB)) @@ -23,15 +24,15 @@ func TestInterface(t *testing.T) { } func FuzzKeyValue(f *testing.F) { - database.FuzzKeyValue(f, New(memdb.New())) + dbtest.FuzzKeyValue(f, New(memdb.New())) } func FuzzNewIteratorWithPrefix(f *testing.F) { - database.FuzzNewIteratorWithPrefix(f, New(memdb.New())) + dbtest.FuzzNewIteratorWithPrefix(f, New(memdb.New())) } func FuzzNewIteratorWithStartAndPrefix(f *testing.F) { - database.FuzzNewIteratorWithStartAndPrefix(f, New(memdb.New())) + dbtest.FuzzNewIteratorWithStartAndPrefix(f, New(memdb.New())) } func TestIterate(t *testing.T) { @@ -300,9 +301,9 @@ func TestSetDatabaseClosed(t *testing.T) { } func BenchmarkInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) - for name, bench := range database.Benchmarks { + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("versiondb_%d_pairs_%d_keys_%d_values_%s", size[0], size[1], size[2], name), func(b *testing.B) { baseDB := memdb.New() db := New(baseDB) diff --git a/go.mod b/go.mod index 00458471b34e..f440ad419e1e 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/DataDog/zstd v1.5.2 github.com/NYTimes/gziphandler v1.1.1 github.com/antithesishq/antithesis-sdk-go v0.3.8 - github.com/ava-labs/coreth v0.13.7 + github.com/ava-labs/coreth v0.13.8-0.20240802110637-b3e5088d062d github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 github.com/btcsuite/btcd/btcutil v1.1.3 github.com/cockroachdb/pebble v0.0.0-20230928194634-aa077af62593 diff --git a/go.sum b/go.sum index 1887349b142c..4f50be7c1b7c 100644 --- a/go.sum +++ b/go.sum @@ -62,8 +62,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/antithesishq/antithesis-sdk-go v0.3.8 h1:OvGoHxIcOXFJLyn9IJQ5DzByZ3YVAWNBc394ObzDRb8= github.com/antithesishq/antithesis-sdk-go v0.3.8/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/coreth v0.13.7 h1:k8T9u/ROifl8f7oXjHRc1KvSISRl9txvy7gGVmHEz6g= -github.com/ava-labs/coreth v0.13.7/go.mod h1:tXDujonxXFOF6oK5HS2EmgtSXJK3Gy6RpZxb5WzR9rM= +github.com/ava-labs/coreth v0.13.8-0.20240802110637-b3e5088d062d h1:klPTcKVvqfA2KSKaRvQAO56Pd4XAqGhwgMTQ6/W+w7w= +github.com/ava-labs/coreth v0.13.8-0.20240802110637-b3e5088d062d/go.mod h1:tXDujonxXFOF6oK5HS2EmgtSXJK3Gy6RpZxb5WzR9rM= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 h1:dOVbtdnZL++pENdTCNZ1nu41eYDQkTML4sWebDnnq8c= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95/go.mod h1:pJxaT9bUgeRNVmNRgtCHb7sFDIRKy7CzTQVi8gGNT6g= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= diff --git a/ids/aliases_test.go b/ids/aliases_test.go index 6c77d7443703..aeed141c2327 100644 --- a/ids/aliases_test.go +++ b/ids/aliases_test.go @@ -1,17 +1,21 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package ids +package ids_test import ( "testing" "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/ids/idstest" + + . "github.com/ava-labs/avalanchego/ids" ) func TestAliaser(t *testing.T) { require := require.New(t) - for _, test := range AliasTests { + for _, test := range idstest.AliasTests { aliaser := NewAliaser() test(require, aliaser, aliaser) } diff --git a/ids/galiasreader/alias_reader_test.go b/ids/galiasreader/alias_reader_test.go index 899c13a24ed2..59c6c4228984 100644 --- a/ids/galiasreader/alias_reader_test.go +++ b/ids/galiasreader/alias_reader_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/ids/idstest" "github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils" aliasreaderpb "github.com/ava-labs/avalanchego/proto/pb/aliasreader" @@ -17,7 +18,7 @@ import ( func TestInterface(t *testing.T) { require := require.New(t) - for _, test := range ids.AliasTests { + for _, test := range idstest.AliasTests { listener, err := grpcutils.NewListener() require.NoError(err) serverCloser := grpcutils.ServerCloser{} diff --git a/ids/test_aliases.go b/ids/idstest/aliases.go similarity index 54% rename from ids/test_aliases.go rename to ids/idstest/aliases.go index 3943fce16023..2dd44e564a2d 100644 --- a/ids/test_aliases.go +++ b/ids/idstest/aliases.go @@ -1,13 +1,15 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test +package idstest -package ids +import ( + "github.com/stretchr/testify/require" -import "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/ids" +) -var AliasTests = []func(require *require.Assertions, r AliaserReader, w AliaserWriter){ +var AliasTests = []func(require *require.Assertions, r ids.AliaserReader, w ids.AliaserWriter){ AliaserLookupErrorTest, AliaserLookupTest, AliaserAliasesEmptyTest, @@ -17,14 +19,14 @@ var AliasTests = []func(require *require.Assertions, r AliaserReader, w AliaserW AliaserRemoveAliasTest, } -func AliaserLookupErrorTest(require *require.Assertions, r AliaserReader, _ AliaserWriter) { +func AliaserLookupErrorTest(require *require.Assertions, r ids.AliaserReader, _ ids.AliaserWriter) { _, err := r.Lookup("Batman") // TODO: require error to be errNoIDWithAlias require.Error(err) //nolint:forbidigo // currently returns grpc errors too } -func AliaserLookupTest(require *require.Assertions, r AliaserReader, w AliaserWriter) { - id := ID{'K', 'a', 't', 'e', ' ', 'K', 'a', 'n', 'e'} +func AliaserLookupTest(require *require.Assertions, r ids.AliaserReader, w ids.AliaserWriter) { + id := ids.ID{'K', 'a', 't', 'e', ' ', 'K', 'a', 'n', 'e'} require.NoError(w.Alias(id, "Batwoman")) res, err := r.Lookup("Batwoman") @@ -32,16 +34,16 @@ func AliaserLookupTest(require *require.Assertions, r AliaserReader, w AliaserWr require.Equal(id, res) } -func AliaserAliasesEmptyTest(require *require.Assertions, r AliaserReader, _ AliaserWriter) { - id := ID{'J', 'a', 'm', 'e', 's', ' ', 'G', 'o', 'r', 'd', 'o', 'n'} +func AliaserAliasesEmptyTest(require *require.Assertions, r ids.AliaserReader, _ ids.AliaserWriter) { + id := ids.ID{'J', 'a', 'm', 'e', 's', ' ', 'G', 'o', 'r', 'd', 'o', 'n'} aliases, err := r.Aliases(id) require.NoError(err) require.Empty(aliases) } -func AliaserAliasesTest(require *require.Assertions, r AliaserReader, w AliaserWriter) { - id := ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} +func AliaserAliasesTest(require *require.Assertions, r ids.AliaserReader, w ids.AliaserWriter) { + id := ids.ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} require.NoError(w.Alias(id, "Batman")) require.NoError(w.Alias(id, "Dark Knight")) @@ -53,9 +55,9 @@ func AliaserAliasesTest(require *require.Assertions, r AliaserReader, w AliaserW require.Equal(expected, aliases) } -func AliaserPrimaryAliasTest(require *require.Assertions, r AliaserReader, w AliaserWriter) { - id1 := ID{'J', 'a', 'm', 'e', 's', ' ', 'G', 'o', 'r', 'd', 'o', 'n'} - id2 := ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} +func AliaserPrimaryAliasTest(require *require.Assertions, r ids.AliaserReader, w ids.AliaserWriter) { + id1 := ids.ID{'J', 'a', 'm', 'e', 's', ' ', 'G', 'o', 'r', 'd', 'o', 'n'} + id2 := ids.ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} require.NoError(w.Alias(id2, "Batman")) require.NoError(w.Alias(id2, "Dark Knight")) @@ -70,9 +72,9 @@ func AliaserPrimaryAliasTest(require *require.Assertions, r AliaserReader, w Ali require.Equal(expected, res) } -func AliaserAliasClashTest(require *require.Assertions, _ AliaserReader, w AliaserWriter) { - id1 := ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} - id2 := ID{'D', 'i', 'c', 'k', ' ', 'G', 'r', 'a', 'y', 's', 'o', 'n'} +func AliaserAliasClashTest(require *require.Assertions, _ ids.AliaserReader, w ids.AliaserWriter) { + id1 := ids.ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} + id2 := ids.ID{'D', 'i', 'c', 'k', ' ', 'G', 'r', 'a', 'y', 's', 'o', 'n'} require.NoError(w.Alias(id1, "Batman")) @@ -81,9 +83,9 @@ func AliaserAliasClashTest(require *require.Assertions, _ AliaserReader, w Alias require.Error(err) //nolint:forbidigo // currently returns grpc errors too } -func AliaserRemoveAliasTest(require *require.Assertions, r AliaserReader, w AliaserWriter) { - id1 := ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} - id2 := ID{'J', 'a', 'm', 'e', 's', ' ', 'G', 'o', 'r', 'd', 'o', 'n'} +func AliaserRemoveAliasTest(require *require.Assertions, r ids.AliaserReader, w ids.AliaserWriter) { + id1 := ids.ID{'B', 'r', 'u', 'c', 'e', ' ', 'W', 'a', 'y', 'n', 'e'} + id2 := ids.ID{'J', 'a', 'm', 'e', 's', ' ', 'G', 'o', 'r', 'd', 'o', 'n'} require.NoError(w.Alias(id1, "Batman")) require.NoError(w.Alias(id1, "Dark Knight")) diff --git a/network/p2p/gossip/gossip_test.go b/network/p2p/gossip/gossip_test.go index a1eed80bed3b..5615fc2d35f3 100644 --- a/network/p2p/gossip/gossip_test.go +++ b/network/p2p/gossip/gossip_test.go @@ -17,8 +17,9 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/network/p2p" "github.com/ava-labs/avalanchego/proto/pb/sdk" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" @@ -104,7 +105,7 @@ func TestGossiperGossip(t *testing.T) { require := require.New(t) ctx := context.Background() - responseSender := &common.FakeSender{ + responseSender := &enginetest.FakeSender{ SentAppResponse: make(chan []byte, 1), } responseNetwork, err := p2p.NewNetwork(logging.NoLog{}, responseSender, prometheus.NewRegistry(), "") @@ -133,7 +134,7 @@ func TestGossiperGossip(t *testing.T) { require.NoError(err) require.NoError(responseNetwork.AddHandler(0x0, handler)) - requestSender := &common.FakeSender{ + requestSender := &enginetest.FakeSender{ SentAppRequest: make(chan []byte, 1), } @@ -509,7 +510,7 @@ func TestPushGossiper(t *testing.T) { require := require.New(t) ctx := context.Background() - sender := &common.FakeSender{ + sender := &enginetest.FakeSender{ SentAppGossip: make(chan []byte, 2), } network, err := p2p.NewNetwork( @@ -524,7 +525,7 @@ func TestPushGossiper(t *testing.T) { &p2p.Peers{}, logging.NoLog{}, constants.PrimaryNetworkID, - &validators.TestState{ + &validatorstest.TestState{ GetCurrentHeightF: func(context.Context) (uint64, error) { return 1, nil }, diff --git a/network/p2p/network_test.go b/network/p2p/network_test.go index 5346a9255a00..3afc9bbcd97a 100644 --- a/network/p2p/network_test.go +++ b/network/p2p/network_test.go @@ -13,7 +13,9 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" @@ -57,7 +59,7 @@ func TestMessageRouting(t *testing.T) { }, } - sender := &common.FakeSender{ + sender := &enginetest.FakeSender{ SentAppGossip: make(chan []byte, 1), SentAppRequest: make(chan []byte, 1), SentCrossChainAppRequest: make(chan []byte, 1), @@ -92,7 +94,7 @@ func TestClientPrefixesMessages(t *testing.T) { require := require.New(t) ctx := context.Background() - sender := common.FakeSender{ + sender := enginetest.FakeSender{ SentAppRequest: make(chan []byte, 1), SentAppGossip: make(chan []byte, 1), SentCrossChainAppRequest: make(chan []byte, 1), @@ -151,7 +153,7 @@ func TestAppRequestResponse(t *testing.T) { require := require.New(t) ctx := context.Background() - sender := common.FakeSender{ + sender := enginetest.FakeSender{ SentAppRequest: make(chan []byte, 1), } network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") @@ -186,7 +188,7 @@ func TestAppRequestCancelledContext(t *testing.T) { ctx := context.Background() sentMessages := make(chan []byte, 1) - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ SendAppRequestF: func(ctx context.Context, _ set.Set[ids.NodeID], _ uint32, msgBytes []byte) error { require.NoError(ctx.Err()) sentMessages <- msgBytes @@ -227,7 +229,7 @@ func TestAppRequestFailed(t *testing.T) { require := require.New(t) ctx := context.Background() - sender := common.FakeSender{ + sender := enginetest.FakeSender{ SentAppRequest: make(chan []byte, 1), } network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") @@ -257,7 +259,7 @@ func TestCrossChainAppRequestResponse(t *testing.T) { require := require.New(t) ctx := context.Background() - sender := common.FakeSender{ + sender := enginetest.FakeSender{ SentCrossChainAppRequest: make(chan []byte, 1), } network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") @@ -289,7 +291,7 @@ func TestCrossChainAppRequestCancelledContext(t *testing.T) { ctx := context.Background() sentMessages := make(chan []byte, 1) - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ SendCrossChainAppRequestF: func(ctx context.Context, _ ids.ID, _ uint32, msgBytes []byte) { require.NoError(ctx.Err()) sentMessages <- msgBytes @@ -326,7 +328,7 @@ func TestCrossChainAppRequestFailed(t *testing.T) { require := require.New(t) ctx := context.Background() - sender := common.FakeSender{ + sender := enginetest.FakeSender{ SentCrossChainAppRequest: make(chan []byte, 1), } network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") @@ -424,7 +426,7 @@ func TestAppRequestMessageForUnregisteredHandler(t *testing.T) { wantRequestID := uint32(111) done := make(chan struct{}) - sender := &common.SenderTest{} + sender := &enginetest.SenderTest{} sender.SendAppErrorF = func(_ context.Context, nodeID ids.NodeID, requestID uint32, errorCode int32, errorMessage string) error { defer close(done) @@ -463,7 +465,7 @@ func TestAppError(t *testing.T) { wantRequestID := uint32(111) done := make(chan struct{}) - sender := &common.SenderTest{} + sender := &enginetest.SenderTest{} sender.SendAppErrorF = func(_ context.Context, nodeID ids.NodeID, requestID uint32, errorCode int32, errorMessage string) error { defer close(done) @@ -544,7 +546,7 @@ func TestAppRequestDuplicateRequestIDs(t *testing.T) { require := require.New(t) ctx := context.Background() - sender := &common.FakeSender{ + sender := &enginetest.FakeSender{ SentAppRequest: make(chan []byte, 1), } @@ -630,7 +632,7 @@ func TestPeersSample(t *testing.T) { t.Run(tt.name, func(t *testing.T) { require := require.New(t) - network, err := NewNetwork(logging.NoLog{}, &common.FakeSender{}, prometheus.NewRegistry(), "") + network, err := NewNetwork(logging.NoLog{}, &enginetest.FakeSender{}, prometheus.NewRegistry(), "") require.NoError(err) for connected := range tt.connected { @@ -673,7 +675,7 @@ func TestAppRequestAnyNodeSelection(t *testing.T) { require := require.New(t) sent := set.Set[ids.NodeID]{} - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ SendAppRequestF: func(_ context.Context, nodeIDs set.Set[ids.NodeID], _ uint32, _ []byte) error { sent = nodeIDs return nil @@ -719,7 +721,7 @@ func TestNodeSamplerClientOption(t *testing.T) { name: "validator connected", peers: []ids.NodeID{nodeID0, nodeID1}, option: func(_ *testing.T, n *Network) ClientOption { - state := &validators.TestState{ + state := &validatorstest.TestState{ GetCurrentHeightF: func(context.Context) (uint64, error) { return 0, nil }, @@ -742,7 +744,7 @@ func TestNodeSamplerClientOption(t *testing.T) { name: "validator disconnected", peers: []ids.NodeID{nodeID0}, option: func(_ *testing.T, n *Network) ClientOption { - state := &validators.TestState{ + state := &validatorstest.TestState{ GetCurrentHeightF: func(context.Context) (uint64, error) { return 0, nil }, @@ -768,7 +770,7 @@ func TestNodeSamplerClientOption(t *testing.T) { require := require.New(t) done := make(chan struct{}) - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ SendAppRequestF: func(_ context.Context, nodeIDs set.Set[ids.NodeID], _ uint32, _ []byte) error { require.Subset(tt.expected, nodeIDs.List()) close(done) @@ -798,7 +800,7 @@ func TestNodeSamplerClientOption(t *testing.T) { func TestMultipleClients(t *testing.T) { require := require.New(t) - n, err := NewNetwork(logging.NoLog{}, &common.SenderTest{}, prometheus.NewRegistry(), "") + n, err := NewNetwork(logging.NoLog{}, &enginetest.SenderTest{}, prometheus.NewRegistry(), "") require.NoError(err) _ = n.NewClient(0) _ = n.NewClient(0) diff --git a/network/p2p/validators_test.go b/network/p2p/validators_test.go index 49b2197f132a..2c7787904f8c 100644 --- a/network/p2p/validators_test.go +++ b/network/p2p/validators_test.go @@ -14,7 +14,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/logging" ) @@ -195,7 +195,7 @@ func TestValidatorsSample(t *testing.T) { } gomock.InOrder(calls...) - network, err := NewNetwork(logging.NoLog{}, &common.FakeSender{}, prometheus.NewRegistry(), "") + network, err := NewNetwork(logging.NoLog{}, &enginetest.FakeSender{}, prometheus.NewRegistry(), "") require.NoError(err) ctx := context.Background() @@ -315,7 +315,7 @@ func TestValidatorsTop(t *testing.T) { mockValidators.EXPECT().GetCurrentHeight(gomock.Any()).Return(uint64(1), nil) mockValidators.EXPECT().GetValidatorSet(gomock.Any(), uint64(1), subnetID).Return(validatorSet, nil) - network, err := NewNetwork(logging.NoLog{}, &common.FakeSender{}, prometheus.NewRegistry(), "") + network, err := NewNetwork(logging.NoLog{}, &enginetest.FakeSender{}, prometheus.NewRegistry(), "") require.NoError(err) ctx := context.Background() diff --git a/scripts/lint.sh b/scripts/lint.sh index 96cd538926d8..c35a87dd7910 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -99,11 +99,10 @@ function test_import_testing_only_in_tests { # IMPORT_GOMOCK=$( echo "${NON_TEST_GO_FILES}" | xargs grep -l '"go.uber.org/mock'); HAVE_TEST_LOGIC=$( printf "%s\n%s\n%s\n%s" "${IMPORT_TESTING}" "${IMPORT_TESTIFY}" "${IMPORT_FROM_TESTS}" "${IMPORT_TEST_PKG}" ); - TAGGED_AS_TEST=$( echo "${NON_TEST_GO_FILES}" | xargs grep -lP '^\/\/go:build\s+(.+(,|\s+))?test[,\s]?'); IN_TEST_PKG=$( echo "${NON_TEST_GO_FILES}" | grep -P '.*test/[^/]+\.go$' ) # directory (hence package name) ends in "test" # Files in /tests/ are already excluded by the `find ... ! -path` - INTENDED_FOR_TESTING=$( printf "%s\n%s" "${TAGGED_AS_TEST}" "${IN_TEST_PKG}" ) + INTENDED_FOR_TESTING="${IN_TEST_PKG}" # -3 suppresses files that have test logic and have the "test" build tag # -2 suppresses files that are tagged despite not having detectable test logic @@ -113,7 +112,7 @@ function test_import_testing_only_in_tests { return 0; fi - echo 'Non-test Go files importing test-only packages MUST (a) have '//go:build test' tag; (b) be in *test package; or (c) be in /tests/ directory:'; + echo 'Non-test Go files importing test-only packages MUST (a) be in *test package; or (b) be in /tests/ directory:'; echo "${UNTAGGED}"; return 1; } diff --git a/snow/consensus/snowball/test_snowflake.go b/snow/consensus/snowball/snowflake_test.go similarity index 99% rename from snow/consensus/snowball/test_snowflake.go rename to snow/consensus/snowball/snowflake_test.go index 8688ee82c09b..78ce95b27e3d 100644 --- a/snow/consensus/snowball/test_snowflake.go +++ b/snow/consensus/snowball/snowflake_test.go @@ -1,8 +1,6 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - package snowball import "testing" diff --git a/snow/engine/avalanche/bootstrap/bootstrapper_test.go b/snow/engine/avalanche/bootstrap/bootstrapper_test.go index 2792e8682f61..abd6304f2651 100644 --- a/snow/engine/avalanche/bootstrap/bootstrapper_test.go +++ b/snow/engine/avalanche/bootstrap/bootstrapper_test.go @@ -23,9 +23,9 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowstorm" "github.com/ava-labs/avalanchego/snow/engine/avalanche/bootstrap/queue" "github.com/ava-labs/avalanchego/snow/engine/avalanche/getter" - "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex/vertextest" "github.com/ava-labs/avalanchego/snow/engine/common/tracker" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" @@ -56,7 +56,7 @@ func (t *testTx) Accept(ctx context.Context) error { return nil } -func newConfig(t *testing.T) (Config, ids.NodeID, *common.SenderTest, *vertex.TestManager, *vertex.TestVM) { +func newConfig(t *testing.T) (Config, ids.NodeID, *enginetest.SenderTest, *vertextest.TestManager, *vertextest.TestVM) { require := require.New(t) snowCtx := snowtest.Context(t, snowtest.CChainID) @@ -64,9 +64,9 @@ func newConfig(t *testing.T) (Config, ids.NodeID, *common.SenderTest, *vertex.Te vdrs := validators.NewManager() db := memdb.New() - sender := &common.SenderTest{T: t} - manager := vertex.NewTestManager(t) - vm := &vertex.TestVM{} + sender := &enginetest.SenderTest{T: t} + manager := vertextest.NewTestManager(t) + vm := &vertextest.TestVM{} vm.T = t sender.Default(true) diff --git a/snow/engine/avalanche/bootstrap/queue/test_job.go b/snow/engine/avalanche/bootstrap/queue/job_test.go similarity index 99% rename from snow/engine/avalanche/bootstrap/queue/test_job.go rename to snow/engine/avalanche/bootstrap/queue/job_test.go index 8884ee0a2357..91a370b96d81 100644 --- a/snow/engine/avalanche/bootstrap/queue/test_job.go +++ b/snow/engine/avalanche/bootstrap/queue/job_test.go @@ -1,8 +1,6 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - package queue import ( diff --git a/snow/engine/avalanche/bootstrap/queue/test_parser.go b/snow/engine/avalanche/bootstrap/queue/parser_test.go similarity index 97% rename from snow/engine/avalanche/bootstrap/queue/test_parser.go rename to snow/engine/avalanche/bootstrap/queue/parser_test.go index 2787973d267e..1cc1cfd2973f 100644 --- a/snow/engine/avalanche/bootstrap/queue/test_parser.go +++ b/snow/engine/avalanche/bootstrap/queue/parser_test.go @@ -1,8 +1,6 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - package queue import ( diff --git a/snow/engine/avalanche/state/unique_vertex_test.go b/snow/engine/avalanche/state/unique_vertex_test.go index 206b04c7d0e9..f37896474013 100644 --- a/snow/engine/avalanche/state/unique_vertex_test.go +++ b/snow/engine/avalanche/state/unique_vertex_test.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/snow/consensus/snowstorm" "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex/vertextest" "github.com/ava-labs/avalanchego/utils/hashing" "github.com/ava-labs/avalanchego/utils/logging" ) @@ -23,7 +24,7 @@ import ( var errUnknownTx = errors.New("unknown tx") func newTestSerializer(t *testing.T, parse func(context.Context, []byte) (snowstorm.Tx, error)) *Serializer { - vm := vertex.TestVM{} + vm := vertextest.TestVM{} vm.T = t vm.Default(true) vm.ParseTxF = parse diff --git a/snow/engine/avalanche/vertex/test_builder.go b/snow/engine/avalanche/vertex/vertextest/builder.go similarity index 87% rename from snow/engine/avalanche/vertex/test_builder.go rename to snow/engine/avalanche/vertex/vertextest/builder.go index 90d603fc10a9..828fbaa00199 100644 --- a/snow/engine/avalanche/vertex/test_builder.go +++ b/snow/engine/avalanche/vertex/vertextest/builder.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package vertex +package vertextest import ( "context" @@ -14,12 +12,13 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/avalanche" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" ) var ( errBuild = errors.New("unexpectedly called Build") - _ Builder = (*TestBuilder)(nil) + _ vertex.Builder = (*TestBuilder)(nil) ) type TestBuilder struct { diff --git a/snow/engine/avalanche/vertex/test_manager.go b/snow/engine/avalanche/vertex/vertextest/manager.go similarity index 76% rename from snow/engine/avalanche/vertex/test_manager.go rename to snow/engine/avalanche/vertex/vertextest/manager.go index 22bb6ce696eb..0ccee48a8e19 100644 --- a/snow/engine/avalanche/vertex/test_manager.go +++ b/snow/engine/avalanche/vertex/vertextest/manager.go @@ -1,13 +1,15 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test +package vertextest -package vertex +import ( + "testing" -import "testing" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" +) -var _ Manager = (*TestManager)(nil) +var _ vertex.Manager = (*TestManager)(nil) type TestManager struct { TestBuilder diff --git a/snow/engine/avalanche/vertex/test_parser.go b/snow/engine/avalanche/vertex/vertextest/parser.go similarity index 86% rename from snow/engine/avalanche/vertex/test_parser.go rename to snow/engine/avalanche/vertex/vertextest/parser.go index d3c2b0b8d8a2..21a308690bd6 100644 --- a/snow/engine/avalanche/vertex/test_parser.go +++ b/snow/engine/avalanche/vertex/vertextest/parser.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package vertex +package vertextest import ( "context" @@ -13,12 +11,13 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/snow/consensus/avalanche" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" ) var ( errParse = errors.New("unexpectedly called Parse") - _ Parser = (*TestParser)(nil) + _ vertex.Parser = (*TestParser)(nil) ) type TestParser struct { diff --git a/snow/engine/avalanche/vertex/test_storage.go b/snow/engine/avalanche/vertex/vertextest/storage.go similarity index 93% rename from snow/engine/avalanche/vertex/test_storage.go rename to snow/engine/avalanche/vertex/vertextest/storage.go index 3e00dbdda879..5dc1314d9a91 100644 --- a/snow/engine/avalanche/vertex/test_storage.go +++ b/snow/engine/avalanche/vertex/vertextest/storage.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package vertex +package vertextest import ( "context" @@ -14,6 +12,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/avalanche" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" ) var ( @@ -21,7 +20,7 @@ var ( errEdge = errors.New("unexpectedly called Edge") errStopVertexAccepted = errors.New("unexpectedly called StopVertexAccepted") - _ Storage = (*TestStorage)(nil) + _ vertex.Storage = (*TestStorage)(nil) ) type TestStorage struct { diff --git a/snow/engine/avalanche/vertex/test_vm.go b/snow/engine/avalanche/vertex/vertextest/vm.go similarity index 83% rename from snow/engine/avalanche/vertex/test_vm.go rename to snow/engine/avalanche/vertex/vertextest/vm.go index 49948b81d516..416472cb51d8 100644 --- a/snow/engine/avalanche/vertex/test_vm.go +++ b/snow/engine/avalanche/vertex/vertextest/vm.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package vertex +package vertextest import ( "context" @@ -13,17 +11,18 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/snowstorm" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" ) var ( errLinearize = errors.New("unexpectedly called Linearize") - _ LinearizableVM = (*TestVM)(nil) + _ vertex.LinearizableVM = (*TestVM)(nil) ) type TestVM struct { - block.TestVM + blocktest.TestVM CantLinearize, CantParse bool diff --git a/snow/engine/common/test_bootstrap_tracker.go b/snow/engine/enginetest/bootstrap_tracker.go similarity index 98% rename from snow/engine/common/test_bootstrap_tracker.go rename to snow/engine/enginetest/bootstrap_tracker.go index 59aea61c5549..577b06300403 100644 --- a/snow/engine/common/test_bootstrap_tracker.go +++ b/snow/engine/enginetest/bootstrap_tracker.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package common +package enginetest import ( "testing" diff --git a/snow/engine/common/test_bootstrapper.go b/snow/engine/enginetest/bootstrapper.go similarity index 83% rename from snow/engine/common/test_bootstrapper.go rename to snow/engine/enginetest/bootstrapper.go index ae1aef57abdf..da9ae3641bf8 100644 --- a/snow/engine/common/test_bootstrapper.go +++ b/snow/engine/enginetest/bootstrapper.go @@ -1,19 +1,19 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package common +package enginetest import ( "context" "errors" "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/snow/engine/common" ) var ( - _ BootstrapableEngine = (*BootstrapperTest)(nil) + _ common.BootstrapableEngine = (*BootstrapperTest)(nil) errClear = errors.New("unexpectedly called Clear") ) diff --git a/snow/engine/common/test_engine.go b/snow/engine/enginetest/engine.go similarity index 97% rename from snow/engine/common/test_engine.go rename to snow/engine/enginetest/engine.go index 80470fa0509c..3cb9817d6880 100644 --- a/snow/engine/common/test_engine.go +++ b/snow/engine/enginetest/engine.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package common +package enginetest import ( "context" @@ -15,6 +13,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" ) @@ -47,7 +46,7 @@ var ( errChits = errors.New("unexpectedly called Chits") errStart = errors.New("unexpectedly called Start") - _ Engine = (*EngineTest)(nil) + _ common.Engine = (*EngineTest)(nil) ) // EngineTest is a test engine @@ -115,7 +114,7 @@ type EngineTest struct { ContextF func() *snow.ConsensusContext HaltF func(context.Context) TimeoutF, GossipF, ShutdownF func(context.Context) error - NotifyF func(context.Context, Message) error + NotifyF func(context.Context, common.Message) error GetF, GetAncestorsF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) error PullQueryF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID, requestedHeight uint64) error PutF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, container []byte) error @@ -127,20 +126,20 @@ type EngineTest struct { GetStateSummaryFrontierF, GetStateSummaryFrontierFailedF, GetAcceptedStateSummaryFailedF, GetAcceptedFrontierF, GetFailedF, GetAncestorsFailedF, QueryFailedF, GetAcceptedFrontierFailedF, GetAcceptedFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32) error - AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *AppError) error + AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error StateSummaryFrontierF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, summary []byte) error GetAcceptedStateSummaryF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, keys set.Set[uint64]) error AcceptedStateSummaryF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, summaryIDs set.Set[ids.ID]) error ConnectedF func(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error DisconnectedF func(ctx context.Context, nodeID ids.NodeID) error HealthF func(context.Context) (interface{}, error) - GetVMF func() VM + GetVMF func() common.VM AppRequestF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, msg []byte) error AppResponseF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, msg []byte) error AppGossipF func(ctx context.Context, nodeID ids.NodeID, msg []byte) error CrossChainAppRequestF func(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, msg []byte) error CrossChainAppResponseF func(ctx context.Context, chainID ids.ID, requestID uint32, msg []byte) error - CrossChainAppRequestFailedF func(ctx context.Context, chainID ids.ID, requestID uint32, appErr *AppError) error + CrossChainAppRequestFailedF func(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error } func (e *EngineTest) Default(cant bool) { @@ -265,7 +264,7 @@ func (e *EngineTest) Shutdown(ctx context.Context) error { return errShutdown } -func (e *EngineTest) Notify(ctx context.Context, msg Message) error { +func (e *EngineTest) Notify(ctx context.Context, msg common.Message) error { if e.NotifyF != nil { return e.NotifyF(ctx, msg) } @@ -564,7 +563,7 @@ func (e *EngineTest) CrossChainAppRequest(ctx context.Context, chainID ids.ID, r return errCrossChainAppRequest } -func (e *EngineTest) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *AppError) error { +func (e *EngineTest) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { if e.CrossChainAppRequestFailedF != nil { return e.CrossChainAppRequestFailedF(ctx, chainID, requestID, appErr) } @@ -616,7 +615,7 @@ func (e *EngineTest) AppResponse(ctx context.Context, nodeID ids.NodeID, request return errAppResponse } -func (e *EngineTest) AppRequestFailed(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *AppError) error { +func (e *EngineTest) AppRequestFailed(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error { if e.AppRequestFailedF != nil { return e.AppRequestFailedF(ctx, nodeID, requestID, appErr) } diff --git a/snow/engine/common/test_sender.go b/snow/engine/enginetest/sender.go similarity index 97% rename from snow/engine/common/test_sender.go rename to snow/engine/enginetest/sender.go index 9f4e5689751d..25c227969315 100644 --- a/snow/engine/common/test_sender.go +++ b/snow/engine/enginetest/sender.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package common +package enginetest import ( "context" @@ -12,12 +10,13 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/utils/set" ) var ( - _ Sender = (*SenderTest)(nil) - _ AppSender = (*FakeSender)(nil) + _ common.Sender = (*SenderTest)(nil) + _ common.AppSender = (*FakeSender)(nil) errSendAppRequest = errors.New("unexpectedly called SendAppRequest") errSendAppResponse = errors.New("unexpectedly called SendAppResponse") @@ -57,7 +56,7 @@ type SenderTest struct { SendAppRequestF func(context.Context, set.Set[ids.NodeID], uint32, []byte) error SendAppResponseF func(context.Context, ids.NodeID, uint32, []byte) error SendAppErrorF func(context.Context, ids.NodeID, uint32, int32, string) error - SendAppGossipF func(context.Context, SendConfig, []byte) error + SendAppGossipF func(context.Context, common.SendConfig, []byte) error SendCrossChainAppRequestF func(context.Context, ids.ID, uint32, []byte) SendCrossChainAppResponseF func(context.Context, ids.ID, uint32, []byte) SendCrossChainAppErrorF func(context.Context, ids.ID, uint32, int32, string) @@ -332,7 +331,7 @@ func (s *SenderTest) SendAppError(ctx context.Context, nodeID ids.NodeID, reques // initialized, then testing will fail. func (s *SenderTest) SendAppGossip( ctx context.Context, - config SendConfig, + config common.SendConfig, appGossipBytes []byte, ) error { switch { @@ -350,7 +349,7 @@ type FakeSender struct { SentAppGossip, SentCrossChainAppRequest, SentCrossChainAppResponse chan []byte - SentAppError, SentCrossChainAppError chan *AppError + SentAppError, SentCrossChainAppError chan *common.AppError } func (f FakeSender) SendAppRequest(_ context.Context, _ set.Set[ids.NodeID], _ uint32, bytes []byte) error { @@ -376,14 +375,14 @@ func (f FakeSender) SendAppError(_ context.Context, _ ids.NodeID, _ uint32, erro return nil } - f.SentAppError <- &AppError{ + f.SentAppError <- &common.AppError{ Code: errorCode, Message: errorMessage, } return nil } -func (f FakeSender) SendAppGossip(_ context.Context, _ SendConfig, bytes []byte) error { +func (f FakeSender) SendAppGossip(_ context.Context, _ common.SendConfig, bytes []byte) error { if f.SentAppGossip == nil { return nil } @@ -415,7 +414,7 @@ func (f FakeSender) SendCrossChainAppError(_ context.Context, _ ids.ID, _ uint32 return nil } - f.SentCrossChainAppError <- &AppError{ + f.SentCrossChainAppError <- &common.AppError{ Code: errorCode, Message: errorMessage, } diff --git a/snow/engine/common/test_timer.go b/snow/engine/enginetest/timer.go similarity index 85% rename from snow/engine/common/test_timer.go rename to snow/engine/enginetest/timer.go index c189dd15c237..f0bd1700dd66 100644 --- a/snow/engine/common/test_timer.go +++ b/snow/engine/enginetest/timer.go @@ -1,18 +1,18 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package common +package enginetest import ( "testing" "time" "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/snow/engine/common" ) -var _ Timer = (*TimerTest)(nil) +var _ common.Timer = (*TimerTest)(nil) // TimerTest is a test timer type TimerTest struct { diff --git a/snow/engine/common/test_vm.go b/snow/engine/enginetest/vm.go similarity index 93% rename from snow/engine/common/test_vm.go rename to snow/engine/enginetest/vm.go index bbad058e13ff..2dadf512fe92 100644 --- a/snow/engine/common/test_vm.go +++ b/snow/engine/enginetest/vm.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package common +package enginetest import ( "context" @@ -17,6 +15,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/version" ) @@ -37,7 +36,7 @@ var ( errCrossChainAppResponse = errors.New("unexpectedly called CrossChainAppResponse") errCrossChainAppRequestFailed = errors.New("unexpectedly called CrossChainAppRequestFailed") - _ VM = (*TestVM)(nil) + _ common.VM = (*TestVM)(nil) ) // TestVM is a test vm @@ -50,7 +49,7 @@ type TestVM struct { CantAppRequest, CantAppResponse, CantAppGossip, CantAppRequestFailed, CantCrossChainAppRequest, CantCrossChainAppResponse, CantCrossChainAppRequestFailed bool - InitializeF func(ctx context.Context, chainCtx *snow.Context, db database.Database, genesisBytes []byte, upgradeBytes []byte, configBytes []byte, msgChan chan<- Message, fxs []*Fx, appSender AppSender) error + InitializeF func(ctx context.Context, chainCtx *snow.Context, db database.Database, genesisBytes []byte, upgradeBytes []byte, configBytes []byte, msgChan chan<- common.Message, fxs []*common.Fx, appSender common.AppSender) error SetStateF func(ctx context.Context, state snow.State) error ShutdownF func(context.Context) error CreateHandlersF func(context.Context) (map[string]http.Handler, error) @@ -60,11 +59,11 @@ type TestVM struct { AppRequestF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, msg []byte) error AppResponseF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, msg []byte) error AppGossipF func(ctx context.Context, nodeID ids.NodeID, msg []byte) error - AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *AppError) error + AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error VersionF func(context.Context) (string, error) CrossChainAppRequestF func(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, msg []byte) error CrossChainAppResponseF func(ctx context.Context, chainID ids.ID, requestID uint32, msg []byte) error - CrossChainAppRequestFailedF func(ctx context.Context, chainID ids.ID, requestID uint32, appErr *AppError) error + CrossChainAppRequestFailedF func(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error } func (vm *TestVM) Default(cant bool) { @@ -92,9 +91,9 @@ func (vm *TestVM) Initialize( genesisBytes, upgradeBytes, configBytes []byte, - msgChan chan<- Message, - fxs []*Fx, - appSender AppSender, + msgChan chan<- common.Message, + fxs []*common.Fx, + appSender common.AppSender, ) error { if vm.InitializeF != nil { return vm.InitializeF( @@ -174,7 +173,7 @@ func (vm *TestVM) AppRequest(ctx context.Context, nodeID ids.NodeID, requestID u return errAppRequest } -func (vm *TestVM) AppRequestFailed(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *AppError) error { +func (vm *TestVM) AppRequestFailed(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error { if vm.AppRequestFailedF != nil { return vm.AppRequestFailedF(ctx, nodeID, requestID, appErr) } @@ -226,7 +225,7 @@ func (vm *TestVM) CrossChainAppRequest(ctx context.Context, chainID ids.ID, requ return errCrossChainAppRequest } -func (vm *TestVM) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *AppError) error { +func (vm *TestVM) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { if vm.CrossChainAppRequestFailedF != nil { return vm.CrossChainAppRequestFailedF(ctx, chainID, requestID, appErr) } diff --git a/snow/engine/snowman/block/batched_vm_test.go b/snow/engine/snowman/block/batched_vm_test.go index b4d251c284ba..86129d294084 100644 --- a/snow/engine/snowman/block/batched_vm_test.go +++ b/snow/engine/snowman/block/batched_vm_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package block +package block_test import ( "context" @@ -14,7 +14,10 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/snowman" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/utils/logging" + + . "github.com/ava-labs/avalanchego/snow/engine/snowman/block" ) var errTest = errors.New("non-nil error") @@ -22,7 +25,7 @@ var errTest = errors.New("non-nil error") func TestGetAncestorsDatabaseNotFound(t *testing.T) { require := require.New(t) - vm := &TestVM{} + vm := &blocktest.TestVM{} someID := ids.GenerateTestID() vm.GetBlockF = func(_ context.Context, id ids.ID) (snowman.Block, error) { require.Equal(someID, id) @@ -38,7 +41,7 @@ func TestGetAncestorsDatabaseNotFound(t *testing.T) { func TestGetAncestorsPropagatesErrors(t *testing.T) { require := require.New(t) - vm := &TestVM{} + vm := &blocktest.TestVM{} someID := ids.GenerateTestID() vm.GetBlockF = func(_ context.Context, id ids.ID) (snowman.Block, error) { require.Equal(someID, id) diff --git a/snow/engine/snowman/block/test_batched_vm.go b/snow/engine/snowman/block/blocktest/batched_vm.go similarity index 93% rename from snow/engine/snowman/block/test_batched_vm.go rename to snow/engine/snowman/block/blocktest/batched_vm.go index 92e766b86137..1513df481bb2 100644 --- a/snow/engine/snowman/block/test_batched_vm.go +++ b/snow/engine/snowman/block/blocktest/batched_vm.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package block +package blocktest import ( "context" @@ -15,13 +13,14 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/snowman" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block" ) var ( errGetAncestor = errors.New("unexpectedly called GetAncestor") errBatchedParseBlock = errors.New("unexpectedly called BatchedParseBlock") - _ BatchedChainVM = (*TestBatchedVM)(nil) + _ block.BatchedChainVM = (*TestBatchedVM)(nil) ) // TestBatchedVM is a BatchedVM that is useful for testing. diff --git a/snow/engine/snowman/block/test_state_summary.go b/snow/engine/snowman/block/blocktest/state_summary.go similarity index 69% rename from snow/engine/snowman/block/test_state_summary.go rename to snow/engine/snowman/block/blocktest/state_summary.go index 5921acb3e8dc..d410c19a38b7 100644 --- a/snow/engine/snowman/block/test_state_summary.go +++ b/snow/engine/snowman/block/blocktest/state_summary.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package block +package blocktest import ( "context" @@ -13,10 +11,11 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block" ) var ( - _ StateSummary = (*TestStateSummary)(nil) + _ block.StateSummary = (*TestStateSummary)(nil) errAccept = errors.New("unexpectedly called Accept") ) @@ -28,7 +27,7 @@ type TestStateSummary struct { T *testing.T CantAccept bool - AcceptF func(context.Context) (StateSyncMode, error) + AcceptF func(context.Context) (block.StateSyncMode, error) } func (s *TestStateSummary) ID() ids.ID { @@ -43,12 +42,12 @@ func (s *TestStateSummary) Bytes() []byte { return s.BytesV } -func (s *TestStateSummary) Accept(ctx context.Context) (StateSyncMode, error) { +func (s *TestStateSummary) Accept(ctx context.Context) (block.StateSyncMode, error) { if s.AcceptF != nil { return s.AcceptF(ctx) } if s.CantAccept && s.T != nil { require.FailNow(s.T, errAccept.Error()) } - return StateSyncSkipped, errAccept + return block.StateSyncSkipped, errAccept } diff --git a/snow/engine/snowman/block/test_state_syncable_vm.go b/snow/engine/snowman/block/blocktest/state_syncable_vm.go similarity index 81% rename from snow/engine/snowman/block/test_state_syncable_vm.go rename to snow/engine/snowman/block/blocktest/state_syncable_vm.go index 2bf5fe425941..66b28c374be5 100644 --- a/snow/engine/snowman/block/test_state_syncable_vm.go +++ b/snow/engine/snowman/block/blocktest/state_syncable_vm.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package block +package blocktest import ( "context" @@ -11,10 +9,12 @@ import ( "testing" "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/snow/engine/snowman/block" ) var ( - _ StateSyncableVM = (*TestStateSyncableVM)(nil) + _ block.StateSyncableVM = (*TestStateSyncableVM)(nil) errStateSyncEnabled = errors.New("unexpectedly called StateSyncEnabled") errStateSyncGetOngoingSummary = errors.New("unexpectedly called StateSyncGetOngoingSummary") @@ -33,10 +33,10 @@ type TestStateSyncableVM struct { CantGetStateSummary bool StateSyncEnabledF func(context.Context) (bool, error) - GetOngoingSyncStateSummaryF func(context.Context) (StateSummary, error) - GetLastStateSummaryF func(context.Context) (StateSummary, error) - ParseStateSummaryF func(ctx context.Context, summaryBytes []byte) (StateSummary, error) - GetStateSummaryF func(ctx context.Context, summaryHeight uint64) (StateSummary, error) + GetOngoingSyncStateSummaryF func(context.Context) (block.StateSummary, error) + GetLastStateSummaryF func(context.Context) (block.StateSummary, error) + ParseStateSummaryF func(ctx context.Context, summaryBytes []byte) (block.StateSummary, error) + GetStateSummaryF func(ctx context.Context, summaryHeight uint64) (block.StateSummary, error) } func (vm *TestStateSyncableVM) StateSyncEnabled(ctx context.Context) (bool, error) { @@ -49,7 +49,7 @@ func (vm *TestStateSyncableVM) StateSyncEnabled(ctx context.Context) (bool, erro return false, errStateSyncEnabled } -func (vm *TestStateSyncableVM) GetOngoingSyncStateSummary(ctx context.Context) (StateSummary, error) { +func (vm *TestStateSyncableVM) GetOngoingSyncStateSummary(ctx context.Context) (block.StateSummary, error) { if vm.GetOngoingSyncStateSummaryF != nil { return vm.GetOngoingSyncStateSummaryF(ctx) } @@ -59,7 +59,7 @@ func (vm *TestStateSyncableVM) GetOngoingSyncStateSummary(ctx context.Context) ( return nil, errStateSyncGetOngoingSummary } -func (vm *TestStateSyncableVM) GetLastStateSummary(ctx context.Context) (StateSummary, error) { +func (vm *TestStateSyncableVM) GetLastStateSummary(ctx context.Context) (block.StateSummary, error) { if vm.GetLastStateSummaryF != nil { return vm.GetLastStateSummaryF(ctx) } @@ -69,7 +69,7 @@ func (vm *TestStateSyncableVM) GetLastStateSummary(ctx context.Context) (StateSu return nil, errGetLastStateSummary } -func (vm *TestStateSyncableVM) ParseStateSummary(ctx context.Context, summaryBytes []byte) (StateSummary, error) { +func (vm *TestStateSyncableVM) ParseStateSummary(ctx context.Context, summaryBytes []byte) (block.StateSummary, error) { if vm.ParseStateSummaryF != nil { return vm.ParseStateSummaryF(ctx, summaryBytes) } @@ -79,7 +79,7 @@ func (vm *TestStateSyncableVM) ParseStateSummary(ctx context.Context, summaryByt return nil, errParseStateSummary } -func (vm *TestStateSyncableVM) GetStateSummary(ctx context.Context, summaryHeight uint64) (StateSummary, error) { +func (vm *TestStateSyncableVM) GetStateSummary(ctx context.Context, summaryHeight uint64) (block.StateSummary, error) { if vm.GetStateSummaryF != nil { return vm.GetStateSummaryF(ctx, summaryHeight) } diff --git a/snow/engine/snowman/block/test_vm.go b/snow/engine/snowman/block/blocktest/vm.go similarity index 94% rename from snow/engine/snowman/block/test_vm.go rename to snow/engine/snowman/block/blocktest/vm.go index cdbeabacc4f1..c12c617b0bcf 100644 --- a/snow/engine/snowman/block/test_vm.go +++ b/snow/engine/snowman/block/blocktest/vm.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package block +package blocktest import ( "context" @@ -13,7 +11,8 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/snowman" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block" ) var ( @@ -23,12 +22,12 @@ var ( errLastAccepted = errors.New("unexpectedly called LastAccepted") errGetBlockIDAtHeight = errors.New("unexpectedly called GetBlockIDAtHeight") - _ ChainVM = (*TestVM)(nil) + _ block.ChainVM = (*TestVM)(nil) ) // TestVM is a ChainVM that is useful for testing. type TestVM struct { - common.TestVM + enginetest.TestVM CantBuildBlock, CantParseBlock, diff --git a/snow/engine/snowman/bootstrap/bootstrapper_test.go b/snow/engine/snowman/bootstrap/bootstrapper_test.go index 6bccfdb58f95..25713771c8ed 100644 --- a/snow/engine/snowman/bootstrap/bootstrapper_test.go +++ b/snow/engine/snowman/bootstrap/bootstrapper_test.go @@ -20,9 +20,9 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" - "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/common/tracker" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/engine/snowman/bootstrap/interval" "github.com/ava-labs/avalanchego/snow/engine/snowman/getter" "github.com/ava-labs/avalanchego/snow/snowtest" @@ -35,7 +35,7 @@ import ( var errUnknownBlock = errors.New("unknown block") -func newConfig(t *testing.T) (Config, ids.NodeID, *common.SenderTest, *block.TestVM) { +func newConfig(t *testing.T) (Config, ids.NodeID, *enginetest.SenderTest, *blocktest.TestVM) { require := require.New(t) snowCtx := snowtest.Context(t, snowtest.CChainID) @@ -43,8 +43,8 @@ func newConfig(t *testing.T) (Config, ids.NodeID, *common.SenderTest, *block.Tes vdrs := validators.NewManager() - sender := &common.SenderTest{} - vm := &block.TestVM{} + sender := &enginetest.SenderTest{} + vm := &blocktest.TestVM{} sender.T = t vm.T = t @@ -53,7 +53,7 @@ func newConfig(t *testing.T) (Config, ids.NodeID, *common.SenderTest, *block.Tes vm.Default(true) isBootstrapped := false - bootstrapTracker := &common.BootstrapTrackerTest{ + bootstrapTracker := &enginetest.BootstrapTrackerTest{ T: t, IsBootstrappedF: func() bool { return isBootstrapped @@ -99,7 +99,7 @@ func newConfig(t *testing.T) (Config, ids.NodeID, *common.SenderTest, *block.Tes PeerTracker: peerTracker, Sender: sender, BootstrapTracker: bootstrapTracker, - Timer: &common.TimerTest{}, + Timer: &enginetest.TimerTest{}, AncestorsMaxContainersReceived: 2000, DB: memdb.New(), VM: vm, @@ -109,9 +109,9 @@ func newConfig(t *testing.T) (Config, ids.NodeID, *common.SenderTest, *block.Tes func TestBootstrapperStartsOnlyIfEnoughStakeIsConnected(t *testing.T) { require := require.New(t) - sender := &common.SenderTest{T: t} - vm := &block.TestVM{ - TestVM: common.TestVM{T: t}, + sender := &enginetest.SenderTest{T: t} + vm := &blocktest.TestVM{ + TestVM: enginetest.TestVM{T: t}, } sender.Default(true) @@ -147,8 +147,8 @@ func TestBootstrapperStartsOnlyIfEnoughStakeIsConnected(t *testing.T) { StartupTracker: startupTracker, PeerTracker: peerTracker, Sender: sender, - BootstrapTracker: &common.BootstrapTrackerTest{}, - Timer: &common.TimerTest{}, + BootstrapTracker: &enginetest.BootstrapTrackerTest{}, + Timer: &enginetest.TimerTest{}, AncestorsMaxContainersReceived: 2000, DB: memdb.New(), VM: vm, @@ -611,8 +611,8 @@ func TestBootstrapNoParseOnNew(t *testing.T) { ctx := snowtest.ConsensusContext(snowCtx) peers := validators.NewManager() - sender := &common.SenderTest{} - vm := &block.TestVM{} + sender := &enginetest.SenderTest{} + vm := &blocktest.TestVM{} sender.T = t vm.T = t @@ -621,7 +621,7 @@ func TestBootstrapNoParseOnNew(t *testing.T) { vm.Default(true) isBootstrapped := false - bootstrapTracker := &common.BootstrapTrackerTest{ + bootstrapTracker := &enginetest.BootstrapTrackerTest{ T: t, IsBootstrappedF: func() bool { return isBootstrapped @@ -680,7 +680,7 @@ func TestBootstrapNoParseOnNew(t *testing.T) { PeerTracker: peerTracker, Sender: sender, BootstrapTracker: bootstrapTracker, - Timer: &common.TimerTest{}, + Timer: &enginetest.TimerTest{}, AncestorsMaxContainersReceived: 2000, DB: intervalDB, VM: vm, @@ -773,7 +773,7 @@ func TestBootstrapperRollbackOnSetState(t *testing.T) { require.Equal(blks[0].HeightV, bs.startingHeight) } -func initializeVMWithBlockchain(vm *block.TestVM, blocks []*snowmantest.Block) { +func initializeVMWithBlockchain(vm *blocktest.TestVM, blocks []*snowmantest.Block) { vm.CantSetState = false vm.LastAcceptedF = snowmantest.MakeLastAcceptedBlockF( blocks, diff --git a/snow/engine/snowman/config_test.go b/snow/engine/snowman/config_test.go index 555a580442c1..7ee38616ca26 100644 --- a/snow/engine/snowman/config_test.go +++ b/snow/engine/snowman/config_test.go @@ -8,9 +8,9 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowball" "github.com/ava-labs/avalanchego/snow/consensus/snowman" - "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/common/tracker" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" ) @@ -20,8 +20,8 @@ func DefaultConfig(t testing.TB) Config { return Config{ Ctx: snowtest.ConsensusContext(ctx), - VM: &block.TestVM{}, - Sender: &common.SenderTest{}, + VM: &blocktest.TestVM{}, + Sender: &enginetest.SenderTest{}, Validators: validators.NewManager(), ConnectedValidators: tracker.NewPeers(), Params: snowball.Parameters{ diff --git a/snow/engine/snowman/engine_test.go b/snow/engine/snowman/engine_test.go index eaca5ab8220e..0d68577c5032 100644 --- a/snow/engine/snowman/engine_test.go +++ b/snow/engine/snowman/engine_test.go @@ -22,8 +22,9 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/ancestor" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/engine/snowman/getter" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" @@ -64,7 +65,7 @@ func MakeParseBlockF(blks ...[]*snowmantest.Block) func(context.Context, []byte) } } -func setup(t *testing.T, config Config) (ids.NodeID, validators.Manager, *common.SenderTest, *block.TestVM, *Engine) { +func setup(t *testing.T, config Config) (ids.NodeID, validators.Manager, *enginetest.SenderTest, *blocktest.TestVM, *Engine) { require := require.New(t) vdr := ids.GenerateTestNodeID() @@ -72,11 +73,11 @@ func setup(t *testing.T, config Config) (ids.NodeID, validators.Manager, *common require.NoError(config.ConnectedValidators.Connected(context.Background(), vdr, version.CurrentApp)) config.Validators.RegisterSetCallbackListener(config.Ctx.SubnetID, config.ConnectedValidators) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} config.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t config.VM = vm @@ -326,11 +327,11 @@ func TestEngineMultipleQuery(t *testing.T) { require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr1, nil, ids.Empty, 1)) require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr2, nil, ids.Empty, 1)) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t engCfg.VM = vm @@ -650,11 +651,11 @@ func TestVoteCanceling(t *testing.T) { require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr1, nil, ids.Empty, 1)) require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr2, nil, ids.Empty, 1)) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t engCfg.VM = vm @@ -719,11 +720,11 @@ func TestEngineNoQuery(t *testing.T) { engCfg := DefaultConfig(t) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t vm.LastAcceptedF = snowmantest.MakeLastAcceptedBlockF( []*snowmantest.Block{snowmantest.Genesis}, @@ -759,11 +760,11 @@ func TestEngineNoRepollQuery(t *testing.T) { engCfg := DefaultConfig(t) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t vm.LastAcceptedF = snowmantest.MakeLastAcceptedBlockF( []*snowmantest.Block{snowmantest.Genesis}, @@ -1400,11 +1401,11 @@ func TestEngineAggressivePolling(t *testing.T) { vdr := ids.GenerateTestNodeID() require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr, nil, ids.Empty, 1)) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t engCfg.VM = vm @@ -1487,12 +1488,12 @@ func TestEngineDoubleChit(t *testing.T) { require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr0, nil, ids.Empty, 1)) require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr1, nil, ids.Empty, 1)) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t engCfg.VM = vm @@ -1574,11 +1575,11 @@ func TestEngineBuildBlockLimit(t *testing.T) { vdr := ids.GenerateTestNodeID() require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr, nil, ids.Empty, 1)) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t engCfg.VM = vm @@ -2158,12 +2159,12 @@ func TestEngineApplyAcceptedFrontierInQueryFailed(t *testing.T) { vdr := ids.GenerateTestNodeID() require.NoError(vals.AddStaker(engCfg.Ctx.SubnetID, vdr, nil, ids.Empty, 1)) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t engCfg.VM = vm @@ -2252,12 +2253,12 @@ func TestEngineRepollsMisconfiguredSubnet(t *testing.T) { vals := validators.NewManager() engCfg.Validators = vals - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} engCfg.Sender = sender sender.Default(true) - vm := &block.TestVM{} + vm := &blocktest.TestVM{} vm.T = t engCfg.VM = vm @@ -2391,7 +2392,7 @@ func TestEngineVoteStallRegression(t *testing.T) { require.NoError(config.Validators.AddStaker(config.Ctx.SubnetID, nodeID1, nil, ids.Empty, 1)) require.NoError(config.Validators.AddStaker(config.Ctx.SubnetID, nodeID2, nil, ids.Empty, 1)) - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ T: t, SendChitsF: func(context.Context, ids.NodeID, uint32, ids.ID, ids.ID, ids.ID) {}, } @@ -2401,8 +2402,8 @@ func TestEngineVoteStallRegression(t *testing.T) { acceptedChain := snowmantest.BuildDescendants(snowmantest.Genesis, 3) rejectedChain := snowmantest.BuildDescendants(snowmantest.Genesis, 2) - vm := &block.TestVM{ - TestVM: common.TestVM{ + vm := &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, InitializeF: func( context.Context, @@ -2611,7 +2612,7 @@ func TestEngineEarlyTerminateVoterRegression(t *testing.T) { nodeID := ids.GenerateTestNodeID() require.NoError(config.Validators.AddStaker(config.Ctx.SubnetID, nodeID, nil, ids.Empty, 1)) - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ T: t, SendChitsF: func(context.Context, ids.NodeID, uint32, ids.ID, ids.ID, ids.ID) {}, } @@ -2619,8 +2620,8 @@ func TestEngineEarlyTerminateVoterRegression(t *testing.T) { config.Sender = sender chain := snowmantest.BuildDescendants(snowmantest.Genesis, 3) - vm := &block.TestVM{ - TestVM: common.TestVM{ + vm := &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, InitializeF: func( context.Context, @@ -2756,7 +2757,7 @@ func TestEngineRegistersInvalidVoterDependencyRegression(t *testing.T) { nodeID := ids.GenerateTestNodeID() require.NoError(config.Validators.AddStaker(config.Ctx.SubnetID, nodeID, nil, ids.Empty, 1)) - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ T: t, SendChitsF: func(context.Context, ids.NodeID, uint32, ids.ID, ids.ID, ids.ID) {}, } @@ -2769,8 +2770,8 @@ func TestEngineRegistersInvalidVoterDependencyRegression(t *testing.T) { ) rejectedChain[1].VerifyV = errInvalid - vm := &block.TestVM{ - TestVM: common.TestVM{ + vm := &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, InitializeF: func( context.Context, diff --git a/snow/engine/snowman/getter/getter_test.go b/snow/engine/snowman/getter/getter_test.go index 6d1324cb2a32..dbdd2a2f17f7 100644 --- a/snow/engine/snowman/getter/getter_test.go +++ b/snow/engine/snowman/getter/getter_test.go @@ -17,7 +17,9 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" ) @@ -25,19 +27,19 @@ import ( var errUnknownBlock = errors.New("unknown block") type StateSyncEnabledMock struct { - *block.TestVM + *blocktest.TestVM *block.MockStateSyncableVM } -func newTest(t *testing.T) (common.AllGetsServer, StateSyncEnabledMock, *common.SenderTest) { +func newTest(t *testing.T) (common.AllGetsServer, StateSyncEnabledMock, *enginetest.SenderTest) { ctrl := gomock.NewController(t) vm := StateSyncEnabledMock{ - TestVM: &block.TestVM{}, + TestVM: &blocktest.TestVM{}, MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), } - sender := &common.SenderTest{ + sender := &enginetest.SenderTest{ T: t, } sender.Default(true) diff --git a/snow/engine/snowman/syncer/state_syncer_test.go b/snow/engine/snowman/syncer/state_syncer_test.go index 2ee745bb5c64..54a4608dce79 100644 --- a/snow/engine/snowman/syncer/state_syncer_test.go +++ b/snow/engine/snowman/syncer/state_syncer_test.go @@ -18,7 +18,9 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/common/tracker" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/engine/snowman/getter" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/utils/logging" @@ -38,11 +40,11 @@ func TestStateSyncerIsEnabledIfVMSupportsStateSyncing(t *testing.T) { // Build state syncer snowCtx := snowtest.Context(t, snowtest.CChainID) ctx := snowtest.ConsensusContext(snowCtx) - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} // Non state syncableVM case - nonStateSyncableVM := &block.TestVM{ - TestVM: common.TestVM{T: t}, + nonStateSyncableVM := &blocktest.TestVM{ + TestVM: enginetest.TestVM{T: t}, } dummyGetter, err := getter.New( nonStateSyncableVM, @@ -66,10 +68,10 @@ func TestStateSyncerIsEnabledIfVMSupportsStateSyncing(t *testing.T) { // State syncableVM case fullVM := &fullVM{ - TestVM: &block.TestVM{ - TestVM: common.TestVM{T: t}, + TestVM: &blocktest.TestVM{ + TestVM: enginetest.TestVM{T: t}, }, - TestStateSyncableVM: &block.TestStateSyncableVM{ + TestStateSyncableVM: &blocktest.TestStateSyncableVM{ T: t, }, } @@ -164,7 +166,7 @@ func TestStateSyncLocalSummaryIsIncludedAmongFrontiersIfAvailable(t *testing.T) syncer, fullVM, _ := buildTestsObjects(t, ctx, startup, beacons, (totalWeight+1)/2) // mock VM to simulate a valid summary is returned - localSummary := &block.TestStateSummary{ + localSummary := &blocktest.TestStateSummary{ HeightV: 2000, IDV: summaryID, BytesV: summaryBytes, @@ -292,7 +294,7 @@ func TestUnRequestedStateSummaryFrontiersAreDropped(t *testing.T) { // mock VM to simulate a valid summary is returned fullVM.CantParseStateSummary = true fullVM.ParseStateSummaryF = func(_ context.Context, summaryBytes []byte) (block.StateSummary, error) { - return &block.TestStateSummary{ + return &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, @@ -478,7 +480,7 @@ func TestLateResponsesFromUnresponsiveFrontiersAreNotRecorded(t *testing.T) { // mock VM to simulate a valid but late summary is returned fullVM.CantParseStateSummary = true fullVM.ParseStateSummaryF = func(_ context.Context, summaryBytes []byte) (block.StateSummary, error) { - return &block.TestStateSummary{ + return &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, @@ -527,7 +529,7 @@ func TestStateSyncIsRestartedIfTooManyFrontierSeedersTimeout(t *testing.T) { fullVM.ParseStateSummaryF = func(_ context.Context, b []byte) (block.StateSummary, error) { switch { case bytes.Equal(b, summaryBytes): - return &block.TestStateSummary{ + return &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, @@ -615,7 +617,7 @@ func TestVoteRequestsAreSentAsAllFrontierBeaconsResponded(t *testing.T) { fullVM.CantParseStateSummary = true fullVM.ParseStateSummaryF = func(_ context.Context, b []byte) (block.StateSummary, error) { require.Equal(summaryBytes, b) - return &block.TestStateSummary{ + return &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, @@ -685,7 +687,7 @@ func TestUnRequestedVotesAreDropped(t *testing.T) { // mock VM to simulate a valid summary is returned fullVM.CantParseStateSummary = true fullVM.ParseStateSummaryF = func(_ context.Context, summaryBytes []byte) (block.StateSummary, error) { - return &block.TestStateSummary{ + return &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, @@ -802,7 +804,7 @@ func TestVotesForUnknownSummariesAreDropped(t *testing.T) { // mock VM to simulate a valid summary is returned fullVM.CantParseStateSummary = true fullVM.ParseStateSummaryF = func(_ context.Context, summaryBytes []byte) (block.StateSummary, error) { - return &block.TestStateSummary{ + return &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, @@ -904,13 +906,13 @@ func TestStateSummaryIsPassedToVMAsMajorityOfVotesIsCastedForIt(t *testing.T) { } // mock VM to simulate a valid summary is returned - summary := &block.TestStateSummary{ + summary := &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, T: t, } - minoritySummary := &block.TestStateSummary{ + minoritySummary := &blocktest.TestStateSummary{ HeightV: minorityKey, IDV: minoritySummaryID, BytesV: minoritySummaryBytes, @@ -1049,7 +1051,7 @@ func TestVotingIsRestartedIfMajorityIsNotReachedDueToTimeouts(t *testing.T) { } // mock VM to simulate a valid summary is returned - minoritySummary := &block.TestStateSummary{ + minoritySummary := &blocktest.TestStateSummary{ HeightV: minorityKey, IDV: minoritySummaryID, BytesV: minoritySummaryBytes, @@ -1155,13 +1157,13 @@ func TestStateSyncIsStoppedIfEnoughVotesAreCastedWithNoClearMajority(t *testing. } // mock VM to simulate a valid minoritySummary1 is returned - minoritySummary1 := &block.TestStateSummary{ + minoritySummary1 := &blocktest.TestStateSummary{ HeightV: key, IDV: summaryID, BytesV: summaryBytes, T: t, } - minoritySummary2 := &block.TestStateSummary{ + minoritySummary2 := &blocktest.TestStateSummary{ HeightV: minorityKey, IDV: minoritySummaryID, BytesV: minoritySummaryBytes, diff --git a/snow/engine/snowman/syncer/utils_test.go b/snow/engine/snowman/syncer/utils_test.go index a5217a4bf0dd..7a2ea5c28116 100644 --- a/snow/engine/snowman/syncer/utils_test.go +++ b/snow/engine/snowman/syncer/utils_test.go @@ -13,9 +13,10 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/common/tracker" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/engine/snowman/getter" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/hashing" @@ -53,8 +54,8 @@ func init() { } type fullVM struct { - *block.TestVM - *block.TestStateSyncableVM + *blocktest.TestVM + *blocktest.TestStateSyncableVM } func buildTestPeers(t *testing.T, subnetID ids.ID) validators.Manager { @@ -77,19 +78,19 @@ func buildTestsObjects( ) ( *stateSyncer, *fullVM, - *common.SenderTest, + *enginetest.SenderTest, ) { require := require.New(t) fullVM := &fullVM{ - TestVM: &block.TestVM{ - TestVM: common.TestVM{T: t}, + TestVM: &blocktest.TestVM{ + TestVM: enginetest.TestVM{T: t}, }, - TestStateSyncableVM: &block.TestStateSyncableVM{ + TestStateSyncableVM: &blocktest.TestStateSyncableVM{ T: t, }, } - sender := &common.SenderTest{T: t} + sender := &enginetest.SenderTest{T: t} dummyGetter, err := getter.New( fullVM, sender, diff --git a/snow/networking/benchlist/test_benchable.go b/snow/networking/benchlist/benchable_test.go similarity index 98% rename from snow/networking/benchlist/test_benchable.go rename to snow/networking/benchlist/benchable_test.go index 57a611a3765a..dabfab564829 100644 --- a/snow/networking/benchlist/test_benchable.go +++ b/snow/networking/benchlist/benchable_test.go @@ -1,8 +1,6 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - package benchlist import ( diff --git a/snow/networking/handler/handler_test.go b/snow/networking/handler/handler_test.go index 929c51780c24..3e145f39778a 100644 --- a/snow/networking/handler/handler_test.go +++ b/snow/networking/handler/handler_test.go @@ -19,6 +19,7 @@ import ( "github.com/ava-labs/avalanchego/network/p2p" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" @@ -82,8 +83,8 @@ func TestHandlerDropsTimedOutMessages(t *testing.T) { require.NoError(err) handler := handlerIntf.(*handler) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -194,8 +195,8 @@ func TestHandlerClosesOnError(t *testing.T) { closed <- struct{}{} }) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -207,7 +208,7 @@ func TestHandlerClosesOnError(t *testing.T) { return errFatal } - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(false) engine.ContextF = func() *snow.ConsensusContext { return ctx @@ -294,8 +295,8 @@ func TestHandlerDropsGossipDuringBootstrapping(t *testing.T) { handler.clock.Set(time.Now()) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -382,14 +383,14 @@ func TestHandlerDispatchInternal(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } bootstrapper.Default(false) - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(false) engine.ContextF = func() *snow.ConsensusContext { return ctx @@ -468,14 +469,14 @@ func TestHandlerSubnetConnector(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } bootstrapper.Default(false) - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(false) engine.ContextF = func() *snow.ConsensusContext { return ctx @@ -650,14 +651,14 @@ func TestDynamicEngineTypeDispatch(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } bootstrapper.Default(false) - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(false) engine.ContextF = func() *snow.ConsensusContext { return ctx diff --git a/snow/networking/handler/health_test.go b/snow/networking/handler/health_test.go index 789d3464187e..57c1b48b2f89 100644 --- a/snow/networking/handler/health_test.go +++ b/snow/networking/handler/health_test.go @@ -15,7 +15,7 @@ import ( "github.com/ava-labs/avalanchego/network/p2p" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowball" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" @@ -97,14 +97,14 @@ func TestHealthCheckSubnet(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } bootstrapper.Default(false) - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(false) engine.ContextF = func() *snow.ConsensusContext { return ctx diff --git a/snow/networking/router/chain_router_test.go b/snow/networking/router/chain_router_test.go index 7472de1fc016..f27931192200 100644 --- a/snow/networking/router/chain_router_test.go +++ b/snow/networking/router/chain_router_test.go @@ -18,6 +18,7 @@ import ( "github.com/ava-labs/avalanchego/network/p2p" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/networking/benchlist" "github.com/ava-labs/avalanchego/snow/networking/handler" "github.com/ava-labs/avalanchego/snow/networking/timeout" @@ -117,8 +118,8 @@ func TestShutdown(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -136,7 +137,7 @@ func TestShutdown(t *testing.T) { } bootstrapper.HaltF = func(context.Context) {} - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(true) engine.CantGossip = false engine.ContextF = func() *snow.ConsensusContext { @@ -243,7 +244,7 @@ func TestConnectedAfterShutdownErrorLogRegression(t *testing.T) { ) require.NoError(err) - engine := common.EngineTest{ + engine := enginetest.EngineTest{ T: t, StartF: func(context.Context, uint32) error { return nil @@ -262,7 +263,7 @@ func TestConnectedAfterShutdownErrorLogRegression(t *testing.T) { engine.Default(true) engine.CantGossip = false - bootstrapper := &common.BootstrapperTest{ + bootstrapper := &enginetest.BootstrapperTest{ EngineTest: engine, CantClear: true, } @@ -377,8 +378,8 @@ func TestShutdownTimesOut(t *testing.T) { require.NoError(err) bootstrapFinished := make(chan struct{}, 1) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -398,7 +399,7 @@ func TestShutdownTimesOut(t *testing.T) { return nil } - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(false) engine.ContextF = func() *snow.ConsensusContext { return ctx @@ -546,8 +547,8 @@ func TestRouterTimeout(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -1129,8 +1130,8 @@ func TestValidatorOnlyMessageDrops(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -1148,7 +1149,7 @@ func TestValidatorOnlyMessageDrops(t *testing.T) { State: snow.Bootstrapping, // assumed bootstrapping is ongoing }) - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.ContextF = func() *snow.ConsensusContext { return ctx } @@ -1410,8 +1411,8 @@ func TestValidatorOnlyAllowedNodeMessageDrops(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -1428,7 +1429,7 @@ func TestValidatorOnlyAllowedNodeMessageDrops(t *testing.T) { Type: engineType, State: snow.Bootstrapping, // assumed bootstrapping is ongoing }) - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.ContextF = func() *snow.ConsensusContext { return ctx } @@ -1679,7 +1680,7 @@ func TestCrossChainAppRequest(t *testing.T) { } } -func newChainRouterTest(t *testing.T) (*ChainRouter, *common.EngineTest) { +func newChainRouterTest(t *testing.T) (*ChainRouter, *enginetest.EngineTest) { // Create a timeout manager tm, err := timeout.NewManager( &timer.AdaptiveTimeoutConfig{ @@ -1750,8 +1751,8 @@ func newChainRouterTest(t *testing.T) (*ChainRouter, *common.EngineTest) { ) require.NoError(t, err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -1760,7 +1761,7 @@ func newChainRouterTest(t *testing.T) (*ChainRouter, *common.EngineTest) { return ctx } - engine := &common.EngineTest{T: t} + engine := &enginetest.EngineTest{T: t} engine.Default(false) engine.ContextF = func() *snow.ConsensusContext { return ctx diff --git a/snow/networking/sender/sender_test.go b/snow/networking/sender/sender_test.go index 34f138f6db21..c7b1f5530054 100644 --- a/snow/networking/sender/sender_test.go +++ b/snow/networking/sender/sender_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package sender +package sender_test import ( "context" @@ -19,9 +19,11 @@ import ( "github.com/ava-labs/avalanchego/network/p2p" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/networking/benchlist" "github.com/ava-labs/avalanchego/snow/networking/handler" "github.com/ava-labs/avalanchego/snow/networking/router" + "github.com/ava-labs/avalanchego/snow/networking/sender/sendertest" "github.com/ava-labs/avalanchego/snow/networking/timeout" "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/snow/snowtest" @@ -37,6 +39,8 @@ import ( p2ppb "github.com/ava-labs/avalanchego/proto/pb/p2p" commontracker "github.com/ava-labs/avalanchego/snow/engine/common/tracker" + + . "github.com/ava-labs/avalanchego/snow/networking/sender" ) const testThreadPoolSize = 2 @@ -88,7 +92,7 @@ func TestTimeout(t *testing.T) { prometheus.NewRegistry(), )) - externalSender := &ExternalSenderTest{TB: t} + externalSender := &sendertest.ExternalSenderTest{TB: t} externalSender.Default(false) sender, err := New( @@ -136,8 +140,8 @@ func TestTimeout(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -365,7 +369,7 @@ func TestReliableMessages(t *testing.T) { prometheus.NewRegistry(), )) - externalSender := &ExternalSenderTest{TB: t} + externalSender := &sendertest.ExternalSenderTest{TB: t} externalSender.Default(false) sender, err := New( @@ -413,8 +417,8 @@ func TestReliableMessages(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } @@ -522,7 +526,7 @@ func TestReliableMessagesToMyself(t *testing.T) { prometheus.NewRegistry(), )) - externalSender := &ExternalSenderTest{TB: t} + externalSender := &sendertest.ExternalSenderTest{TB: t} externalSender.Default(false) sender, err := New( @@ -570,8 +574,8 @@ func TestReliableMessagesToMyself(t *testing.T) { ) require.NoError(err) - bootstrapper := &common.BootstrapperTest{ - EngineTest: common.EngineTest{ + bootstrapper := &enginetest.BootstrapperTest{ + EngineTest: enginetest.EngineTest{ T: t, }, } diff --git a/snow/networking/sender/test_external_sender.go b/snow/networking/sender/sendertest/external.go similarity index 89% rename from snow/networking/sender/test_external_sender.go rename to snow/networking/sender/sendertest/external.go index da91edb54db1..56e5d37f31aa 100644 --- a/snow/networking/sender/test_external_sender.go +++ b/snow/networking/sender/sendertest/external.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package sender +package sendertest import ( "errors" @@ -12,12 +10,13 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/message" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/networking/sender" "github.com/ava-labs/avalanchego/subnets" "github.com/ava-labs/avalanchego/utils/set" ) var ( - _ ExternalSender = (*ExternalSenderTest)(nil) + _ sender.ExternalSender = (*ExternalSenderTest)(nil) errSend = errors.New("unexpectedly called Send") ) diff --git a/snow/snowtest/context.go b/snow/snowtest/context.go index 3cacc8e873bf..65e1eb87cc74 100644 --- a/snow/snowtest/context.go +++ b/snow/snowtest/context.go @@ -14,7 +14,7 @@ import ( "github.com/ava-labs/avalanchego/api/metrics" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/logging" @@ -63,7 +63,7 @@ func Context(tb testing.TB, chainID ids.ID) *snow.Context { require.NoError(aliaser.Alias(CChainID, "C")) require.NoError(aliaser.Alias(CChainID, CChainID.String())) - validatorState := &validators.TestState{ + validatorState := &validatorstest.TestState{ GetSubnetIDF: func(_ context.Context, chainID ids.ID) (ids.ID, error) { subnetID, ok := map[ids.ID]ids.ID{ constants.PlatformChainID: constants.PrimaryNetworkID, diff --git a/snow/validators/test_state.go b/snow/validators/validatorstest/state.go similarity index 89% rename from snow/validators/test_state.go rename to snow/validators/validatorstest/state.go index 378f3e8a8780..bc6cef2c667a 100644 --- a/snow/validators/test_state.go +++ b/snow/validators/validatorstest/state.go @@ -1,10 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -// TODO: https://github.com/ava-labs/avalanchego/issues/3174 -//go:build test || !test - -package validators +package validatorstest import ( "context" @@ -14,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/validators" ) var ( @@ -23,7 +21,7 @@ var ( errGetValidatorSet = errors.New("unexpectedly called GetValidatorSet") ) -var _ State = (*TestState)(nil) +var _ validators.State = (*TestState)(nil) type TestState struct { T testing.TB @@ -36,7 +34,7 @@ type TestState struct { GetMinimumHeightF func(ctx context.Context) (uint64, error) GetCurrentHeightF func(ctx context.Context) (uint64, error) GetSubnetIDF func(ctx context.Context, chainID ids.ID) (ids.ID, error) - GetValidatorSetF func(ctx context.Context, height uint64, subnetID ids.ID) (map[ids.NodeID]*GetValidatorOutput, error) + GetValidatorSetF func(ctx context.Context, height uint64, subnetID ids.ID) (map[ids.NodeID]*validators.GetValidatorOutput, error) } func (vm *TestState) GetMinimumHeight(ctx context.Context) (uint64, error) { @@ -73,7 +71,7 @@ func (vm *TestState) GetValidatorSet( ctx context.Context, height uint64, subnetID ids.ID, -) (map[ids.NodeID]*GetValidatorOutput, error) { +) (map[ids.NodeID]*validators.GetValidatorOutput, error) { if vm.GetValidatorSetF != nil { return vm.GetValidatorSetF(ctx, height, subnetID) } diff --git a/vms/avm/environment_test.go b/vms/avm/environment_test.go index ad4eff1aa1ba..32db5ae00fd1 100644 --- a/vms/avm/environment_test.go +++ b/vms/avm/environment_test.go @@ -19,6 +19,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/constants" @@ -192,7 +193,7 @@ func setup(tb testing.TB, c *envConfig) *environment { }, c.additionalFxs..., ), - &common.SenderTest{}, + &enginetest.SenderTest{}, )) stopVertexID := ids.GenerateTestID() diff --git a/vms/avm/network/network_test.go b/vms/avm/network/network_test.go index bdcfbda6a136..9313209113eb 100644 --- a/vms/avm/network/network_test.go +++ b/vms/avm/network/network_test.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/avm/block/executor" "github.com/ava-labs/avalanchego/vms/avm/fxs" @@ -178,7 +179,7 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { logging.NoLog{}, ids.EmptyNodeID, ids.Empty, - &validators.TestState{ + &validatorstest.TestState{ GetCurrentHeightF: func(context.Context) (uint64, error) { return 0, nil }, @@ -272,7 +273,7 @@ func TestNetworkIssueTxFromRPCWithoutVerification(t *testing.T) { logging.NoLog{}, ids.EmptyNodeID, ids.Empty, - &validators.TestState{ + &validatorstest.TestState{ GetCurrentHeightF: func(context.Context) (uint64, error) { return 0, nil }, diff --git a/vms/platformvm/block/builder/helpers_test.go b/vms/platformvm/block/builder/helpers_test.go index 9b1954ebefea..7b3575e237e2 100644 --- a/vms/platformvm/block/builder/helpers_test.go +++ b/vms/platformvm/block/builder/helpers_test.go @@ -22,6 +22,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" @@ -107,7 +108,7 @@ type environment struct { blkManager blockexecutor.Manager mempool mempool.Mempool network *network.Network - sender *common.SenderTest + sender *enginetest.SenderTest isBootstrapped *utils.Atomic[bool] config *config.Config @@ -168,7 +169,7 @@ func newEnvironment(t *testing.T, f fork) *environment { //nolint:unparam } registerer := prometheus.NewRegistry() - res.sender = &common.SenderTest{T: t} + res.sender = &enginetest.SenderTest{T: t} res.sender.SendAppGossipF = func(context.Context, common.SendConfig, []byte) error { return nil } diff --git a/vms/platformvm/block/executor/helpers_test.go b/vms/platformvm/block/executor/helpers_test.go index 33470fecf9fc..d8c3b6bf510b 100644 --- a/vms/platformvm/block/executor/helpers_test.go +++ b/vms/platformvm/block/executor/helpers_test.go @@ -23,7 +23,7 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" @@ -120,7 +120,7 @@ type test struct { type environment struct { blkManager Manager mempool mempool.Mempool - sender *common.SenderTest + sender *enginetest.SenderTest isBootstrapped *utils.Atomic[bool] config *config.Config @@ -192,7 +192,7 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f fork) *environment } registerer := prometheus.NewRegistry() - res.sender = &common.SenderTest{T: t} + res.sender = &enginetest.SenderTest{T: t} metrics := metrics.Noop diff --git a/vms/platformvm/validator_set_property_test.go b/vms/platformvm/validator_set_property_test.go index e55bca434180..9149d4023b7d 100644 --- a/vms/platformvm/validator_set_property_test.go +++ b/vms/platformvm/validator_set_property_test.go @@ -25,6 +25,7 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" @@ -684,7 +685,7 @@ func buildVM(t *testing.T) (*VM, ids.ID, error) { ctx.Lock.Lock() defer ctx.Lock.Unlock() - appSender := &common.SenderTest{} + appSender := &enginetest.SenderTest{} appSender.CantSendAppGossip = true appSender.SendAppGossipF = func(context.Context, common.SendConfig, []byte) error { return nil diff --git a/vms/platformvm/vm_test.go b/vms/platformvm/vm_test.go index ab2bcb430463..11b0ebd38214 100644 --- a/vms/platformvm/vm_test.go +++ b/vms/platformvm/vm_test.go @@ -24,11 +24,13 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowball" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/common/tracker" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/bootstrap" "github.com/ava-labs/avalanchego/snow/networking/benchlist" "github.com/ava-labs/avalanchego/snow/networking/handler" "github.com/ava-labs/avalanchego/snow/networking/router" "github.com/ava-labs/avalanchego/snow/networking/sender" + "github.com/ava-labs/avalanchego/snow/networking/sender/sendertest" "github.com/ava-labs/avalanchego/snow/networking/timeout" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" @@ -285,7 +287,7 @@ func defaultVM(t *testing.T, f fork) (*VM, *txstest.WalletFactory, database.Data ctx.Lock.Lock() defer ctx.Lock.Unlock() _, genesisBytes := defaultGenesis(t, ctx.AVAXAssetID) - appSender := &common.SenderTest{} + appSender := &enginetest.SenderTest{} appSender.CantSendAppGossip = true appSender.SendAppGossipF = func(context.Context, common.SendConfig, []byte) error { return nil @@ -1459,7 +1461,7 @@ func TestBootstrapPartiallyAccepted(t *testing.T) { prometheus.NewRegistry(), )) - externalSender := &sender.ExternalSenderTest{TB: t} + externalSender := &sendertest.ExternalSenderTest{TB: t} externalSender.Default(true) // Passes messages from the consensus engine to the network @@ -1476,7 +1478,7 @@ func TestBootstrapPartiallyAccepted(t *testing.T) { require.NoError(err) isBootstrapped := false - bootstrapTracker := &common.BootstrapTrackerTest{ + bootstrapTracker := &enginetest.BootstrapTrackerTest{ T: t, IsBootstrappedF: func() bool { return isBootstrapped @@ -2028,7 +2030,7 @@ func TestUptimeDisallowedAfterNeverConnecting(t *testing.T) { ctx.SharedMemory = m.NewSharedMemory(ctx.ChainID) msgChan := make(chan common.Message, 1) - appSender := &common.SenderTest{T: t} + appSender := &enginetest.SenderTest{T: t} require.NoError(vm.Initialize( context.Background(), ctx, diff --git a/vms/platformvm/warp/gwarp/signer_test.go b/vms/platformvm/warp/gwarp/signer_test.go index 31c7b3e993d4..1f4674db4b48 100644 --- a/vms/platformvm/warp/gwarp/signer_test.go +++ b/vms/platformvm/warp/gwarp/signer_test.go @@ -12,6 +12,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/vms/platformvm/warp" + "github.com/ava-labs/avalanchego/vms/platformvm/warp/signertest" "github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils" pb "github.com/ava-labs/avalanchego/proto/pb/warp" @@ -65,7 +66,7 @@ func setupSigner(t testing.TB) *testSigner { } func TestInterface(t *testing.T) { - for name, test := range warp.SignerTests { + for name, test := range signertest.SignerTests { t.Run(name, func(t *testing.T) { s := setupSigner(t) test(t, s.client, s.sk, s.networkID, s.chainID) diff --git a/vms/platformvm/warp/signer_test.go b/vms/platformvm/warp/signer_test.go index 84b51f6574fa..af618e766641 100644 --- a/vms/platformvm/warp/signer_test.go +++ b/vms/platformvm/warp/signer_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package warp +package warp_test import ( "testing" @@ -11,16 +11,18 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/vms/platformvm/warp" + "github.com/ava-labs/avalanchego/vms/platformvm/warp/signertest" ) func TestSigner(t *testing.T) { - for name, test := range SignerTests { + for name, test := range signertest.SignerTests { t.Run(name, func(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(t, err) chainID := ids.GenerateTestID() - s := NewSigner(sk, constants.UnitTestID, chainID) + s := warp.NewSigner(sk, constants.UnitTestID, chainID) test(t, s, sk, constants.UnitTestID, chainID) }) diff --git a/vms/platformvm/warp/test_signer.go b/vms/platformvm/warp/signertest/signertest.go similarity index 71% rename from vms/platformvm/warp/test_signer.go rename to vms/platformvm/warp/signertest/signertest.go index 3cd3802af3f9..24df8b1af7e0 100644 --- a/vms/platformvm/warp/test_signer.go +++ b/vms/platformvm/warp/signertest/signertest.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package warp +package signertest import ( "testing" @@ -13,20 +11,21 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/vms/platformvm/warp" ) // SignerTests is a list of all signer tests -var SignerTests = map[string]func(t *testing.T, s Signer, sk *bls.SecretKey, networkID uint32, chainID ids.ID){ +var SignerTests = map[string]func(t *testing.T, s warp.Signer, sk *bls.SecretKey, networkID uint32, chainID ids.ID){ "WrongChainID": TestWrongChainID, "WrongNetworkID": TestWrongNetworkID, "Verifies": TestVerifies, } // Test that using a random SourceChainID results in an error -func TestWrongChainID(t *testing.T, s Signer, _ *bls.SecretKey, _ uint32, _ ids.ID) { +func TestWrongChainID(t *testing.T, s warp.Signer, _ *bls.SecretKey, _ uint32, _ ids.ID) { require := require.New(t) - msg, err := NewUnsignedMessage( + msg, err := warp.NewUnsignedMessage( constants.UnitTestID, ids.GenerateTestID(), []byte("payload"), @@ -39,10 +38,10 @@ func TestWrongChainID(t *testing.T, s Signer, _ *bls.SecretKey, _ uint32, _ ids. } // Test that using a different networkID results in an error -func TestWrongNetworkID(t *testing.T, s Signer, _ *bls.SecretKey, networkID uint32, blockchainID ids.ID) { +func TestWrongNetworkID(t *testing.T, s warp.Signer, _ *bls.SecretKey, networkID uint32, blockchainID ids.ID) { require := require.New(t) - msg, err := NewUnsignedMessage( + msg, err := warp.NewUnsignedMessage( networkID+1, blockchainID, []byte("payload"), @@ -55,10 +54,10 @@ func TestWrongNetworkID(t *testing.T, s Signer, _ *bls.SecretKey, networkID uint } // Test that a signature generated with the signer verifies correctly -func TestVerifies(t *testing.T, s Signer, sk *bls.SecretKey, networkID uint32, chainID ids.ID) { +func TestVerifies(t *testing.T, s warp.Signer, sk *bls.SecretKey, networkID uint32, chainID ids.ID) { require := require.New(t) - msg, err := NewUnsignedMessage( + msg, err := warp.NewUnsignedMessage( networkID, chainID, []byte("payload"), diff --git a/vms/platformvm/warp/validator_test.go b/vms/platformvm/warp/validator_test.go index 7d14ed252616..be918f339c74 100644 --- a/vms/platformvm/warp/validator_test.go +++ b/vms/platformvm/warp/validator_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/set" ) @@ -329,7 +330,7 @@ func BenchmarkGetCanonicalValidatorSet(b *testing.B) { validator := getValidatorOutputs[i] getValidatorsOutput[validator.NodeID] = validator } - validatorState := &validators.TestState{ + validatorState := &validatorstest.TestState{ GetValidatorSetF: func(context.Context, uint64, ids.ID) (map[ids.NodeID]*validators.GetValidatorOutput, error) { return getValidatorsOutput, nil }, diff --git a/vms/proposervm/batched_vm_test.go b/vms/proposervm/batched_vm_test.go index dc4d8d3ac616..c61c6678842c 100644 --- a/vms/proposervm/batched_vm_test.go +++ b/vms/proposervm/batched_vm_test.go @@ -23,8 +23,10 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/staking" "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -598,7 +600,7 @@ func TestBatchedParseBlockParallel(t *testing.T) { vm := VM{ ctx: &snow.Context{ChainID: chainID}, - ChainVM: &block.TestVM{ + ChainVM: &blocktest.TestVM{ ParseBlockF: func(_ context.Context, rawBlock []byte) (snowman.Block, error) { return &snowmantest.Block{BytesV: rawBlock}, nil }, @@ -907,8 +909,8 @@ func TestBatchedParseBlockAtSnomanPlusPlusFork(t *testing.T) { } type TestRemoteProposerVM struct { - *block.TestBatchedVM - *block.TestVM + *blocktest.TestBatchedVM + *blocktest.TestVM } func initTestRemoteProposerVM( @@ -923,8 +925,8 @@ func initTestRemoteProposerVM( initialState := []byte("genesis state") coreVM := TestRemoteProposerVM{ - TestVM: &block.TestVM{}, - TestBatchedVM: &block.TestBatchedVM{}, + TestVM: &blocktest.TestVM{}, + TestBatchedVM: &blocktest.TestBatchedVM{}, } coreVM.TestVM.T = t coreVM.TestBatchedVM.T = t @@ -978,7 +980,7 @@ func initTestRemoteProposerVM( }, ) - valState := &validators.TestState{ + valState := &validatorstest.TestState{ T: t, } valState.GetMinimumHeightF = func(context.Context) (uint64, error) { diff --git a/vms/proposervm/proposer/windower_test.go b/vms/proposervm/proposer/windower_test.go index 1a77760af3cf..ea426b916475 100644 --- a/vms/proposervm/proposer/windower_test.go +++ b/vms/proposervm/proposer/windower_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" safemath "github.com/ava-labs/avalanchego/utils/math" ) @@ -57,7 +58,7 @@ func TestWindowerRepeatedValidator(t *testing.T) { nonValidatorID = ids.GenerateTestNodeID() ) - vdrState := &validators.TestState{ + vdrState := &validatorstest.TestState{ T: t, GetValidatorSetF: func(context.Context, uint64, ids.ID) (map[ids.NodeID]*validators.GetValidatorOutput, error) { return map[ids.NodeID]*validators.GetValidatorOutput{ @@ -444,13 +445,13 @@ func TestProposerDistribution(t *testing.T) { require.Less(maxSTDDeviation, 3.) } -func makeValidators(t testing.TB, count int) ([]ids.NodeID, *validators.TestState) { +func makeValidators(t testing.TB, count int) ([]ids.NodeID, *validatorstest.TestState) { validatorIDs := make([]ids.NodeID, count) for i := range validatorIDs { validatorIDs[i] = ids.BuildTestNodeID([]byte{byte(i) + 1}) } - vdrState := &validators.TestState{ + vdrState := &validatorstest.TestState{ T: t, GetValidatorSetF: func(context.Context, uint64, ids.ID) (map[ids.NodeID]*validators.GetValidatorOutput, error) { vdrs := make(map[ids.NodeID]*validators.GetValidatorOutput, MaxVerifyWindows) diff --git a/vms/proposervm/state_syncable_vm_test.go b/vms/proposervm/state_syncable_vm_test.go index 5c4810f9d144..9ef4dc3066f5 100644 --- a/vms/proposervm/state_syncable_vm_test.go +++ b/vms/proposervm/state_syncable_vm_test.go @@ -19,7 +19,9 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/vms/proposervm/summary" @@ -31,12 +33,12 @@ func helperBuildStateSyncTestObjects(t *testing.T) (*fullVM, *VM) { require := require.New(t) innerVM := &fullVM{ - TestVM: &block.TestVM{ - TestVM: common.TestVM{ + TestVM: &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, }, }, - TestStateSyncableVM: &block.TestStateSyncableVM{ + TestStateSyncableVM: &blocktest.TestStateSyncableVM{ T: t, }, } @@ -123,7 +125,7 @@ func TestStateSyncGetOngoingSyncStateSummary(t *testing.T) { require.NoError(vm.Shutdown(context.Background())) }() - innerSummary := &block.TestStateSummary{ + innerSummary := &blocktest.TestStateSummary{ IDV: ids.ID{'s', 'u', 'm', 'm', 'a', 'r', 'y', 'I', 'D'}, HeightV: uint64(2022), BytesV: []byte{'i', 'n', 'n', 'e', 'r'}, @@ -206,7 +208,7 @@ func TestStateSyncGetLastStateSummary(t *testing.T) { require.NoError(vm.Shutdown(context.Background())) }() - innerSummary := &block.TestStateSummary{ + innerSummary := &blocktest.TestStateSummary{ IDV: ids.ID{'s', 'u', 'm', 'm', 'a', 'r', 'y', 'I', 'D'}, HeightV: uint64(2022), BytesV: []byte{'i', 'n', 'n', 'e', 'r'}, @@ -290,7 +292,7 @@ func TestStateSyncGetStateSummary(t *testing.T) { }() reqHeight := uint64(1969) - innerSummary := &block.TestStateSummary{ + innerSummary := &blocktest.TestStateSummary{ IDV: ids.ID{'s', 'u', 'm', 'm', 'a', 'r', 'y', 'I', 'D'}, HeightV: reqHeight, BytesV: []byte{'i', 'n', 'n', 'e', 'r'}, @@ -375,7 +377,7 @@ func TestParseStateSummary(t *testing.T) { }() reqHeight := uint64(1969) - innerSummary := &block.TestStateSummary{ + innerSummary := &blocktest.TestStateSummary{ IDV: ids.ID{'s', 'u', 'm', 'm', 'a', 'r', 'y', 'I', 'D'}, HeightV: reqHeight, BytesV: []byte{'i', 'n', 'n', 'e', 'r'}, @@ -452,7 +454,7 @@ func TestStateSummaryAccept(t *testing.T) { }() reqHeight := uint64(1969) - innerSummary := &block.TestStateSummary{ + innerSummary := &blocktest.TestStateSummary{ IDV: ids.ID{'s', 'u', 'm', 'm', 'a', 'r', 'y', 'I', 'D'}, HeightV: reqHeight, BytesV: []byte{'i', 'n', 'n', 'e', 'r'}, @@ -519,7 +521,7 @@ func TestStateSummaryAcceptOlderBlock(t *testing.T) { }() reqHeight := uint64(1969) - innerSummary := &block.TestStateSummary{ + innerSummary := &blocktest.TestStateSummary{ IDV: ids.ID{'s', 'u', 'm', 'm', 'a', 'r', 'y', 'I', 'D'}, HeightV: reqHeight, BytesV: []byte{'i', 'n', 'n', 'e', 'r'}, diff --git a/vms/proposervm/vm_test.go b/vms/proposervm/vm_test.go index 9c6a786706a1..1b676d67e903 100644 --- a/vms/proposervm/vm_test.go +++ b/vms/proposervm/vm_test.go @@ -24,9 +24,12 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/staking" "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils" @@ -43,8 +46,8 @@ var ( ) type fullVM struct { - *block.TestVM - *block.TestStateSyncableVM + *blocktest.TestVM + *blocktest.TestStateSyncableVM } var ( @@ -79,7 +82,7 @@ func initTestProposerVM( minPChainHeight uint64, ) ( *fullVM, - *validators.TestState, + *validatorstest.TestState, *VM, database.Database, ) { @@ -87,12 +90,12 @@ func initTestProposerVM( initialState := []byte("genesis state") coreVM := &fullVM{ - TestVM: &block.TestVM{ - TestVM: common.TestVM{ + TestVM: &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, }, }, - TestStateSyncableVM: &block.TestStateSyncableVM{ + TestStateSyncableVM: &blocktest.TestStateSyncableVM{ T: t, }, } @@ -139,7 +142,7 @@ func initTestProposerVM( }, ) - valState := &validators.TestState{ + valState := &validatorstest.TestState{ T: t, } valState.GetMinimumHeightF = func(context.Context) (uint64, error) { @@ -779,7 +782,7 @@ func TestPreFork_SetPreference(t *testing.T) { func TestExpiredBuildBlock(t *testing.T) { require := require.New(t) - coreVM := &block.TestVM{} + coreVM := &blocktest.TestVM{} coreVM.T = t coreVM.LastAcceptedF = snowmantest.MakeLastAcceptedBlockF( @@ -818,7 +821,7 @@ func TestExpiredBuildBlock(t *testing.T) { }, ) - valState := &validators.TestState{ + valState := &validatorstest.TestState{ T: t, } valState.GetMinimumHeightF = func(context.Context) (uint64, error) { @@ -1062,7 +1065,7 @@ func TestInnerBlockDeduplication(t *testing.T) { func TestInnerVMRollback(t *testing.T) { require := require.New(t) - valState := &validators.TestState{ + valState := &validatorstest.TestState{ T: t, GetCurrentHeightF: func(context.Context) (uint64, error) { return defaultPChainHeight, nil @@ -1078,8 +1081,8 @@ func TestInnerVMRollback(t *testing.T) { }, } - coreVM := &block.TestVM{ - TestVM: common.TestVM{ + coreVM := &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, InitializeF: func( context.Context, @@ -1556,8 +1559,8 @@ func TestRejectedHeightNotIndexed(t *testing.T) { coreHeights := []ids.ID{snowmantest.GenesisID} initialState := []byte("genesis state") - coreVM := &block.TestVM{ - TestVM: common.TestVM{ + coreVM := &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, }, GetBlockIDAtHeightF: func(_ context.Context, height uint64) (ids.ID, error) { @@ -1610,7 +1613,7 @@ func TestRejectedHeightNotIndexed(t *testing.T) { }, ) - valState := &validators.TestState{ + valState := &validatorstest.TestState{ T: t, } valState.GetMinimumHeightF = func(context.Context) (uint64, error) { @@ -1729,8 +1732,8 @@ func TestRejectedOptionHeightNotIndexed(t *testing.T) { coreHeights := []ids.ID{snowmantest.GenesisID} initialState := []byte("genesis state") - coreVM := &block.TestVM{ - TestVM: common.TestVM{ + coreVM := &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, }, GetBlockIDAtHeightF: func(_ context.Context, height uint64) (ids.ID, error) { @@ -1783,7 +1786,7 @@ func TestRejectedOptionHeightNotIndexed(t *testing.T) { }, ) - valState := &validators.TestState{ + valState := &validatorstest.TestState{ T: t, } valState.GetMinimumHeightF = func(context.Context) (uint64, error) { @@ -2168,8 +2171,8 @@ func TestHistoricalBlockDeletion(t *testing.T) { currentHeight := uint64(0) initialState := []byte("genesis state") - coreVM := &block.TestVM{ - TestVM: common.TestVM{ + coreVM := &blocktest.TestVM{ + TestVM: enginetest.TestVM{ T: t, InitializeF: func(context.Context, *snow.Context, database.Database, []byte, []byte, []byte, chan<- common.Message, []*common.Fx, common.AppSender) error { return nil @@ -2204,7 +2207,7 @@ func TestHistoricalBlockDeletion(t *testing.T) { ctx := snowtest.Context(t, snowtest.CChainID) ctx.NodeID = ids.NodeIDFromCert(pTestCert) - ctx.ValidatorState = &validators.TestState{ + ctx.ValidatorState = &validatorstest.TestState{ T: t, GetMinimumHeightF: func(context.Context) (uint64, error) { return snowmantest.GenesisHeight, nil @@ -2479,7 +2482,7 @@ func TestGetPostDurangoSlotTimeWithNoValidators(t *testing.T) { } func TestLocalParse(t *testing.T) { - innerVM := &block.TestVM{ + innerVM := &blocktest.TestVM{ ParseBlockF: func(_ context.Context, rawBlock []byte) (snowman.Block, error) { return &snowmantest.Block{BytesV: rawBlock}, nil }, diff --git a/vms/rpcchainvm/state_syncable_vm_test.go b/vms/rpcchainvm/state_syncable_vm_test.go index da0c9fe3c89f..347fb78cc4e5 100644 --- a/vms/rpcchainvm/state_syncable_vm_test.go +++ b/vms/rpcchainvm/state_syncable_vm_test.go @@ -19,6 +19,7 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils" @@ -34,7 +35,7 @@ var ( SummaryHeight = uint64(2022) // a summary to be returned in some UTs - mockedSummary = &block.TestStateSummary{ + mockedSummary = &blocktest.TestStateSummary{ IDV: ids.ID{'s', 'u', 'm', 'm', 'a', 'r', 'y', 'I', 'D'}, HeightV: SummaryHeight, BytesV: []byte("summary"), diff --git a/wallet/chain/p/builder_test.go b/wallet/chain/p/builder_test.go index fcc323cb7dd4..4fa86905a00c 100644 --- a/wallet/chain/p/builder_test.go +++ b/wallet/chain/p/builder_test.go @@ -23,7 +23,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" - "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common/utxotest" ) var ( @@ -60,7 +60,7 @@ func TestBaseTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) backend = NewBackend(testContext, chainUTXOs, nil) @@ -107,7 +107,7 @@ func TestAddSubnetValidatorTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) @@ -165,7 +165,7 @@ func TestRemoveSubnetValidatorTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) @@ -217,7 +217,7 @@ func TestCreateChainTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) @@ -277,7 +277,7 @@ func TestCreateSubnetTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) @@ -326,7 +326,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) @@ -380,7 +380,7 @@ func TestImportTx(t *testing.T) { utxos = makeTestUTXOs(utxosKey) sourceChainID = ids.GenerateTestID() importedUTXOs = utxos[:1] - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, sourceChainID: importedUTXOs, }) @@ -429,7 +429,7 @@ func TestExportTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) backend = NewBackend(testContext, chainUTXOs, nil) @@ -480,7 +480,7 @@ func TestTransformSubnetTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) @@ -576,7 +576,7 @@ func TestAddPermissionlessValidatorTx(t *testing.T) { makeUTXO(1 * units.NanoAvax), // small UTXO makeUTXO(9 * units.Avax), // large UTXO } - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) backend = NewBackend(testContext, chainUTXOs, nil) @@ -655,7 +655,7 @@ func TestAddPermissionlessDelegatorTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - chainUTXOs = common.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ + chainUTXOs = utxotest.NewDeterministicChainUTXOs(require, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) backend = NewBackend(testContext, chainUTXOs, nil) diff --git a/wallet/chain/x/builder_test.go b/wallet/chain/x/builder_test.go index 801046c185ca..0fe9cd1e6caa 100644 --- a/wallet/chain/x/builder_test.go +++ b/wallet/chain/x/builder_test.go @@ -19,7 +19,7 @@ import ( "github.com/ava-labs/avalanchego/vms/propertyfx" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/chain/x/builder" - "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common/utxotest" ) var ( @@ -51,7 +51,7 @@ func TestBaseTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, @@ -100,7 +100,7 @@ func TestCreateAssetTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, @@ -189,7 +189,7 @@ func TestMintNFTOperation(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, @@ -234,7 +234,7 @@ func TestMintFTOperation(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, @@ -281,7 +281,7 @@ func TestMintPropertyOperation(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, @@ -324,7 +324,7 @@ func TestBurnPropertyOperation(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, @@ -362,7 +362,7 @@ func TestImportTx(t *testing.T) { utxos = makeTestUTXOs(utxosKey) sourceChainID = ids.GenerateTestID() importedUTXOs = utxos[:1] - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, @@ -412,7 +412,7 @@ func TestExportTx(t *testing.T) { // backend utxosKey = testKeys[1] utxos = makeTestUTXOs(utxosKey) - genericBackend = common.NewDeterministicChainUTXOs( + genericBackend = utxotest.NewDeterministicChainUTXOs( require, map[ids.ID][]*avax.UTXO{ xChainID: utxos, diff --git a/wallet/subnet/primary/common/test_utxos.go b/wallet/subnet/primary/common/utxotest/utxotest.go similarity index 83% rename from wallet/subnet/primary/common/test_utxos.go rename to wallet/subnet/primary/common/utxotest/utxotest.go index 0ab6b6decb8f..29436ac55eaf 100644 --- a/wallet/subnet/primary/common/test_utxos.go +++ b/wallet/subnet/primary/common/utxotest/utxotest.go @@ -1,9 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -//go:build test - -package common +package utxotest import ( "context" @@ -14,10 +12,11 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) func NewDeterministicChainUTXOs(require *require.Assertions, utxoSets map[ids.ID][]*avax.UTXO) *DeterministicChainUTXOs { - globalUTXOs := NewUTXOs() + globalUTXOs := common.NewUTXOs() for subnetID, utxos := range utxoSets { for _, utxo := range utxos { require.NoError( @@ -26,12 +25,12 @@ func NewDeterministicChainUTXOs(require *require.Assertions, utxoSets map[ids.ID } } return &DeterministicChainUTXOs{ - ChainUTXOs: NewChainUTXOs(constants.PlatformChainID, globalUTXOs), + ChainUTXOs: common.NewChainUTXOs(constants.PlatformChainID, globalUTXOs), } } type DeterministicChainUTXOs struct { - ChainUTXOs + common.ChainUTXOs } func (c *DeterministicChainUTXOs) UTXOs(ctx context.Context, sourceChainID ids.ID) ([]*avax.UTXO, error) { diff --git a/x/merkledb/db_test.go b/x/merkledb/db_test.go index f18e5053854b..1ef015f8db1b 100644 --- a/x/merkledb/db_test.go +++ b/x/merkledb/db_test.go @@ -18,6 +18,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/trace" @@ -100,7 +101,7 @@ func Test_MerkleDB_GetValues_Safety(t *testing.T) { func Test_MerkleDB_DB_Interface(t *testing.T) { for _, bf := range validBranchFactors { - for name, test := range database.Tests { + for name, test := range dbtest.Tests { t.Run(fmt.Sprintf("%s_%d", name, bf), func(t *testing.T) { db, err := getBasicDBWithBranchFactor(bf) require.NoError(t, err) @@ -111,10 +112,10 @@ func Test_MerkleDB_DB_Interface(t *testing.T) { } func Benchmark_MerkleDB_DBInterface(b *testing.B) { - for _, size := range database.BenchmarkSizes { - keys, values := database.SetupBenchmark(b, size[0], size[1], size[2]) + for _, size := range dbtest.BenchmarkSizes { + keys, values := dbtest.SetupBenchmark(b, size[0], size[1], size[2]) for _, bf := range validBranchFactors { - for name, bench := range database.Benchmarks { + for name, bench := range dbtest.Benchmarks { b.Run(fmt.Sprintf("merkledb_%d_%d_pairs_%d_keys_%d_values_%s", bf, size[0], size[1], size[2], name), func(b *testing.B) { db, err := getBasicDBWithBranchFactor(bf) require.NoError(b, err)