From 5057337f86b4b1423b33b169873ade54048346c0 Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 25 Jul 2024 18:49:30 +0330 Subject: [PATCH] test(other): using testify properly (#1433) --- CONTRIBUTING.md | 10 ++ committee/committee_test.go | 118 ++++++++++---------- config/config_test.go | 56 +++++----- consensus/config_test.go | 6 +- consensus/consensus_test.go | 26 ++--- consensus/height_test.go | 2 +- consensus/log/log_test.go | 2 +- consensus/manager_test.go | 8 +- consensus/propose_test.go | 4 +- consensus/spec/README.md | 2 +- consensus/voteset/vote_box_test.go | 2 +- consensus/voteset/voteset_test.go | 34 +++--- crypto/address_test.go | 10 +- crypto/bls/bls_test.go | 8 +- crypto/bls/hdkeychain/extendedkey_test.go | 40 +++---- crypto/bls/private_key_test.go | 6 +- crypto/bls/public_key_test.go | 13 ++- crypto/bls/signature_test.go | 10 +- crypto/hash/hash_test.go | 4 +- execution/executor/sortition_test.go | 2 - genesis/genesis_test.go | 33 +++--- go.mod | 2 +- go.sum | 2 + network/config_test.go | 2 +- network/gossip_test.go | 2 +- network/mdns_test.go | 4 +- network/network_test.go | 50 ++++----- network/utils_test.go | 6 +- node/node_test.go | 2 +- sandbox/sandbox_test.go | 73 ++++++------ scripts/snapshot.py | 74 +++++++----- sortition/vrf_test.go | 6 +- state/execution_test.go | 10 +- state/lastinfo/last_info_test.go | 4 +- state/state_test.go | 66 +++++------ store/account_test.go | 16 +-- store/block_test.go | 4 +- store/config_test.go | 6 +- store/store_test.go | 24 ++-- store/validator_test.go | 22 ++-- sync/bundle/message/block_announce_test.go | 2 +- sync/bundle/message/blocks_request_test.go | 8 +- sync/bundle/message/blocks_response_test.go | 18 +-- sync/bundle/message/hello_ack_test.go | 2 +- sync/bundle/message/hello_test.go | 6 +- sync/bundle/message/proposal_test.go | 2 +- sync/bundle/message/query_proposal_test.go | 4 +- sync/bundle/message/query_votes_test.go | 4 +- sync/bundle/message/transactions_test.go | 4 +- sync/bundle/message/vote_test.go | 2 +- sync/cache/cache_test.go | 4 +- sync/handler_block_announce_test.go | 8 +- sync/handler_blocks_request_test.go | 28 ++--- sync/handler_blocks_response_test.go | 8 +- sync/handler_hello_test.go | 24 ++-- sync/handler_query_proposal_test.go | 2 +- sync/handler_query_votes_test.go | 2 +- sync/handler_vote_test.go | 2 +- sync/peerset/peer/service/services_test.go | 12 +- sync/peerset/peer_set_test.go | 40 +++---- sync/sync_test.go | 6 +- tests/account_test.go | 2 +- tests/transaction_test.go | 8 +- tests/validator_test.go | 2 +- txpool/txpool_test.go | 16 +-- types/account/account_test.go | 16 +-- types/amount/amount_test.go | 12 +- types/block/block_test.go | 8 +- types/block/txs_test.go | 6 +- types/certificate/block_certificate_test.go | 10 +- types/certificate/vote_certificate_test.go | 10 +- types/tx/payload/bond_test.go | 12 +- types/tx/payload/sortition_test.go | 12 +- types/tx/payload/transfer_test.go | 16 +-- types/tx/tx_test.go | 10 +- types/validator/validator_test.go | 32 +++--- types/vote/vote_test.go | 52 ++++----- util/errors/errors_test.go | 10 +- util/htpasswd/htpasswd_test.go | 2 +- util/io_test.go | 2 +- util/linkedlist/linkedlist_test.go | 68 +++++------ util/persistentmerkle/merkle_test.go | 32 +++--- util/simplemerkle/merkle_test.go | 8 +- util/slice_test.go | 42 +++---- util/time_test.go | 28 ++--- util/utils_test.go | 54 ++++----- wallet/addresspath/path_test.go | 4 +- wallet/encrypter/encrypter_test.go | 14 +-- wallet/vault/utils_test.go | 2 +- wallet/vault/vault_test.go | 48 ++++---- wallet/wallet_test.go | 14 +-- www/grpc/basicauth/basicauth_test.go | 6 +- www/grpc/blockchain_test.go | 40 +++---- www/grpc/middleware_test.go | 10 +- www/grpc/server_test.go | 20 +--- www/grpc/transaction_test.go | 10 +- www/grpc/utils_test.go | 2 +- www/grpc/wallet_test.go | 2 +- www/http/blockchain_test.go | 48 ++++---- www/http/http_test.go | 2 +- www/http/network_test.go | 2 +- www/http/transaction_test.go | 4 +- www/nanomsg/event/event_test.go | 12 +- 103 files changed, 836 insertions(+), 833 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b572c4da8..9308d8500 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,16 @@ You can use these commands in the Makefile: Error and log messages should not start with a capital letter (unless it's a proper noun or acronym) and should not end with punctuation. +All changes on core must contain proper and well-defined unit-tests, also previous tests must be passed as well. +This codebase used `testify` for unit tests, make sure you follow these guide for tests: + +- For panic cases make sure you use `assert.Panics` +- For checking err using `assert.ErrorIs` make sure you pass expected error as second argument. +- For checking equality using `assert.Equal` make sure you pass expected value as the first argument. + + +> This code guideline must be followed for both contributors and maintainers to review the PRs. + #### Examples - Correct ✅: "unable to connect to server" diff --git a/committee/committee_test.go b/committee/committee_test.go index f014a4586..78d64325e 100644 --- a/committee/committee_test.go +++ b/committee/committee_test.go @@ -25,12 +25,12 @@ func TestProposer(t *testing.T) { cmt, _ := ts.GenerateTestCommittee(4) - assert.Equal(t, cmt.Proposer(0).Number(), int32(0)) - assert.Equal(t, cmt.Proposer(3).Number(), int32(3)) - assert.Equal(t, cmt.Proposer(4).Number(), int32(0)) + assert.Equal(t, int32(0), cmt.Proposer(0).Number()) + assert.Equal(t, int32(3), cmt.Proposer(3).Number()) + assert.Equal(t, int32(0), cmt.Proposer(4).Number()) cmt.Update(0, nil) - assert.Equal(t, cmt.Proposer(0).Number(), int32(1)) + assert.Equal(t, int32(1), cmt.Proposer(0).Number()) } func TestInvalidProposerJoinAndLeave(t *testing.T) { @@ -68,29 +68,29 @@ func TestProposerMove(t *testing.T) { // +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+ // - assert.Equal(t, cmt.Proposer(0).Number(), int32(1)) - assert.Equal(t, cmt.Proposer(7).Number(), int32(1)) - assert.Equal(t, cmt.Validators(), []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}) + assert.Equal(t, int32(1), cmt.Proposer(0).Number()) + assert.Equal(t, int32(1), cmt.Proposer(7).Number()) + assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) // Height 1001 cmt.Update(0, nil) - assert.Equal(t, cmt.Proposer(0).Number(), int32(2)) - assert.Equal(t, cmt.Proposer(1).Number(), int32(3)) - assert.Equal(t, cmt.Proposer(7).Number(), int32(2)) - assert.Equal(t, cmt.Validators(), []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}) + assert.Equal(t, int32(2), cmt.Proposer(0).Number()) + assert.Equal(t, int32(3), cmt.Proposer(1).Number()) + assert.Equal(t, int32(2), cmt.Proposer(7).Number()) + assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) // Height 1002 cmt.Update(3, nil) - assert.Equal(t, cmt.Proposer(0).Number(), int32(6)) - assert.Equal(t, cmt.Validators(), []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}) + assert.Equal(t, int32(6), cmt.Proposer(0).Number()) + assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) // Height 1003 cmt.Update(1, nil) - assert.Equal(t, cmt.Proposer(0).Number(), int32(1)) - assert.Equal(t, cmt.Validators(), []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}) + assert.Equal(t, int32(1), cmt.Proposer(0).Number()) + assert.Equal(t, []*validator.Validator{val1, val2, val3, val4, val5, val6, val7}, cmt.Validators()) fmt.Println(cmt.String()) } @@ -105,14 +105,10 @@ func TestValidatorConsistency(t *testing.T) { cmt, _ := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 4, val1.Address()) t.Run("Updating validators' stake, Should panic", func(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("The code did not panic") - } - }() - - val1.AddToStake(1) - cmt.Update(0, []*validator.Validator{val1}) + assert.Panics(t, func() { + val1.AddToStake(1) + cmt.Update(0, []*validator.Validator{val1}) + }, "The code did not panic") }) } @@ -129,7 +125,7 @@ func TestProposerJoin(t *testing.T) { cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 7, val1.Address()) assert.NoError(t, err) - assert.Equal(t, cmt.Size(), 4) + assert.Equal(t, 4, cmt.Size()) // // h=1000, r=0 h=1001, r=0 h=1002, r=1 h=1003, r=1 h=1004, r=0 @@ -142,24 +138,24 @@ func TestProposerJoin(t *testing.T) { // Val2 is in the committee val2.UpdateLastSortitionHeight(1000) cmt.Update(0, []*validator.Validator{val2}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(2)) - assert.Equal(t, cmt.Committers(), []int32{1, 2, 3, 4}) - assert.Equal(t, cmt.Size(), 4) + assert.Equal(t, int32(2), cmt.Proposer(0).Number()) + assert.Equal(t, []int32{1, 2, 3, 4}, cmt.Committers()) + assert.Equal(t, 4, cmt.Size()) fmt.Println(cmt.String()) // Height 1001 val5.UpdateLastSortitionHeight(1001) cmt.Update(0, []*validator.Validator{val5}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(3)) - assert.Equal(t, cmt.Proposer(1).Number(), int32(4)) - assert.Equal(t, cmt.Committers(), []int32{1, 5, 2, 3, 4}) - assert.Equal(t, cmt.Size(), 5) + assert.Equal(t, int32(3), cmt.Proposer(0).Number()) + assert.Equal(t, int32(4), cmt.Proposer(1).Number()) + assert.Equal(t, []int32{1, 5, 2, 3, 4}, cmt.Committers()) + assert.Equal(t, 5, cmt.Size()) fmt.Println(cmt.String()) // Height 1002 cmt.Update(1, nil) - assert.Equal(t, cmt.Proposer(0).Number(), int32(1)) - assert.Equal(t, cmt.Proposer(1).Number(), int32(5)) + assert.Equal(t, int32(1), cmt.Proposer(0).Number()) + assert.Equal(t, int32(5), cmt.Proposer(1).Number()) fmt.Println(cmt.String()) // Height 1003 @@ -167,14 +163,14 @@ func TestProposerJoin(t *testing.T) { val6.UpdateLastSortitionHeight(1003) val7.UpdateLastSortitionHeight(1003) cmt.Update(1, []*validator.Validator{val7, val3, val6}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(2)) - assert.Equal(t, cmt.Committers(), []int32{6, 7, 1, 5, 2, 3, 4}) - assert.Equal(t, cmt.Size(), 7) + assert.Equal(t, int32(2), cmt.Proposer(0).Number()) + assert.Equal(t, []int32{6, 7, 1, 5, 2, 3, 4}, cmt.Committers()) + assert.Equal(t, 7, cmt.Size()) fmt.Println(cmt.String()) // Height 1004 cmt.Update(0, nil) - assert.Equal(t, cmt.Proposer(0).Number(), int32(3)) + assert.Equal(t, int32(3), cmt.Proposer(0).Number()) fmt.Println(cmt.String()) } @@ -260,49 +256,49 @@ func TestProposerJoinAndLeave(t *testing.T) { // Height 1001 val8.UpdateLastSortitionHeight(1001) cmt.Update(0, []*validator.Validator{val8}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(2)) - assert.Equal(t, cmt.Proposer(1).Number(), int32(3)) - assert.Equal(t, cmt.Proposer(2).Number(), int32(4)) - assert.Equal(t, cmt.Committers(), []int32{8, 2, 3, 4, 5, 6, 7}) + assert.Equal(t, int32(2), cmt.Proposer(0).Number()) + assert.Equal(t, int32(3), cmt.Proposer(1).Number()) + assert.Equal(t, int32(4), cmt.Proposer(2).Number()) + assert.Equal(t, []int32{8, 2, 3, 4, 5, 6, 7}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1002 val3.UpdateLastSortitionHeight(1002) cmt.Update(3, []*validator.Validator{val3}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(6)) + assert.Equal(t, int32(6), cmt.Proposer(0).Number()) fmt.Println(cmt.String()) // Height 1003 val2.UpdateLastSortitionHeight(1003) val9.UpdateLastSortitionHeight(1003) cmt.Update(0, []*validator.Validator{val9, val2}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(7)) - assert.Equal(t, cmt.Proposer(1).Number(), int32(8)) - assert.Equal(t, cmt.Committers(), []int32{8, 2, 3, 5, 9, 6, 7}) + assert.Equal(t, int32(7), cmt.Proposer(0).Number()) + assert.Equal(t, int32(8), cmt.Proposer(1).Number()) + assert.Equal(t, []int32{8, 2, 3, 5, 9, 6, 7}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1004 valA.UpdateLastSortitionHeight(1004) cmt.Update(1, []*validator.Validator{valA}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(2)) - assert.Equal(t, cmt.Committers(), []int32{8, 2, 3, 9, 6, 10, 7}) + assert.Equal(t, int32(2), cmt.Proposer(0).Number()) + assert.Equal(t, []int32{8, 2, 3, 9, 6, 10, 7}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1005 valB.UpdateLastSortitionHeight(1005) valC.UpdateLastSortitionHeight(1005) cmt.Update(0, []*validator.Validator{valC, valB}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(3)) - assert.Equal(t, cmt.Proposer(1).Number(), int32(9)) - assert.Equal(t, cmt.Proposer(2).Number(), int32(10)) - assert.Equal(t, cmt.Committers(), []int32{8, 11, 12, 2, 3, 9, 10}) + assert.Equal(t, int32(3), cmt.Proposer(0).Number()) + assert.Equal(t, int32(9), cmt.Proposer(1).Number()) + assert.Equal(t, int32(10), cmt.Proposer(2).Number()) + assert.Equal(t, []int32{8, 11, 12, 2, 3, 9, 10}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1006 val1.UpdateLastSortitionHeight(1006) cmt.Update(2, []*validator.Validator{val1}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(11)) - assert.Equal(t, cmt.Committers(), []int32{11, 12, 2, 1, 3, 9, 10}) + assert.Equal(t, int32(11), cmt.Proposer(0).Number()) + assert.Equal(t, []int32{11, 12, 2, 1, 3, 9, 10}, cmt.Committers()) fmt.Println(cmt.String()) // Height 1007 @@ -311,8 +307,8 @@ func TestProposerJoinAndLeave(t *testing.T) { val5.UpdateLastSortitionHeight(1007) val6.UpdateLastSortitionHeight(1007) cmt.Update(4, []*validator.Validator{val2, val3, val5, val6}) - assert.Equal(t, cmt.Proposer(0).Number(), int32(5)) - assert.Equal(t, cmt.Committers(), []int32{5, 6, 11, 12, 2, 1, 3}) + assert.Equal(t, int32(5), cmt.Proposer(0).Number()) + assert.Equal(t, []int32{5, 6, 11, 12, 2, 1, 3}, cmt.Committers()) fmt.Println(cmt.String()) } @@ -327,12 +323,12 @@ func TestIsProposer(t *testing.T) { cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 4, val1.Address()) assert.NoError(t, err) - assert.Equal(t, cmt.Proposer(0).Number(), int32(0)) - assert.Equal(t, cmt.Proposer(1).Number(), int32(1)) + assert.Equal(t, int32(0), cmt.Proposer(0).Number()) + assert.Equal(t, int32(1), cmt.Proposer(1).Number()) assert.True(t, cmt.IsProposer(val3.Address(), 2)) assert.False(t, cmt.IsProposer(val4.Address(), 2)) assert.False(t, cmt.IsProposer(ts.RandAccAddress(), 2)) - assert.Equal(t, cmt.Validators(), []*validator.Validator{val1, val2, val3, val4}) + assert.Equal(t, []*validator.Validator{val1, val2, val3, val4}, cmt.Validators()) } func TestCommitters(t *testing.T) { @@ -345,7 +341,7 @@ func TestCommitters(t *testing.T) { cmt, err := committee.NewCommittee([]*validator.Validator{val1, val2, val3, val4}, 4, val1.Address()) assert.NoError(t, err) - assert.Equal(t, cmt.Committers(), []int32{0, 1, 2, 3}) + assert.Equal(t, []int32{0, 1, 2, 3}, cmt.Committers()) } func TestSortJoined(t *testing.T) { @@ -383,6 +379,6 @@ func TestTotalPower(t *testing.T) { totalPower := val0.Power() + val1.Power() + val2.Power() + val3.Power() + val4.Power() totalStake := val0.Stake() + val1.Stake() + val2.Stake() + val3.Stake() + val4.Stake() - assert.Equal(t, cmt.TotalPower(), totalPower) - assert.Equal(t, cmt.TotalPower(), int64(totalStake+1)) + assert.Equal(t, totalPower, cmt.TotalPower()) + assert.Equal(t, int64(totalStake+1), cmt.TotalPower()) } diff --git a/config/config_test.go b/config/config_test.go index 0bbf2d3ac..a849eb807 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -18,11 +18,11 @@ func TestSaveMainnetConfig(t *testing.T) { assert.NoError(t, err) assert.NoError(t, conf.BasicCheck()) - assert.Equal(t, DefaultConfigMainnet(), conf) + assert.Equal(t, conf, DefaultConfigMainnet()) confData, _ := util.ReadFile(path) exampleData, _ := util.ReadFile("example_config.toml") - assert.Equal(t, confData, exampleData) + assert.Equal(t, exampleData, confData) } func TestSaveTestnetConfig(t *testing.T) { @@ -32,7 +32,7 @@ func TestSaveTestnetConfig(t *testing.T) { conf, err := LoadFromFile(path, true, defConf) assert.NoError(t, err) - assert.Equal(t, DefaultConfigTestnet(), conf) + assert.Equal(t, conf, DefaultConfigTestnet()) assert.NoError(t, conf.BasicCheck()) } @@ -42,18 +42,18 @@ func TestDefaultConfig(t *testing.T) { assert.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) - assert.Equal(t, conf.Network.NetworkName, "") - assert.Equal(t, conf.Network.DefaultPort, 0) + assert.Zero(t, conf.Network.NetworkName) + assert.Zero(t, conf.Network.DefaultPort) assert.False(t, conf.GRPC.Enable) assert.False(t, conf.GRPC.Gateway.Enable) assert.False(t, conf.HTTP.Enable) assert.False(t, conf.Nanomsg.Enable) - assert.Equal(t, conf.GRPC.Listen, "") - assert.Equal(t, conf.GRPC.Gateway.Listen, "") - assert.Equal(t, conf.HTTP.Listen, "") - assert.Equal(t, conf.Nanomsg.Listen, "") + assert.Zero(t, conf.GRPC.Listen) + assert.Zero(t, conf.GRPC.Gateway.Listen) + assert.Zero(t, conf.HTTP.Listen) + assert.Zero(t, conf.Nanomsg.Listen) } func TestMainnetConfig(t *testing.T) { @@ -61,18 +61,18 @@ func TestMainnetConfig(t *testing.T) { assert.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) - assert.Equal(t, conf.Network.NetworkName, "pactus") - assert.Equal(t, conf.Network.DefaultPort, 21888) + assert.Equal(t, "pactus", conf.Network.NetworkName) + assert.Equal(t, 21888, conf.Network.DefaultPort) assert.True(t, conf.GRPC.Enable) assert.False(t, conf.GRPC.Gateway.Enable) assert.False(t, conf.HTTP.Enable) assert.False(t, conf.Nanomsg.Enable) - assert.Equal(t, conf.GRPC.Listen, "127.0.0.1:50051") - assert.Equal(t, conf.GRPC.Gateway.Listen, "127.0.0.1:8080") - assert.Equal(t, conf.HTTP.Listen, "127.0.0.1:80") - assert.Equal(t, conf.Nanomsg.Listen, "tcp://127.0.0.1:40899") + assert.Equal(t, "127.0.0.1:50051", conf.GRPC.Listen) + assert.Equal(t, "127.0.0.1:8080", conf.GRPC.Gateway.Listen) + assert.Equal(t, "127.0.0.1:80", conf.HTTP.Listen) + assert.Equal(t, "tcp://127.0.0.1:40899", conf.Nanomsg.Listen) } func TestTestnetConfig(t *testing.T) { @@ -80,18 +80,18 @@ func TestTestnetConfig(t *testing.T) { assert.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) - assert.Equal(t, conf.Network.NetworkName, "pactus-testnet") - assert.Equal(t, conf.Network.DefaultPort, 21777) + assert.Equal(t, "pactus-testnet", conf.Network.NetworkName) + assert.Equal(t, 21777, conf.Network.DefaultPort) assert.True(t, conf.GRPC.Enable) assert.True(t, conf.GRPC.Gateway.Enable) assert.False(t, conf.HTTP.Enable) assert.False(t, conf.Nanomsg.Enable) - assert.Equal(t, conf.GRPC.Listen, "[::]:50052") - assert.Equal(t, conf.GRPC.Gateway.Listen, "[::]:8080") - assert.Equal(t, conf.HTTP.Listen, "[::]:80") - assert.Equal(t, conf.Nanomsg.Listen, "tcp://[::]:40799") + assert.Equal(t, "[::]:50052", conf.GRPC.Listen) + assert.Equal(t, "[::]:8080", conf.GRPC.Gateway.Listen) + assert.Equal(t, "[::]:80", conf.HTTP.Listen) + assert.Equal(t, "tcp://[::]:40799", conf.Nanomsg.Listen) } func TestLocalnetConfig(t *testing.T) { @@ -99,18 +99,18 @@ func TestLocalnetConfig(t *testing.T) { assert.NoError(t, conf.BasicCheck()) assert.Empty(t, conf.Network.ListenAddrStrings) - assert.Equal(t, conf.Network.NetworkName, "pactus-localnet") - assert.Equal(t, conf.Network.DefaultPort, 0) + assert.Equal(t, "pactus-localnet", conf.Network.NetworkName) + assert.Equal(t, 0, conf.Network.DefaultPort) assert.True(t, conf.GRPC.Enable) assert.True(t, conf.GRPC.Gateway.Enable) assert.True(t, conf.HTTP.Enable) assert.True(t, conf.Nanomsg.Enable) - assert.Equal(t, conf.GRPC.Listen, "[::]:50052") - assert.Equal(t, conf.GRPC.Gateway.Listen, "[::]:8080") - assert.Equal(t, conf.HTTP.Listen, "[::]:0") - assert.Equal(t, conf.Nanomsg.Listen, "tcp://[::]:40799") + assert.Equal(t, "[::]:50052", conf.GRPC.Listen) + assert.Equal(t, "[::]:8080", conf.GRPC.Gateway.Listen) + assert.Equal(t, "[::]:0", conf.HTTP.Listen) + assert.Equal(t, "tcp://[::]:40799", conf.Nanomsg.Listen) } func TestLoadFromFile(t *testing.T) { @@ -126,7 +126,7 @@ func TestLoadFromFile(t *testing.T) { conf, err := LoadFromFile(path, false, defConf) assert.NoError(t, err) - assert.Equal(t, conf, defConf) + assert.Equal(t, defConf, conf) } func TestExampleConfig(t *testing.T) { diff --git a/consensus/config_test.go b/consensus/config_test.go index c36a4ccf9..49a2f61f6 100644 --- a/consensus/config_test.go +++ b/consensus/config_test.go @@ -74,7 +74,7 @@ func TestConfigBasicCheck(t *testing.T) { func TestCalculateChangeProposerTimeout(t *testing.T) { c := DefaultConfig() - assert.Equal(t, c.CalculateChangeProposerTimeout(0), c.ChangeProposerTimeout) - assert.Equal(t, c.CalculateChangeProposerTimeout(1), c.ChangeProposerTimeout+c.ChangeProposerDelta) - assert.Equal(t, c.CalculateChangeProposerTimeout(4), c.ChangeProposerTimeout+(4*c.ChangeProposerDelta)) + assert.Equal(t, c.ChangeProposerTimeout, c.CalculateChangeProposerTimeout(0)) + assert.Equal(t, c.ChangeProposerTimeout+c.ChangeProposerDelta, c.CalculateChangeProposerTimeout(1)) + assert.Equal(t, c.ChangeProposerTimeout+(4*c.ChangeProposerDelta), c.CalculateChangeProposerTimeout(4)) } diff --git a/consensus/consensus_test.go b/consensus/consensus_test.go index 4d0c9882d..a153f81c4 100644 --- a/consensus/consensus_test.go +++ b/consensus/consensus_test.go @@ -156,7 +156,7 @@ func (td *testData) shouldPublishBlockAnnounce(t *testing.T, cons *consensus, h if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeBlockAnnounce { m := consMsg.message.(*message.BlockAnnounceMessage) - assert.Equal(t, m.Block.Hash(), h) + assert.Equal(t, h, m.Block.Hash()) return } @@ -173,8 +173,8 @@ func (td *testData) shouldPublishProposal(t *testing.T, cons *consensus, if consMsg.sender == cons.valKey.Address() && consMsg.message.Type() == message.TypeProposal { m := consMsg.message.(*message.ProposalMessage) - require.Equal(t, m.Proposal.Height(), height) - require.Equal(t, m.Proposal.Round(), round) + require.Equal(t, height, m.Proposal.Height()) + require.Equal(t, round, m.Proposal.Round()) return m.Proposal } @@ -419,7 +419,7 @@ func TestNotInCommittee(t *testing.T) { td.enterNewHeight(cons) td.newHeightTimeout(cons) - assert.Equal(t, cons.currentState.name(), "new-height") + assert.Equal(t, "new-height", cons.currentState.name()) } func TestVoteWithInvalidHeight(t *testing.T) { @@ -482,7 +482,7 @@ func TestConsensusAddVote(t *testing.T) { assert.False(t, td.consP.HasVote(v5.Hash())) // valid votes for the next height assert.False(t, td.consP.HasVote(v6.Hash())) // invalid votes - assert.Equal(t, td.consP.AllVotes(), []*vote.Vote{v3, v4}) + assert.Equal(t, []*vote.Vote{v3, v4}, td.consP.AllVotes()) assert.NotContains(t, td.consP.AllVotes(), v2) } @@ -601,10 +601,10 @@ func TestPickRandomVote(t *testing.T) { td.addPrepareVote(td.consP, td.RandHash(), 1, 1, tIndexY) rndVote0 := td.consP.PickRandomVote(0) - assert.NotEqual(t, rndVote0.Type(), vote.VoteTypePrepare, "Should not pick prepare votes") + assert.NotEqual(t, vote.VoteTypePrepare, rndVote0.Type(), "Should not pick prepare votes") rndVote1 := td.consP.PickRandomVote(1) - assert.Equal(t, rndVote1.Type(), vote.VoteTypePrepare) + assert.Equal(t, vote.VoteTypePrepare, rndVote1.Type()) rndVote2 := td.consP.PickRandomVote(2) assert.Nil(t, rndVote2) @@ -660,7 +660,7 @@ func TestDuplicateProposal(t *testing.T) { td.consX.SetProposal(p1) td.consX.SetProposal(p2) - assert.Equal(t, td.consX.Proposal().Hash(), p1.Hash()) + assert.Equal(t, p1.Hash(), td.consX.Proposal().Hash()) } func TestNonActiveValidator(t *testing.T) { @@ -682,7 +682,7 @@ func TestNonActiveValidator(t *testing.T) { td.checkHeightRound(t, nonActiveCons, 1, 0) assert.False(t, nonActiveCons.IsActive()) - assert.Equal(t, nonActiveCons.currentState.name(), "new-height") + assert.Equal(t, "new-height", nonActiveCons.currentState.name()) }) t.Run("non-active instances should ignore proposals", func(t *testing.T) { @@ -767,7 +767,7 @@ func TestCases(t *testing.T) { cert, err := checkConsensus(td, 2, nil) require.NoError(t, err, "test %v failed: %s", i+1, err) - require.Equal(t, cert.Round(), test.round, + require.Equal(t, test.round, cert.Round(), "test %v failed. round not matched (expected %d, got %d)", i+1, test.round, cert.Round()) } @@ -858,8 +858,8 @@ func TestByzantine(t *testing.T) { p2 := td.makeProposal(t, h, r) require.NotEqual(t, p1.Block().Hash(), p2.Block().Hash()) - require.Equal(t, p1.Block().Header().ProposerAddress(), td.consB.valKey.Address()) - require.Equal(t, p2.Block().Header().ProposerAddress(), td.consB.valKey.Address()) + require.Equal(t, td.consB.valKey.Address(), p1.Block().Header().ProposerAddress()) + require.Equal(t, td.consB.valKey.Address(), p2.Block().Header().ProposerAddress()) td.enterNewHeight(td.consP) @@ -895,7 +895,7 @@ func TestByzantine(t *testing.T) { cert, err := checkConsensus(td, h, []*vote.Vote{byzVote1, byzVote2}) require.NoError(t, err) - require.Equal(t, cert.Height(), h) + require.Equal(t, h, cert.Height()) require.Contains(t, cert.Absentees(), int32(tIndexB)) } diff --git a/consensus/height_test.go b/consensus/height_test.go index 0c184f3fa..b1f0f4eeb 100644 --- a/consensus/height_test.go +++ b/consensus/height_test.go @@ -38,7 +38,7 @@ func TestNewHeightDoubleEntry(t *testing.T) { td.checkHeightRound(t, td.consX, 2, 0) assert.True(t, td.consX.active) - assert.NotEqual(t, td.consX.currentState.name(), "new-height") + assert.NotEqual(t, "new-height", td.consX.currentState.name()) } func TestNewHeightTimeBehindNetwork(t *testing.T) { diff --git a/consensus/log/log_test.go b/consensus/log/log_test.go index bb3ca8ff6..8658e6980 100644 --- a/consensus/log/log_test.go +++ b/consensus/log/log_test.go @@ -89,7 +89,7 @@ func TestSetRoundProposal(t *testing.T) { assert.True(t, log.HasRoundProposal(4)) assert.Nil(t, log.RoundProposal(0)) assert.Nil(t, log.RoundProposal(5)) - assert.Equal(t, log.RoundProposal(4).Hash(), prop.Hash()) + assert.Equal(t, prop.Hash(), log.RoundProposal(4).Hash()) } func TestCanVote(t *testing.T) { diff --git a/consensus/manager_test.go b/consensus/manager_test.go index 423f391d7..61c939f47 100644 --- a/consensus/manager_test.go +++ b/consensus/manager_test.go @@ -36,8 +36,8 @@ func TestManager(t *testing.T) { consB := mgr.instances[1].(*consensus) // inactive t.Run("Check if keys are assigned properly", func(t *testing.T) { - assert.Equal(t, valKeys[0].PublicKey(), consA.ConsensusKey()) - assert.Equal(t, valKeys[1].PublicKey(), consB.ConsensusKey()) + assert.Equal(t, consA.ConsensusKey(), valKeys[0].PublicKey()) + assert.Equal(t, consB.ConsensusKey(), valKeys[1].PublicKey()) }) t.Run("Check if all instances move to new height", func(t *testing.T) { @@ -48,7 +48,7 @@ func TestManager(t *testing.T) { consHeight, consRound := mgr.HeightRound() assert.True(t, mgr.HasActiveInstance()) - assert.Equal(t, consHeight, stateHeight+1) + assert.Equal(t, stateHeight+1, consHeight) assert.Zero(t, consRound) }) @@ -187,7 +187,7 @@ func TestMediator(t *testing.T) { m, ok := msg.(*message.BlockAnnounceMessage) if ok { - require.Equal(t, m.Height(), stateHeight+1) + require.Equal(t, stateHeight+1, m.Height()) return } diff --git a/consensus/propose_test.go b/consensus/propose_test.go index 9e91277ea..cd2094161 100644 --- a/consensus/propose_test.go +++ b/consensus/propose_test.go @@ -105,6 +105,6 @@ func TestProposalNextRound(t *testing.T) { // consX accepts his proposal, but doesn't move to the next round assert.NotNil(t, td.consX.log.RoundProposal(1)) assert.Nil(t, td.consX.Proposal()) - assert.Equal(t, td.consX.height, uint32(2)) - assert.Equal(t, td.consX.round, int16(0)) + assert.Equal(t, uint32(2), td.consX.height) + assert.Equal(t, int16(0), td.consX.round) } diff --git a/consensus/spec/README.md b/consensus/spec/README.md index 26740b498..02851dc5e 100644 --- a/consensus/spec/README.md +++ b/consensus/spec/README.md @@ -4,7 +4,7 @@ This folder contains the consensus specification for the Pactus blockchain, which is based on the TLA+ formal language. The specification defines the consensus algorithm used by the blockchain. -More info can be found [here](https://pactus.org/learn/consensus/specification/) +More info can be found [here](https://docs.pactus.org/protocol/consensus/specification/) ## Model checking diff --git a/consensus/voteset/vote_box_test.go b/consensus/voteset/vote_box_test.go index 33d7ad301..5bc816b6c 100644 --- a/consensus/voteset/vote_box_test.go +++ b/consensus/voteset/vote_box_test.go @@ -24,5 +24,5 @@ func TestDuplicateVote(t *testing.T) { vb.addVote(v, power) vb.addVote(v, power) - assert.Equal(t, vb.votedPower, power) + assert.Equal(t, power, vb.votedPower) } diff --git a/consensus/voteset/voteset_test.go b/consensus/voteset/voteset_test.go index 976c1ffa2..95f721f87 100644 --- a/consensus/voteset/voteset_test.go +++ b/consensus/voteset/voteset_test.go @@ -51,12 +51,12 @@ func TestAddBlockVote(t *testing.T) { ts.HelperSignVote(invKey, v1) added, err := vs.AddVote(v1) - assert.Equal(t, errors.Code(err), errors.ErrInvalidAddress) // unknown validator + assert.Equal(t, errors.ErrInvalidAddress, errors.Code(err)) // unknown validator assert.False(t, added) ts.HelperSignVote(invKey, v2) added, err = vs.AddVote(v2) - assert.Equal(t, errors.Code(err), errors.ErrInvalidSignature) // invalid signature + assert.Equal(t, errors.ErrInvalidSignature, errors.Code(err)) // invalid signature assert.False(t, added) ts.HelperSignVote(valKey, v2) @@ -70,7 +70,7 @@ func TestAddBlockVote(t *testing.T) { ts.HelperSignVote(valKey, v3) added, err = vs.AddVote(v3) - assert.Equal(t, errors.Code(err), errors.ErrDuplicateVote) + assert.Equal(t, errors.ErrDuplicateVote, errors.Code(err)) assert.True(t, added) } @@ -96,12 +96,12 @@ func TestAddBinaryVote(t *testing.T) { ts.HelperSignVote(invKey, v1) added, err := vs.AddVote(v1) - assert.Equal(t, errors.Code(err), errors.ErrInvalidAddress) // unknown validator + assert.Equal(t, errors.ErrInvalidAddress, errors.Code(err)) // unknown validator assert.False(t, added) ts.HelperSignVote(invKey, v2) added, err = vs.AddVote(v2) - assert.Equal(t, errors.Code(err), errors.ErrInvalidSignature) // invalid signature + assert.Equal(t, errors.ErrInvalidSignature, errors.Code(err)) // invalid signature assert.False(t, added) ts.HelperSignVote(valKey, v2) @@ -115,7 +115,7 @@ func TestAddBinaryVote(t *testing.T) { ts.HelperSignVote(valKey, v3) added, err = vs.AddVote(v3) - assert.Equal(t, errors.Code(err), errors.ErrDuplicateVote) + assert.Equal(t, errors.ErrDuplicateVote, errors.Code(err)) assert.True(t, added) } @@ -144,19 +144,19 @@ func TestDuplicateBlockVote(t *testing.T) { assert.True(t, added) added, err = vs.AddVote(duplicatedVote1) - assert.Equal(t, errors.Code(err), errors.ErrDuplicateVote) + assert.Equal(t, errors.ErrDuplicateVote, errors.Code(err)) assert.True(t, added) added, err = vs.AddVote(duplicatedVote2) - assert.Equal(t, errors.Code(err), errors.ErrDuplicateVote) + assert.Equal(t, errors.ErrDuplicateVote, errors.Code(err)) assert.True(t, added) bv1 := vs.BlockVotes(h1) bv2 := vs.BlockVotes(h2) bv3 := vs.BlockVotes(h3) - assert.Equal(t, bv1[addr], correctVote) - assert.Equal(t, bv2[addr], duplicatedVote1) - assert.Equal(t, bv3[addr], duplicatedVote2) + assert.Equal(t, correctVote, bv1[addr]) + assert.Equal(t, duplicatedVote1, bv2[addr]) + assert.Equal(t, duplicatedVote2, bv3[addr]) assert.False(t, vs.HasQuorumHash()) } @@ -185,11 +185,11 @@ func TestDuplicateBinaryVote(t *testing.T) { assert.True(t, added) added, err = vs.AddVote(duplicatedVote1) - assert.Equal(t, errors.Code(err), errors.ErrDuplicateVote) + assert.Equal(t, errors.ErrDuplicateVote, errors.Code(err)) assert.True(t, added) added, err = vs.AddVote(duplicatedVote2) - assert.Equal(t, errors.Code(err), errors.ErrDuplicateVote) + assert.Equal(t, errors.ErrDuplicateVote, errors.Code(err)) assert.True(t, added) assert.False(t, vs.HasOneThirdOfTotalPower(0)) @@ -235,7 +235,7 @@ func TestQuorum(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, vs.QuorumHash()) - assert.Equal(t, vs.QuorumHash(), &blockHash) + assert.Equal(t, &blockHash, vs.QuorumHash()) assert.True(t, vs.HasQuorumHash()) assert.Contains(t, vs.BlockVotes(blockHash), v4.Signer()) } @@ -268,13 +268,13 @@ func TestAllBlockVotes(t *testing.T) { _, err = vs.AddVote(v3) assert.NoError(t, err) - assert.Equal(t, vs.QuorumHash(), &h1) + assert.Equal(t, &h1, vs.QuorumHash()) _, err = vs.AddVote(v4) assert.Error(t, err) // duplicated // Check accumulated power - assert.Equal(t, vs.QuorumHash(), &h1) + assert.Equal(t, &h1, vs.QuorumHash()) // Check previous votes assert.Contains(t, vs.AllVotes(), v1) @@ -317,7 +317,7 @@ func TestAllBinaryVotes(t *testing.T) { assert.Nil(t, ranVote1) ranVote2 := vs.GetRandomVote(1, vote.CPValueYes) - assert.Equal(t, ranVote2, v2) + assert.Equal(t, v2, ranVote2) } func TestOneThirdPower(t *testing.T) { diff --git a/crypto/address_test.go b/crypto/address_test.go index 3de8f7376..cdb835566 100644 --- a/crypto/address_test.go +++ b/crypto/address_test.go @@ -116,8 +116,8 @@ func TestToString(t *testing.T) { addr, err := crypto.AddressFromString(test.encoded) if test.err == nil { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, addr, *test.result, "test %v: invalid result", no) - assert.Equal(t, addr.String(), strings.ToLower(test.encoded), "test %v: invalid encode", no) + assert.Equal(t, *test.result, addr, "test %v: invalid result", no) + assert.Equal(t, strings.ToLower(test.encoded), addr.String(), "test %v: invalid encode", no) } else { assert.ErrorIs(t, err, test.err, "test %v: invalid error", no) } @@ -173,11 +173,11 @@ func TestAddressEncoding(t *testing.T) { err := addr.Decode(r) if test.err != nil { - assert.ErrorIs(t, test.err, err, "test %v: error not matched", no) - assert.Equal(t, addr.SerializeSize(), test.size, "test %v invalid size", no) + assert.ErrorIs(t, err, test.err, "test %v: error not matched", no) + assert.Equal(t, test.size, addr.SerializeSize(), "test %v invalid size", no) } else { assert.NoError(t, err, "test %v expected no error", no) - assert.Equal(t, addr.SerializeSize(), test.size, "test %v invalid size", no) + assert.Equal(t, test.size, addr.SerializeSize(), "test %v invalid size", no) length := addr.SerializeSize() for i := 0; i < length; i++ { diff --git a/crypto/bls/bls_test.go b/crypto/bls/bls_test.go index e42232104..9fd940103 100644 --- a/crypto/bls/bls_test.go +++ b/crypto/bls/bls_test.go @@ -23,10 +23,10 @@ func TestSigning(t *testing.T) { addr, _ := crypto.AddressFromString("pc1p5x2a0lkt5nrrdqe0rkcv6r4pfkmdhrr3xk73tq") sig1 := prv.Sign(msg) - assert.Equal(t, sig1.Bytes(), sig.Bytes()) + assert.Equal(t, sig.Bytes(), sig1.Bytes()) assert.NoError(t, pub.Verify(msg, sig)) - assert.Equal(t, prv.PublicKey(), pub) - assert.Equal(t, pub.ValidatorAddress(), addr) + assert.Equal(t, pub, prv.PublicKey()) + assert.Equal(t, addr, pub.ValidatorAddress()) } func TestSignatureAggregate(t *testing.T) { @@ -180,7 +180,7 @@ func TestHashToCurve(t *testing.T) { mappedPoint, _ := g1.HashToCurve([]byte(test.msg), domain) d, _ := hex.DecodeString(test.expected) expectedPoint, _ := g1.FromBytes(d) - assert.Equal(t, mappedPoint, expectedPoint, + assert.Equal(t, expectedPoint, mappedPoint, "test %v: not match", no) } } diff --git a/crypto/bls/hdkeychain/extendedkey_test.go b/crypto/bls/hdkeychain/extendedkey_test.go index 35b0f341e..1932ed978 100644 --- a/crypto/bls/hdkeychain/extendedkey_test.go +++ b/crypto/bls/hdkeychain/extendedkey_test.go @@ -33,7 +33,7 @@ func TestNonHardenedDerivation(t *testing.T) { pubKey1 := extKey1.RawPublicKey() pubKey2 := extKey2.RawPublicKey() - require.Equal(t, extKey1.Path(), path) + require.Equal(t, path, extKey1.Path()) require.Equal(t, pubKey1, pubKey2) } @@ -63,8 +63,8 @@ func TestHardenedDerivation(t *testing.T) { blsPrivKey, _ := bls.PrivateKeyFromBytes(privKey) pubKey := extKey.RawPublicKey() - assert.Equal(t, extKey.Path(), path) - assert.Equal(t, blsPrivKey.PublicKey().Bytes(), pubKey) + assert.Equal(t, path, extKey.Path()) + assert.Equal(t, pubKey, blsPrivKey.PublicKey().Bytes()) } // TestDerivation tests derive private keys in hardened and non hardened modes. @@ -146,20 +146,20 @@ func TestDerivation(t *testing.T) { privKeyG1, err := extKeyG1.RawPrivateKey() require.NoError(t, err) - require.Equal(t, hex.EncodeToString(privKeyG1), test.wantPrivG1, + require.Equal(t, test.wantPrivG1, hex.EncodeToString(privKeyG1), "mismatched serialized private key for test #%v", i+1) privKeyG2, err := extKeyG2.RawPrivateKey() require.NoError(t, err) - require.Equal(t, hex.EncodeToString(privKeyG2), test.wantPrivG2, + require.Equal(t, test.wantPrivG2, hex.EncodeToString(privKeyG2), "mismatched serialized private key for test #%v", i+1) pubKeyG1 := extKeyG1.RawPublicKey() - require.Equal(t, hex.EncodeToString(pubKeyG1), test.wantPubG1, + require.Equal(t, test.wantPubG1, hex.EncodeToString(pubKeyG1), "mismatched serialized public key for test #%v", i+1) pubKeyG2 := extKeyG2.RawPublicKey() - require.Equal(t, hex.EncodeToString(pubKeyG2), test.wantPubG2, + require.Equal(t, test.wantPubG2, hex.EncodeToString(pubKeyG2), "mismatched serialized public key for test #%v", i+1) neuterKeyG1 := extKeyG1.Neuter() @@ -171,12 +171,12 @@ func TestDerivation(t *testing.T) { require.True(t, extKeyG2.IsPrivate()) require.False(t, neuterKeyG1.IsPrivate()) require.False(t, neuterKeyG2.IsPrivate()) - require.Equal(t, neuterPubKeyG1, pubKeyG1) - require.Equal(t, neuterPubKeyG2, pubKeyG2) - require.Equal(t, extKeyG1.Path(), test.path) - require.Equal(t, extKeyG2.Path(), test.path) - require.Equal(t, neuterKeyG1.Path(), test.path) - require.Equal(t, neuterKeyG2.Path(), test.path) + require.Equal(t, pubKeyG1, neuterPubKeyG1) + require.Equal(t, pubKeyG2, neuterPubKeyG2) + require.Equal(t, test.path, extKeyG1.Path()) + require.Equal(t, test.path, extKeyG2.Path()) + require.Equal(t, test.path, neuterKeyG1.Path()) + require.Equal(t, test.path, neuterKeyG2.Path()) _, err = neuterKeyG1.RawPrivateKey() assert.ErrorIs(t, err, ErrNotPrivExtKey) @@ -185,7 +185,7 @@ func TestDerivation(t *testing.T) { assert.ErrorIs(t, err, ErrNotPrivExtKey) blsPrivKey, _ := bls.PrivateKeyFromBytes(privKeyG2) - require.Equal(t, blsPrivKey.PublicKey().Bytes(), pubKeyG2) + require.Equal(t, pubKeyG2, blsPrivKey.PublicKey().Bytes()) } } @@ -338,10 +338,10 @@ func TestKeyToString(t *testing.T) { extKeyG2, _ := masterKeyG2.DerivePath(test.path) neuterKeyG2 := extKeyG2.Neuter() - require.Equal(t, extKeyG1.String(), test.wantXPrivG1, "test %d failed", i) - require.Equal(t, neuterKeyG1.String(), test.wantXPubG1, "test %d failed", i) - require.Equal(t, extKeyG2.String(), test.wantXPrivG2, "test %d failed", i) - require.Equal(t, neuterKeyG2.String(), test.wantXPubG2, "test %d failed", i) + require.Equal(t, test.wantXPrivG1, extKeyG1.String(), "test %d failed", i) + require.Equal(t, test.wantXPubG1, neuterKeyG1.String(), "test %d failed", i) + require.Equal(t, test.wantXPrivG2, extKeyG2.String(), "test %d failed", i) + require.Equal(t, test.wantXPubG2, neuterKeyG2.String(), "test %d failed", i) recoveredExtKeyG1, err := NewKeyFromString(test.wantXPrivG1) require.NoError(t, err) @@ -432,6 +432,8 @@ func TestInvalidString(t *testing.T) { func TestNeuter(t *testing.T) { extKey, _ := NewKeyFromString("XSECRET1PQ5QQQQYQQYQQQQQZQQQGQQSQQQQQPJ568VS9LZ67JKWW0P6TQY9NY58LV0PCVRQQTAEMKGV6ULJNS99Y68JHCVGPYPZTWSAST8PWFJMJQDU0FU8D4YMF58CZ998PGRN29EZYHLWNDVDDJAT3F4D") neuterKey := extKey.Neuter() - assert.Equal(t, neuterKey.String(), "xpublic1pq5qqqqyqqyqqqqqzqqqgqqsqqqqqpj568vs9lz67jkww0p6tqy9ny58lv0pcvrqqtaemkgv6uljns99y68jhcvgpxzvmgpqnpgdwddkajrwl9gjudyh5q4fklms3q3390mtt5ytznugp4kqxtrrpcqulq53aunrwnav2tjqzv47re") + assert.Equal(t, + "xpublic1pq5qqqqyqqyqqqqqzqqqgqqsqqqqqpj568vs9lz67jkww0p6tqy9ny58lv0pcvrqqtaemkgv6uljns99y68jhcvgpxzvmgpqnpgdwddkajrwl9gjudyh5q4fklms3q3390mtt5ytznugp4kqxtrrpcqulq53aunrwnav2tjqzv47re", + neuterKey.String()) assert.Equal(t, neuterKey, neuterKey.Neuter()) } diff --git a/crypto/bls/private_key_test.go b/crypto/bls/private_key_test.go index e270f2c8e..3d23e7c16 100644 --- a/crypto/bls/private_key_test.go +++ b/crypto/bls/private_key_test.go @@ -97,8 +97,8 @@ func TestPrivateKeyToString(t *testing.T) { prv, err := bls.PrivateKeyFromString(test.encoded) if test.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, prv.Bytes(), test.result, "test %v: invalid bytes", no) - assert.Equal(t, prv.String(), strings.ToUpper(test.encoded), "test %v: invalid encoded", no) + assert.Equal(t, test.result, prv.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, strings.ToUpper(test.encoded), prv.String(), "test %v: invalid encoded", no) } else { assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) } @@ -157,7 +157,7 @@ func TestKeyGen(t *testing.T) { } else { assert.NoError(t, err, "test'%v' failed. has error", i) - assert.Equal(t, hex.EncodeToString(prv.Bytes()), test.sk, + assert.Equal(t, test.sk, hex.EncodeToString(prv.Bytes()), "test '%v' failed. not equal", i) } } diff --git a/crypto/bls/public_key_test.go b/crypto/bls/public_key_test.go index 5d8d6a24f..2c3735ba5 100644 --- a/crypto/bls/public_key_test.go +++ b/crypto/bls/public_key_test.go @@ -76,15 +76,16 @@ func TestPublicKeyVerifyAddress(t *testing.T) { assert.NoError(t, err) err = pub1.VerifyAddress(pub2.AccountAddress()) - assert.Equal(t, err, crypto.AddressMismatchError{ + assert.Equal(t, crypto.AddressMismatchError{ Expected: pub1.AccountAddress(), Got: pub2.AccountAddress(), - }) + }, err) + err = pub1.VerifyAddress(pub2.ValidatorAddress()) - assert.Equal(t, err, crypto.AddressMismatchError{ + assert.Equal(t, crypto.AddressMismatchError{ Expected: pub1.ValidatorAddress(), Got: pub2.ValidatorAddress(), - }) + }, err) } func TestNilPublicKey(t *testing.T) { @@ -178,8 +179,8 @@ func TestPublicKeyBytes(t *testing.T) { pub, err := bls.PublicKeyFromString(test.encoded) if test.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, pub.Bytes(), test.result, "test %v: invalid bytes", no) - assert.Equal(t, pub.String(), test.encoded, "test %v: invalid encoded", no) + assert.Equal(t, test.result, pub.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, test.encoded, pub.String(), "test %v: invalid encoded", no) } else { assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) } diff --git a/crypto/bls/signature_test.go b/crypto/bls/signature_test.go index 0f9034e3d..7e098275b 100644 --- a/crypto/bls/signature_test.go +++ b/crypto/bls/signature_test.go @@ -80,9 +80,9 @@ func TestVerifyingSignature(t *testing.T) { assert.False(t, sig1.EqualsTo(sig2)) assert.NoError(t, pb1.Verify(msg, sig1)) assert.NoError(t, pb2.Verify(msg, sig2)) - assert.ErrorIs(t, crypto.ErrInvalidSignature, pb1.Verify(msg, sig2)) - assert.ErrorIs(t, crypto.ErrInvalidSignature, pb2.Verify(msg, sig1)) - assert.ErrorIs(t, crypto.ErrInvalidSignature, pb1.Verify(msg[1:], sig1)) + assert.ErrorIs(t, pb1.Verify(msg, sig2), crypto.ErrInvalidSignature) + assert.ErrorIs(t, pb2.Verify(msg, sig1), crypto.ErrInvalidSignature) + assert.ErrorIs(t, pb1.Verify(msg[1:], sig1), crypto.ErrInvalidSignature) } func TestSignatureBytes(t *testing.T) { @@ -128,8 +128,8 @@ func TestSignatureBytes(t *testing.T) { sig, err := bls.SignatureFromString(test.encoded) if test.valid { assert.NoError(t, err, "test %v: unexpected error", no) - assert.Equal(t, sig.Bytes(), test.bytes, "test %v: invalid bytes", no) - assert.Equal(t, sig.String(), test.encoded, "test %v: invalid encode", no) + assert.Equal(t, test.bytes, sig.Bytes(), "test %v: invalid bytes", no) + assert.Equal(t, test.encoded, sig.String(), "test %v: invalid encode", no) } else { assert.Contains(t, err.Error(), test.errMsg, "test %v: error not matched", no) } diff --git a/crypto/hash/hash_test.go b/crypto/hash/hash_test.go index 54a45645d..18f8e0b36 100644 --- a/crypto/hash/hash_test.go +++ b/crypto/hash/hash_test.go @@ -41,14 +41,14 @@ func TestHash256(t *testing.T) { data := []byte("zarb") h1 := hash.Hash256(data) expected, _ := hex.DecodeString("12b38977f2d67f06f0c0cd54aaf7324cf4fee184398ea33d295e8d1543c2ee1a") - assert.Equal(t, h1, expected) + assert.Equal(t, expected, h1) } func TestHash160(t *testing.T) { data := []byte("zarb") h := hash.Hash160(data) expected, _ := hex.DecodeString("e93efc0c83176034cb828e39435eeecc07a29298") - assert.Equal(t, h, expected) + assert.Equal(t, expected, h) } func TestHashBasicCheck(t *testing.T) { diff --git a/execution/executor/sortition_test.go b/execution/executor/sortition_test.go index bd2c75fd5..d0f0ab836 100644 --- a/execution/executor/sortition_test.go +++ b/execution/executor/sortition_test.go @@ -73,7 +73,6 @@ func TestExecuteSortitionTx(t *testing.T) { t.Run("Should fail, invalid proof", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime, val.Address(), proof) td.sandbox.TestAcceptSortition = false - td.check(t, trx, true, ErrInvalidSortitionProof) td.check(t, trx, false, ErrInvalidSortitionProof) }) @@ -99,7 +98,6 @@ func TestExecuteSortitionTx(t *testing.T) { t.Run("Should fail, expired sortition", func(t *testing.T) { trx := tx.NewSortitionTx(lockTime-1, val.Address(), proof) td.sandbox.TestAcceptSortition = true - td.check(t, trx, true, ErrExpiredSortition) td.check(t, trx, false, ErrExpiredSortition) }) diff --git a/genesis/genesis_test.go b/genesis/genesis_test.go index c800778bc..ebdefd9eb 100644 --- a/genesis/genesis_test.go +++ b/genesis/genesis_test.go @@ -29,7 +29,7 @@ func TestMarshaling(t *testing.T) { []*validator.Validator{val}, param.DefaultParams()) gen2 := new(genesis.Genesis) - assert.Equal(t, gen1.Params().BlockIntervalInSecond, 10) + assert.Equal(t, 10, gen1.Params().BlockIntervalInSecond) bz, err := json.MarshalIndent(gen1, " ", " ") require.NoError(t, err) @@ -52,17 +52,18 @@ func TestGenesisTestnet(t *testing.T) { crypto.AddressHRP = "tpc" gen := genesis.TestnetGenesis() - assert.Equal(t, len(gen.Validators()), 4) - assert.Equal(t, len(gen.Accounts()), 5) + assert.Equal(t, 4, len(gen.Validators())) + assert.Equal(t, 5, len(gen.Accounts())) genTime, _ := time.Parse("2006-01-02", "2024-03-16") expected, _ := hash.FromString("13f96e6fbc9e0de0d53537ac5e894fc8e66be1600436db2df1511dc30696e822") - assert.Equal(t, gen.Hash(), expected) - assert.Equal(t, gen.GenesisTime(), genTime) - assert.Equal(t, gen.Params().BondInterval, uint32(360)) - assert.Equal(t, gen.ChainType(), genesis.Testnet) - assert.Equal(t, gen.TotalSupply(), amount.Amount(42e15)) + assert.Equal(t, expected, gen.Hash()) + assert.Equal(t, genTime, gen.GenesisTime()) + assert.Equal(t, uint32(360), gen.Params().BondInterval) + assert.Equal(t, genesis.Testnet, gen.ChainType()) + assert.Equal(t, amount.Amount(42e15), gen.TotalSupply()) + // reset address HRP global variable to miannet to prevent next tests failing. crypto.AddressHRP = "pc" } @@ -73,12 +74,12 @@ func TestGenesisMainnet(t *testing.T) { genTime, _ := time.Parse("02 Jan 2006, 15:04 MST", "24 Jan 2024, 20:24 UTC") expected, _ := hash.FromString("e4d59e3145c9d718caf178edb33bc2ca7fe43e5b30990c9d57d53a60c4741432") - assert.Equal(t, gen.Hash(), expected) - assert.Equal(t, gen.GenesisTime(), genTime) - assert.Equal(t, gen.Params().BondInterval, uint32(8640/24)) - assert.Equal(t, gen.Params().UnbondInterval, uint32(8640*21)) - assert.Equal(t, gen.ChainType(), genesis.Mainnet) - assert.Equal(t, gen.TotalSupply(), amount.Amount(42e15)) + assert.Equal(t, expected, gen.Hash()) + assert.Equal(t, genTime, gen.GenesisTime()) + assert.Equal(t, uint32(8640/24), gen.Params().BondInterval) + assert.Equal(t, uint32(8640*21), gen.Params().UnbondInterval) + assert.Equal(t, genesis.Mainnet, gen.ChainType()) + assert.Equal(t, amount.Amount(42e15), gen.TotalSupply()) } func TestCheckGenesisAccountAndValidator(t *testing.T) { @@ -97,10 +98,10 @@ func TestCheckGenesisAccountAndValidator(t *testing.T) { gen := genesis.MakeGenesis(util.Now(), accs, vals, param.DefaultParams()) for addr, acc := range gen.Accounts() { - assert.Equal(t, acc, accs[addr]) + assert.Equal(t, accs[addr], acc) } for i, val := range gen.Validators() { - assert.Equal(t, val.Hash(), vals[i].Hash()) + assert.Equal(t, vals[i].Hash(), val.Hash()) } } diff --git a/go.mod b/go.mod index c6549f1c6..e30fcd5a7 100644 --- a/go.mod +++ b/go.mod @@ -33,7 +33,7 @@ require ( go.nanomsg.org/mangos/v3 v3.4.2 golang.org/x/crypto v0.24.0 golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 - google.golang.org/grpc v1.64.1 + google.golang.org/grpc v1.65.0 google.golang.org/protobuf v1.34.2 gopkg.in/natefinch/lumberjack.v2 v2.2.1 ) diff --git a/go.sum b/go.sum index 0e88d2230..7ae004190 100644 --- a/go.sum +++ b/go.sum @@ -794,6 +794,8 @@ google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3Iji google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= +google.golang.org/grpc v1.65.0 h1:bs/cUb4lp1G5iImFFd3u5ixQzweKizoZJAwBNLR42lc= +google.golang.org/grpc v1.65.0/go.mod h1:WgYC2ypjlB0EiQi6wdKixMqukr6lBc0Vo+oOgjrM5ZQ= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/network/config_test.go b/network/config_test.go index 3a3862957..7e16ffa85 100644 --- a/network/config_test.go +++ b/network/config_test.go @@ -116,7 +116,7 @@ func TestConfigBasicCheck(t *testing.T) { tc.updateFn(conf) if tc.expectedErr != nil { err := conf.BasicCheck() - assert.ErrorIs(t, tc.expectedErr, err, + assert.ErrorIs(t, err, tc.expectedErr, "Expected error not matched for test %d-%s, expected: %s, got: %s", i, tc.name, tc.expectedErr, err) } else { err := conf.BasicCheck() diff --git a/network/gossip_test.go b/network/gossip_test.go index 66dec3a3e..70a4a9fee 100644 --- a/network/gossip_test.go +++ b/network/gossip_test.go @@ -96,7 +96,7 @@ func TestTopicValidator(t *testing.T) { } propagate = tt.propagate result := validator(context.Background(), tt.peerID, msg) - assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, result, tt.expectedResult) }) } } diff --git a/network/mdns_test.go b/network/mdns_test.go index 7f68a5aac..611e6bb00 100644 --- a/network/mdns_test.go +++ b/network/mdns_test.go @@ -34,8 +34,8 @@ func TestMDNS(t *testing.T) { net1.SendTo(msg, net2.SelfID()) se := shouldReceiveEvent(t, net2, EventTypeStream).(*StreamMessage) - assert.Equal(t, se.From, net1.SelfID()) - assert.Equal(t, readData(t, se.Reader, len(msg)), msg) + assert.Equal(t, net1.SelfID(), se.From) + assert.Equal(t, msg, readData(t, se.Reader, len(msg))) net1.Stop() net2.Stop() diff --git a/network/network_test.go b/network/network_test.go index 3cdc04c11..21988317d 100644 --- a/network/network_test.go +++ b/network/network_test.go @@ -305,10 +305,10 @@ func TestNetwork(t *testing.T) { eN := shouldReceiveEvent(t, networkN, EventTypeGossip).(*GossipMessage) eX := shouldReceiveEvent(t, networkX, EventTypeGossip).(*GossipMessage) - assert.Equal(t, eB.Data, msg) - assert.Equal(t, eM.Data, msg) - assert.Equal(t, eN.Data, msg) - assert.Equal(t, eX.Data, msg) + assert.Equal(t, msg, eB.Data) + assert.Equal(t, msg, eM.Data) + assert.Equal(t, msg, eN.Data) + assert.Equal(t, msg, eX.Data) }) t.Run("only nodes subscribed to the consensus topic receive consensus gossip messages", func(t *testing.T) { @@ -323,9 +323,9 @@ func TestNetwork(t *testing.T) { eN := shouldReceiveEvent(t, networkN, EventTypeGossip).(*GossipMessage) shouldNotReceiveEvent(t, networkX) // Not joined the consensus topic - assert.Equal(t, eB.Data, msg) - assert.Equal(t, eM.Data, msg) - assert.Equal(t, eN.Data, msg) + assert.Equal(t, msg, eB.Data) + assert.Equal(t, msg, eM.Data) + assert.Equal(t, msg, eN.Data) }) t.Run("node P (public) is directly accessible by nodes M and N (private behind NAT)", func(t *testing.T) { @@ -336,8 +336,8 @@ func TestNetwork(t *testing.T) { msgM := ts.RandBytes(64) networkM.SendTo(msgM, networkP.SelfID()) eP := shouldReceiveEvent(t, networkP, EventTypeStream).(*StreamMessage) - assert.Equal(t, eP.From, networkM.SelfID()) - assert.Equal(t, readData(t, eP.Reader, len(msgM)), msgM) + assert.Equal(t, networkM.SelfID(), eP.From) + assert.Equal(t, msgM, readData(t, eP.Reader, len(msgM))) }) t.Run("node P (public) is directly accessible by node X (private behind NAT, without relay)", func(t *testing.T) { @@ -348,8 +348,8 @@ func TestNetwork(t *testing.T) { msgX := ts.RandBytes(64) networkX.SendTo(msgX, networkP.SelfID()) eP := shouldReceiveEvent(t, networkP, EventTypeStream).(*StreamMessage) - assert.Equal(t, eP.From, networkX.SelfID()) - assert.Equal(t, readData(t, eP.Reader, len(msgX)), msgX) + assert.Equal(t, networkX.SelfID(), eP.From) + assert.Equal(t, msgX, readData(t, eP.Reader, len(msgX))) }) t.Run("node P (public) is directly accessible by node B (bootstrap)", func(t *testing.T) { @@ -359,8 +359,8 @@ func TestNetwork(t *testing.T) { networkB.SendTo(msgB, networkP.SelfID()) eB := shouldReceiveEvent(t, networkP, EventTypeStream).(*StreamMessage) - assert.Equal(t, eB.From, networkB.SelfID()) - assert.Equal(t, readData(t, eB.Reader, len(msgB)), msgB) + assert.Equal(t, networkB.SelfID(), eB.From) + assert.Equal(t, msgB, readData(t, eB.Reader, len(msgB))) }) t.Run("Ignore broadcasting identical messages", func(t *testing.T) { @@ -373,7 +373,7 @@ func TestNetwork(t *testing.T) { eX := shouldReceiveEvent(t, networkX, EventTypeGossip).(*GossipMessage) - assert.Equal(t, eX.Data, msg) + assert.Equal(t, msg, eX.Data) assert.NotEqual(t, eX.From, networkM.SelfID(), "network X has no direct connection with M") assert.NotEqual(t, eX.From, networkN.SelfID(), "network X has no direct connection with N") @@ -392,7 +392,7 @@ func TestNetwork(t *testing.T) { // msgM := ts.RandBytes(64) // networkM.SendTo(msgM, networkN.SelfID()) // eM := shouldReceiveEvent(t, networkN, EventTypeStream).(*StreamMessage) - // assert.Equal(t, readData(t, eM.Reader, len(msgM)), msgM) + // assert.Equal(t, msgM, readData(t, eM.Reader, len(msgM))) // }) t.Run("closing connection", func(t *testing.T) { @@ -403,18 +403,18 @@ func TestNetwork(t *testing.T) { networkP.Stop() networkB.CloseConnection(networkP.SelfID()) e := shouldReceiveEvent(t, networkB, EventTypeDisconnect).(*DisconnectEvent) - assert.Equal(t, e.PeerID, networkP.SelfID()) + assert.Equal(t, networkP.SelfID(), e.PeerID) networkB.SendTo(msgB, networkP.SelfID()) }) t.Run("Reachability Status", func(t *testing.T) { fmt.Printf("Running %s\n", t.Name()) - assert.Equal(t, networkP.ReachabilityStatus(), "Public") - assert.Equal(t, networkB.ReachabilityStatus(), "Public") - assert.Equal(t, networkM.ReachabilityStatus(), "Private") - assert.Equal(t, networkN.ReachabilityStatus(), "Private") - assert.Equal(t, networkX.ReachabilityStatus(), "Private") + assert.Equal(t, "Public", networkP.ReachabilityStatus()) + assert.Equal(t, "Public", networkB.ReachabilityStatus()) + assert.Equal(t, "Private", networkM.ReachabilityStatus()) + assert.Equal(t, "Private", networkN.ReachabilityStatus()) + assert.Equal(t, "Private", networkX.ReachabilityStatus()) }) } @@ -476,15 +476,15 @@ func testConnection(t *testing.T, networkP, networkB *network) { time.Sleep(100 * time.Millisecond) } - assert.Equal(t, networkB.NumConnectedPeers(), 1) - assert.Equal(t, networkP.NumConnectedPeers(), 1) + assert.Equal(t, 1, networkB.NumConnectedPeers()) + assert.Equal(t, 1, networkP.NumConnectedPeers()) msg := []byte("test-msg") networkP.SendTo(msg, networkB.SelfID()) e := shouldReceiveEvent(t, networkB, EventTypeStream).(*StreamMessage) - assert.Equal(t, e.From, networkP.SelfID()) - assert.Equal(t, readData(t, e.Reader, len(msg)), msg) + assert.Equal(t, networkP.SelfID(), e.From) + assert.Equal(t, msg, readData(t, e.Reader, len(msg))) networkB.Stop() networkP.Stop() diff --git a/network/utils_test.go b/network/utils_test.go index af1963605..d9d5319ee 100644 --- a/network/utils_test.go +++ b/network/utils_test.go @@ -43,7 +43,7 @@ func TestMakeMultiAddrs(t *testing.T) { actualPis, actualError := MakeMultiAddrs(tc.inputAddrs) if tc.expected != nil { - assert.Equal(t, actualPis, tc.expected) + assert.Equal(t, tc.expected, actualPis) assert.NoError(t, actualError) } else { assert.Error(t, actualError) @@ -100,7 +100,7 @@ func TestMakeAddrInfos(t *testing.T) { actualPis, actualError := MakeAddrInfos(tc.inputAddrs) if tc.expectedPis != nil { - assert.Equal(t, actualPis, tc.expectedPis) + assert.Equal(t, tc.expectedPis, actualPis) assert.NoError(t, actualError) } else { assert.Error(t, actualError) @@ -159,5 +159,5 @@ func TestMessageIdFunc(t *testing.T) { m := &lp2pspb.Message{Data: []byte("zarb")} id := MessageIDFunc(m) - assert.Equal(t, "\x12\xb3\x89\x77\xf2\xd6\x7f\x06\xf0\xc0\xcd\x54\xaa\xf7\x32\x4c\xf4\xfe\xe1\x84", id) + assert.Equal(t, id, "\x12\xb3\x89\x77\xf2\xd6\x7f\x06\xf0\xc0\xcd\x54\xaa\xf7\x32\x4c\xf4\xfe\xe1\x84") } diff --git a/node/node_test.go b/node/node_test.go index 46785f3bc..ddfe57014 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -45,7 +45,7 @@ func TestRunningNode(t *testing.T) { assert.True(t, conf.Sync.Services.IsPrunedNode()) require.NoError(t, err) - assert.Equal(t, nd.state.LastBlockHash(), hash.UndefHash) + assert.Equal(t, hash.UndefHash, nd.state.LastBlockHash()) err = nd.Start() require.NoError(t, err) diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 17bf23b16..414a5c4fe 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -55,8 +55,8 @@ func setup(t *testing.T) *testData { } sandbox := NewSandbox(mockStore.LastHeight, mockStore, params, cmt, totalPower).(*sandbox) - assert.Equal(t, sandbox.CurrentHeight(), lastHeight) - assert.Equal(t, sandbox.Params(), params) + assert.Equal(t, lastHeight, sandbox.CurrentHeight()) + assert.Equal(t, params, sandbox.Params()) return &testData{ TestSuite: ts, @@ -89,27 +89,27 @@ func TestAccountChange(t *testing.T) { sbAcc1.AddToBalance(1) assert.False(t, td.sandbox.accounts[addr].updated) - assert.Equal(t, td.sandbox.Account(addr).Balance(), bal) + assert.Equal(t, bal, td.sandbox.Account(addr).Balance()) td.sandbox.UpdateAccount(addr, sbAcc1) assert.True(t, td.sandbox.accounts[addr].updated) - assert.Equal(t, td.sandbox.Account(addr).Balance(), bal+1) + assert.Equal(t, bal+1, td.sandbox.Account(addr).Balance()) t.Run("Update the same account again", func(t *testing.T) { sbAcc2 := td.sandbox.Account(addr) sbAcc2.AddToBalance(1) assert.True(t, td.sandbox.accounts[addr].updated, "it is updated before") - assert.Equal(t, td.sandbox.Account(addr).Balance(), bal+1) + assert.Equal(t, bal+1, td.sandbox.Account(addr).Balance()) td.sandbox.UpdateAccount(addr, sbAcc2) assert.True(t, td.sandbox.accounts[addr].updated) - assert.Equal(t, td.sandbox.Account(addr).Balance(), bal+2) + assert.Equal(t, bal+2, td.sandbox.Account(addr).Balance()) }) t.Run("Should be iterated", func(t *testing.T) { td.sandbox.IterateAccounts(func(a crypto.Address, acc *account.Account, updated bool) { assert.Equal(t, addr, a) assert.True(t, updated) - assert.Equal(t, acc.Balance(), bal+2) + assert.Equal(t, bal+2, acc.Balance()) }) }) }) @@ -147,7 +147,7 @@ func TestAnyRecentTransaction(t *testing.T) { assert.True(t, td.sandbox.AnyRecentTransaction(randTx2.ID())) totalTxFees := randTx1.Fee() + randTx2.Fee() - assert.Equal(t, td.sandbox.AccumulatedFee(), totalTxFees) + assert.Equal(t, totalTxFees, td.sandbox.AccumulatedFee()) } func TestValidatorChange(t *testing.T) { @@ -174,27 +174,27 @@ func TestValidatorChange(t *testing.T) { sbVal1.AddToStake(1) assert.False(t, td.sandbox.validators[addr].updated) - assert.Equal(t, td.sandbox.Validator(addr).Stake(), stk) + assert.Equal(t, stk, td.sandbox.Validator(addr).Stake()) td.sandbox.UpdateValidator(sbVal1) assert.True(t, td.sandbox.validators[sbVal1.Address()].updated) - assert.Equal(t, td.sandbox.Validator(addr).Stake(), stk+1) + assert.Equal(t, stk+1, td.sandbox.Validator(addr).Stake()) t.Run("Update the same validator again", func(t *testing.T) { sbVal2 := td.sandbox.Validator(addr) sbVal2.AddToStake(1) assert.True(t, td.sandbox.validators[addr].updated, "it is updated before") - assert.Equal(t, td.sandbox.Validator(addr).Stake(), stk+1) + assert.Equal(t, stk+1, td.sandbox.Validator(addr).Stake()) td.sandbox.UpdateValidator(sbVal2) assert.True(t, td.sandbox.validators[sbVal1.Address()].updated) - assert.Equal(t, td.sandbox.Validator(addr).Stake(), stk+2) + assert.Equal(t, stk+2, td.sandbox.Validator(addr).Stake()) }) t.Run("Should be iterated", func(t *testing.T) { td.sandbox.IterateValidators(func(val *validator.Validator, updated bool, joined bool) { assert.True(t, updated) assert.False(t, joined) - assert.Equal(t, val.Stake(), stk+2) + assert.Equal(t, stk+2, val.Stake()) }) }) }) @@ -265,13 +265,10 @@ func TestCreateDuplicated(t *testing.T) { }) t.Run("Try creating duplicated validator, Should panic", func(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("The code did not panic") - } - }() - pub := td.valKeys[3].PublicKey() - td.sandbox.MakeNewValidator(pub) + assert.Panics(t, func() { + pub := td.valKeys[3].PublicKey() + td.sandbox.MakeNewValidator(pub) + }) }) } @@ -279,23 +276,17 @@ func TestUpdateFromOutsideTheSandbox(t *testing.T) { td := setup(t) t.Run("Try update an account from outside the sandbox, Should panic", func(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("The code did not panic") - } - }() - acc, addr := td.GenerateTestAccount(td.RandInt32(0)) - td.sandbox.UpdateAccount(addr, acc) + assert.Panics(t, func() { + acc, addr := td.GenerateTestAccount(td.RandInt32(0)) + td.sandbox.UpdateAccount(addr, acc) + }) }) t.Run("Try update a validator from outside the sandbox, Should panic", func(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("The code did not panic") - } - }() - val, _ := td.GenerateTestValidator(td.RandInt32(0)) - td.sandbox.UpdateValidator(val) + assert.Panics(t, func() { + val, _ := td.GenerateTestValidator(td.RandInt32(0)) + td.sandbox.UpdateValidator(val) + }) }) } @@ -307,7 +298,7 @@ func TestAccountDeepCopy(t *testing.T) { acc := td.sandbox.MakeNewAccount(addr) acc.AddToBalance(1) - assert.NotEqual(t, td.sandbox.Account(addr), acc) + assert.NotEqual(t, acc, td.sandbox.Account(addr)) }) t.Run("existing account", func(t *testing.T) { @@ -315,7 +306,7 @@ func TestAccountDeepCopy(t *testing.T) { acc := td.sandbox.Account(addr) acc.AddToBalance(1) - assert.NotEqual(t, td.sandbox.Account(addr), acc) + assert.NotEqual(t, acc, td.sandbox.Account(addr)) }) t.Run("sandbox account", func(t *testing.T) { @@ -323,7 +314,7 @@ func TestAccountDeepCopy(t *testing.T) { acc := td.sandbox.Account(addr) acc.AddToBalance(1) - assert.NotEqual(t, td.sandbox.Account(addr), acc) + assert.NotEqual(t, acc, td.sandbox.Account(addr)) }) } @@ -335,7 +326,7 @@ func TestValidatorDeepCopy(t *testing.T) { val := td.sandbox.MakeNewValidator(pub) val.AddToStake(1) - assert.NotEqual(t, td.sandbox.Validator(pub.ValidatorAddress()), val) + assert.NotEqual(t, val, td.sandbox.Validator(pub.ValidatorAddress())) }) val0, _ := td.store.ValidatorByNumber(0) @@ -344,14 +335,14 @@ func TestValidatorDeepCopy(t *testing.T) { val := td.sandbox.Validator(addr) val.AddToStake(1) - assert.NotEqual(t, td.sandbox.Validator(addr), val) + assert.NotEqual(t, val, td.sandbox.Validator(addr)) }) t.Run("sandbox validator", func(t *testing.T) { val := td.sandbox.Validator(addr) val.AddToStake(1) - assert.NotEqual(t, td.sandbox.Validator(addr), val) + assert.NotEqual(t, val, td.sandbox.Validator(addr)) }) } @@ -360,7 +351,7 @@ func TestPowerDelta(t *testing.T) { assert.Zero(t, td.sandbox.PowerDelta()) td.sandbox.UpdatePowerDelta(1) - assert.Equal(t, td.sandbox.PowerDelta(), int64(1)) + assert.Equal(t, int64(1), td.sandbox.PowerDelta()) td.sandbox.UpdatePowerDelta(-1) assert.Zero(t, td.sandbox.PowerDelta()) } diff --git a/scripts/snapshot.py b/scripts/snapshot.py index e84de29be..a00c55d94 100644 --- a/scripts/snapshot.py +++ b/scripts/snapshot.py @@ -39,9 +39,7 @@ def setup_logging(): logging.basicConfig( - format='[%(asctime)s] %(message)s', - datefmt='%Y-%m-%d-%H:%M', - level=logging.INFO + format="[%(asctime)s] %(message)s", datefmt="%Y-%m-%d-%H:%M", level=logging.INFO ) @@ -64,10 +62,10 @@ def sha256(file_path): @staticmethod def update_metadata_file(snapshot_path, snapshot_metadata): - metadata_file = os.path.join(snapshot_path, 'snapshots', 'metadata.json') + metadata_file = os.path.join(snapshot_path, "snapshots", "metadata.json") if os.path.isfile(metadata_file): logging.info(f"Updating existing metadata file '{metadata_file}'") - with open(metadata_file, 'r') as f: + with open(metadata_file, "r") as f: metadata = json.load(f) else: logging.info(f"Creating new metadata file '{metadata_file}'") @@ -82,22 +80,24 @@ def update_metadata_file(snapshot_path, snapshot_metadata): metadata.append(formatted_metadata) - with open(metadata_file, 'w') as f: + with open(metadata_file, "w") as f: json.dump(metadata, f, indent=4) @staticmethod def update_metadata_after_removal(snapshots_dir, removed_snapshots): - metadata_file = os.path.join(snapshots_dir, 'metadata.json') + metadata_file = os.path.join(snapshots_dir, "metadata.json") if not os.path.isfile(metadata_file): return logging.info(f"Updating metadata file '{metadata_file}' after snapshot removal") - with open(metadata_file, 'r') as f: + with open(metadata_file, "r") as f: metadata = json.load(f) - updated_metadata = [entry for entry in metadata if entry["name"] not in removed_snapshots] + updated_metadata = [ + entry for entry in metadata if entry["name"] not in removed_snapshots + ] - with open(metadata_file, 'w') as f: + with open(metadata_file, "w") as f: json.dump(updated_metadata, f, indent=4) @staticmethod @@ -133,7 +133,13 @@ def create_compressed_snapshot_json(compressed_file, rel_path): def run_command(command): logging.info(f"Running command: {' '.join(command)}") try: - result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + result = subprocess.run( + command, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) logging.info(f"Command output: {result.stdout.strip()}") if result.stderr.strip(): logging.error(f"Command error: {result.stderr.strip()}") @@ -154,13 +160,13 @@ class DaemonManager: def start_service(service_path): sv = get_service_name(service_path) logging.info(f"Starting '{sv}' service") - return run_command(['sudo', 'systemctl', 'start', sv]) + return run_command(["sudo", "systemctl", "start", sv]) @staticmethod def stop_service(service_path): sv = get_service_name(service_path) logging.info(f"Stopping '{sv}' service") - return run_command(['sudo', 'systemctl', 'stop', sv]) + return run_command(["sudo", "systemctl", "stop", sv]) class SnapshotManager: @@ -168,14 +174,18 @@ def __init__(self, args): self.args = args def manage_snapshots(self): - snapshots_dir = os.path.join(self.args.snapshot_path, 'snapshots') + snapshots_dir = os.path.join(self.args.snapshot_path, "snapshots") logging.info(f"Managing snapshots in '{snapshots_dir}'") if not os.path.exists(snapshots_dir): - logging.info(f"Snapshots directory '{snapshots_dir}' does not exist. Creating it.") + logging.info( + f"Snapshots directory '{snapshots_dir}' does not exist. Creating it." + ) os.makedirs(snapshots_dir) - snapshots = sorted([s for s in os.listdir(snapshots_dir) if s != 'metadata.json']) + snapshots = sorted( + [s for s in os.listdir(snapshots_dir) if s != "metadata.json"] + ) logging.info(f"Found snapshots: {snapshots}") logging.info(f"Retention policy is to keep {self.args.retention} snapshots") @@ -193,7 +203,7 @@ def manage_snapshots(self): def create_snapshot(self): timestamp_str = get_timestamp_str() - snapshot_dir = os.path.join(self.args.snapshot_path, 'snapshots', timestamp_str) + snapshot_dir = os.path.join(self.args.snapshot_path, "snapshots", timestamp_str) logging.info(f"Creating snapshot directory '{snapshot_dir}'") os.makedirs(snapshot_dir, exist_ok=True) @@ -232,7 +242,7 @@ def create_snapshot(self): class Validation: @staticmethod def validate_args(args): - logging.info('Validating arguments') + logging.info("Validating arguments") if not os.path.isfile(args.service_path): raise ValueError(f"Service file '{args.service_path}' does not exist.") @@ -243,17 +253,19 @@ def validate_args(args): logging.info(f"Data path '{args.data_path}' exists") if not os.access(args.data_path, os.W_OK): - raise PermissionError(f"No permission to access data path '{args.data_path}'.") + raise PermissionError( + f"No permission to access data path '{args.data_path}'." + ) logging.info(f"Permission to access data path '{args.data_path}' confirmed") - if args.compress == 'zip' and not shutil.which('zip'): + if args.compress == "zip" and not shutil.which("zip"): raise EnvironmentError("The 'zip' command is not available.") - elif args.compress == 'zip': + elif args.compress == "zip": logging.info("The 'zip' command is available") - if args.compress == 'tar' and not shutil.which('tar'): + if args.compress == "tar" and not shutil.which("tar"): raise EnvironmentError("The 'tar' command is not available.") - elif args.compress == 'tar': + elif args.compress == "tar": logging.info("The 'tar' command is available") if args.retention <= 0: @@ -261,10 +273,14 @@ def validate_args(args): logging.info(f"Retention value is set to {args.retention}") if not os.access(args.snapshot_path, os.W_OK): - raise PermissionError(f"No permission to access snapshot path '{args.snapshot_path}'.") - logging.info(f"Permission to access snapshot path '{args.snapshot_path}' confirmed") - - snapshots_dir = os.path.join(args.snapshot_path, 'snapshots') + raise PermissionError( + f"No permission to access snapshot path '{args.snapshot_path}'." + ) + logging.info( + f"Permission to access snapshot path '{args.snapshot_path}' confirmed" + ) + + snapshots_dir = os.path.join(args.snapshot_path, "snapshots") if not os.path.isdir(snapshots_dir): logging.info("Snapshots directory does not exist, creating it") os.makedirs(snapshots_dir) @@ -276,7 +292,9 @@ def validate(): if os.name == "nt": raise EnvironmentError("Windows not supported.") if os.geteuid() != 0: - raise PermissionError("This script requires sudo/root access. Please run with sudo.") + raise PermissionError( + "This script requires sudo/root access. Please run with sudo." + ) class ProcessBackup: diff --git a/sortition/vrf_test.go b/sortition/vrf_test.go index 96623b59b..591c34aea 100644 --- a/sortition/vrf_test.go +++ b/sortition/vrf_test.go @@ -27,7 +27,7 @@ func TestVRF(t *testing.T) { index2, result := sortition.Verify(seed, pk, proof, max) - assert.Equal(t, result, true) + assert.True(t, result) assert.Equal(t, index, index2) } } @@ -79,7 +79,7 @@ func TestGetIndex(t *testing.T) { // proofH * 1000000 / denominator = 655152.7021258341 proof1, _ := sortition.ProofFromString( "1719b896ec1cc66a0f44c4bf90890d988e341cb2c1a808907780af844c854291536c12fdaef9a526bb7ef80da17c0b03") - assert.Equal(t, sortition.GetIndex(proof1, 1*1e6), uint64(655152)) + assert.Equal(t, uint64(655152), sortition.GetIndex(proof1, 1*1e6)) // proof: 45180defab2daae377977bf09dcdd7d76ff4fc96d1b50cc8ac5a1601c0522fb11641c3ed0fefd4b1e1808c498d699396 // proofH: 80212979d1de1ca4ce1258fc0be66a4453b3804e64a5ca8d95f7def2c291c7fe @@ -87,5 +87,5 @@ func TestGetIndex(t *testing.T) { // proofH * 1000000 / denominator = 500506.0121928797 proof2, _ := sortition.ProofFromString( "45180defab2daae377977bf09dcdd7d76ff4fc96d1b50cc8ac5a1601c0522fb11641c3ed0fefd4b1e1808c498d699396") - assert.Equal(t, sortition.GetIndex(proof2, 1*1e6), uint64(500506)) + assert.Equal(t, uint64(500506), sortition.GetIndex(proof2, 1*1e6)) } diff --git a/state/execution_test.go b/state/execution_test.go index a45ef36bf..e1811c760 100644 --- a/state/execution_test.go +++ b/state/execution_test.go @@ -38,13 +38,13 @@ func TestProposeBlock(t *testing.T) { assert.NoError(t, td.state.AddPendingTx(validTrx2)) blk, cert := td.makeBlockAndCertificate(t, 0) - assert.Equal(t, blk.Header().PrevBlockHash(), td.state.LastBlockHash()) - assert.Equal(t, blk.Transactions()[1:], block.Txs{validTrx1, validTrx2}) + assert.Equal(t, td.state.LastBlockHash(), blk.Header().PrevBlockHash()) + assert.Equal(t, block.Txs{validTrx1, validTrx2}, blk.Transactions()[1:]) assert.True(t, blk.Transactions()[0].IsSubsidyTx()) assert.NoError(t, td.state.CommitBlock(blk, cert)) - assert.Equal(t, td.state.TotalPower(), int64(1000000004)) - assert.Equal(t, td.state.committee.TotalPower(), int64(4)) + assert.Equal(t, int64(1000000004), td.state.TotalPower()) + assert.Equal(t, int64(4), td.state.committee.TotalPower()) } func TestExecuteBlock(t *testing.T) { @@ -139,6 +139,6 @@ func TestExecuteBlock(t *testing.T) { // Check if fee is claimed treasury := sb.Account(crypto.TreasuryAddress) subsidy := td.state.params.BlockReward - assert.Equal(t, treasury.Balance(), 21*1e15-(10*subsidy)) // Two extra blocks has committed yet + assert.Equal(t, 21*1e15-(10*subsidy), treasury.Balance()) // Two extra blocks has committed yet }) } diff --git a/state/lastinfo/last_info_test.go b/state/lastinfo/last_info_test.go index d071f15b9..d64697232 100644 --- a/state/lastinfo/last_info_test.go +++ b/state/lastinfo/last_info_test.go @@ -84,7 +84,7 @@ func setup(t *testing.T) *testData { lastCert := certificate.NewBlockCertificate(lastHeight, 0) lastCert.SetSignature(committers, []int32{}, sig) mockStore.SaveBlock(lastBlock, lastCert) - assert.Equal(t, mockStore.LastHeight, lastHeight) + assert.Equal(t, lastHeight, mockStore.LastHeight) lastInfo.UpdateSortitionSeed(lastSeed) lastInfo.UpdateBlockHash(lastBlock.Hash()) @@ -118,7 +118,7 @@ func TestRestoreCommittee(t *testing.T) { assert.Equal(t, td.lastInfo.Certificate().Hash(), li.Certificate().Hash()) assert.Equal(t, td.lastInfo.BlockTime(), li.BlockTime()) assert.Equal(t, td.lastInfo.Validators(), []*validator.Validator{val0, val1, val2, val3}) - assert.Equal(t, cmt.Committers(), []int32{1, 4, 2, 3}) + assert.Equal(t, []int32{1, 4, 2, 3}, cmt.Committers()) } func TestRestoreFailed(t *testing.T) { diff --git a/state/state_test.go b/state/state_test.go index 4bbc14479..860e295df 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -153,9 +153,9 @@ func TestBlockSubsidyTx(t *testing.T) { randAccumulatedFee := td.RandFee() trx := td.state.createSubsidyTx(rewardAddr, randAccumulatedFee) assert.True(t, trx.IsSubsidyTx()) - assert.Equal(t, trx.Payload().Value(), td.state.params.BlockReward+randAccumulatedFee) - assert.Equal(t, trx.Payload().(*payload.TransferPayload).From, crypto.TreasuryAddress) - assert.Equal(t, trx.Payload().(*payload.TransferPayload).To, rewardAddr) + assert.Equal(t, td.state.params.BlockReward+randAccumulatedFee, trx.Payload().Value()) + assert.Equal(t, crypto.TreasuryAddress, trx.Payload().(*payload.TransferPayload).From) + assert.Equal(t, rewardAddr, trx.Payload().(*payload.TransferPayload).To) } func TestGenesisHash(t *testing.T) { @@ -189,10 +189,10 @@ func TestTryCommitValidBlocks(t *testing.T) { // No error here but block is ignored, because the height is invalid assert.NoError(t, td.state.CommitBlock(blk, crt)) - assert.Equal(t, td.state.LastBlockHash(), blk.Hash()) - assert.Equal(t, td.state.LastBlockTime(), blk.Header().Time()) - assert.Equal(t, td.state.LastCertificate().Hash(), crt.Hash()) - assert.Equal(t, td.state.LastBlockHeight(), uint32(9)) + assert.Equal(t, blk.Hash(), td.state.LastBlockHash()) + assert.Equal(t, blk.Header().Time(), td.state.LastBlockTime()) + assert.Equal(t, crt.Hash(), td.state.LastCertificate().Hash()) + assert.Equal(t, uint32(9), td.state.LastBlockHeight()) } func TestCommitSandbox(t *testing.T) { @@ -207,7 +207,7 @@ func TestCommitSandbox(t *testing.T) { td.state.commitSandbox(sb, 0) stateAcc := td.state.AccountByAddress(addr) - assert.Equal(t, newAcc, stateAcc) + assert.Equal(t, stateAcc, newAcc) }) t.Run("Add new validator", func(t *testing.T) { @@ -222,8 +222,8 @@ func TestCommitSandbox(t *testing.T) { stateValByNumber := td.state.ValidatorByAddress(pub.ValidatorAddress()) stateValByAddr := td.state.ValidatorByAddress(pub.ValidatorAddress()) - assert.Equal(t, newVal, stateValByNumber) - assert.Equal(t, newVal, stateValByAddr) + assert.Equal(t, stateValByNumber, newVal) + assert.Equal(t, stateValByAddr, newVal) }) t.Run("Modify account", func(t *testing.T) { @@ -330,7 +330,7 @@ func TestUpdateLastCertificate(t *testing.T) { for i, test := range tests { err := td.state.UpdateLastCertificate(test.vote) - assert.ErrorIs(t, test.err, err, "error not matched for test %v", i) + assert.ErrorIs(t, err, test.err, "error not matched for test %v", i) } } @@ -350,7 +350,7 @@ func TestBlockProposal(t *testing.T) { b, err := td.state.ProposeBlock(td.state.valKeys[0], td.RandAccAddress()) assert.NoError(t, err) assert.NoError(t, td.state.ValidateBlock(b, 0)) - assert.Equal(t, b.Transactions().Len(), 1) + assert.Equal(t, 1, b.Transactions().Len()) }) } @@ -366,25 +366,21 @@ func TestForkDetection(t *testing.T) { }) t.Run("Two blocks with different previous block hashes", func(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("The code did not panic") - } - }() - - blk0, _ := td.makeBlockAndCertificate(t, 0) - blkFork := block.MakeBlock( - blk0.Header().Version(), - blk0.Header().Time(), - blk0.Transactions(), - td.RandHash(), - blk0.Header().StateRoot(), - blk0.PrevCertificate(), - blk0.Header().SortitionSeed(), - blk0.Header().ProposerAddress()) - certFork := td.makeCertificateAndSign(t, blkFork.Hash(), 0) - - _ = td.state.CommitBlock(blkFork, certFork) + assert.Panics(t, func() { + blk0, _ := td.makeBlockAndCertificate(t, 0) + blkFork := block.MakeBlock( + blk0.Header().Version(), + blk0.Header().Time(), + blk0.Transactions(), + td.RandHash(), + blk0.Header().StateRoot(), + blk0.PrevCertificate(), + blk0.Header().SortitionSeed(), + blk0.Header().ProposerAddress()) + certFork := td.makeCertificateAndSign(t, blkFork.Hash(), 0) + + _ = td.state.CommitBlock(blkFork, certFork) + }) }) } @@ -394,7 +390,7 @@ func TestSortition(t *testing.T) { secValKey := td.state.valKeys[1] assert.False(t, td.state.evaluateSortition()) // not a validator assert.False(t, td.state.IsValidator(secValKey.Address())) - assert.Equal(t, td.state.CommitteePower(), int64(4)) + assert.Equal(t, int64(4), td.state.CommitteePower()) trx := tx.NewBondTx(1, td.genAccKey.PublicKeyNative().AccountAddress(), secValKey.Address(), secValKey.PublicKey(), 1000000000, 100000, "") @@ -405,7 +401,7 @@ func TestSortition(t *testing.T) { assert.False(t, td.state.evaluateSortition()) // bonding period assert.True(t, td.state.IsValidator(secValKey.Address())) - assert.Equal(t, td.state.CommitteePower(), int64(4)) + assert.Equal(t, int64(4), td.state.CommitteePower()) assert.False(t, td.state.committee.Contains(secValKey.Address())) // Not in the committee // Committing another 10 blocks @@ -417,7 +413,7 @@ func TestSortition(t *testing.T) { td.commitBlocks(t, 1) assert.True(t, td.state.IsValidator(secValKey.Address())) - assert.Equal(t, td.state.CommitteePower(), int64(1000000004)) + assert.Equal(t, int64(1000000004), td.state.CommitteePower()) assert.True(t, td.state.committee.Contains(secValKey.Address())) // In the committee } @@ -626,6 +622,6 @@ func TestCommittedBlock(t *testing.T) { cBlkLast := td.state.CommittedBlock(td.state.LastBlockHeight()) blkLast, err := cBlkLast.ToBlock() assert.NoError(t, err) - assert.Equal(t, td.state.LastBlockHash(), blkLast.Hash()) + assert.Equal(t, blkLast.Hash(), td.state.LastBlockHash()) }) } diff --git a/store/account_test.go b/store/account_test.go index 72844ee10..5076ec04e 100644 --- a/store/account_test.go +++ b/store/account_test.go @@ -21,7 +21,7 @@ func TestAccountCounter(t *testing.T) { td.store.UpdateAccount(addr, acc) assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalAccounts(), int32(1)) + assert.Equal(t, int32(1), td.store.TotalAccounts()) }) t.Run("Update account, should not increase the total accounts number", func(t *testing.T) { @@ -29,7 +29,7 @@ func TestAccountCounter(t *testing.T) { td.store.UpdateAccount(addr, acc) assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalAccounts(), int32(1)) + assert.Equal(t, int32(1), td.store.TotalAccounts()) }) t.Run("Get account", func(t *testing.T) { @@ -37,7 +37,7 @@ func TestAccountCounter(t *testing.T) { assert.NoError(t, err) assert.Equal(t, acc1.Hash(), acc.Hash()) - assert.Equal(t, td.store.TotalAccounts(), int32(1)) + assert.Equal(t, int32(1), td.store.TotalAccounts()) assert.True(t, td.store.HasAccount(addr)) }) } @@ -52,13 +52,13 @@ func TestAccountBatchSaving(t *testing.T) { td.store.UpdateAccount(addr, acc) } assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalAccounts(), total) + assert.Equal(t, total, td.store.TotalAccounts()) }) t.Run("Close and load db", func(t *testing.T) { td.store.Close() store, _ := NewStore(td.store.config) - assert.Equal(t, store.TotalAccounts(), total) + assert.Equal(t, total, store.TotalAccounts()) }) } @@ -75,7 +75,7 @@ func TestAccountByAddress(t *testing.T) { lastAddr = addr } assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalAccounts(), total) + assert.Equal(t, total, td.store.TotalAccounts()) }) t.Run("Non existing account", func(t *testing.T) { @@ -95,7 +95,7 @@ func TestAccountByAddress(t *testing.T) { acc, err := store.Account(lastAddr) assert.NoError(t, err) require.NotNil(t, acc) - assert.Equal(t, acc.Number(), total-1) + assert.Equal(t, total-1, acc.Number()) }) } @@ -140,5 +140,5 @@ func TestAccountDeepCopy(t *testing.T) { acc2, _ := td.store.Account(addr) acc2.AddToBalance(1) accCache, _ := td.store.accountStore.accCache.Get(addr) - assert.NotEqual(t, accCache.Hash(), acc2.Hash()) + assert.NotEqual(t, acc2.Hash(), accCache.Hash()) } diff --git a/store/block_test.go b/store/block_test.go index 61fdbcf2b..ea04a8378 100644 --- a/store/block_test.go +++ b/store/block_test.go @@ -27,14 +27,14 @@ func TestBlockStore(t *testing.T) { cBlk, err := td.store.Block(lastHeight + 1) assert.NoError(t, err) - assert.Equal(t, cBlk.Height, lastHeight+1) + assert.Equal(t, lastHeight+1, cBlk.Height) d, _ := nextBlk.Bytes() assert.True(t, bytes.Equal(cBlk.Data, d)) cert := td.store.LastCertificate() assert.NoError(t, err) - assert.Equal(t, cert.Hash(), nextCert.Hash()) + assert.Equal(t, nextCert.Hash(), cert.Hash()) }) } diff --git a/store/config_test.go b/store/config_test.go index eb974b32b..a25f2a03f 100644 --- a/store/config_test.go +++ b/store/config_test.go @@ -62,7 +62,7 @@ func TestConfigBasicCheck(t *testing.T) { tc.updateFn(conf) if tc.expectedErr != nil { err := conf.BasicCheck() - assert.ErrorIs(t, tc.expectedErr, err, + assert.ErrorIs(t, err, tc.expectedErr, "Expected error not matched for test %d-%s, expected: %s, got: %s", i, tc.name, tc.expectedErr, err) } else { err := conf.BasicCheck() @@ -78,8 +78,8 @@ func TestConfigStorePath(t *testing.T) { assert.NoError(t, conf.BasicCheck()) if runtime.GOOS != "windows" { - assert.Equal(t, conf.StorePath(), conf.Path+"/store.db") + assert.Equal(t, conf.Path+"/store.db", conf.StorePath()) } else { - assert.Equal(t, conf.StorePath(), conf.Path+"\\store.db") + assert.Equal(t, conf.Path+"\\store.db", conf.StorePath()) } } diff --git a/store/store_test.go b/store/store_test.go index fef48e803..7c14437ac 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -75,9 +75,9 @@ func TestBlockHash(t *testing.T) { sb, _ := td.store.Block(1) - assert.Equal(t, td.store.BlockHash(0), hash.UndefHash) - assert.Equal(t, td.store.BlockHash(util.MaxUint32), hash.UndefHash) - assert.Equal(t, td.store.BlockHash(1), sb.BlockHash) + assert.Equal(t, hash.UndefHash, td.store.BlockHash(0)) + assert.Equal(t, hash.UndefHash, td.store.BlockHash(util.MaxUint32)) + assert.Equal(t, sb.BlockHash, td.store.BlockHash(1)) } func TestBlockHeight(t *testing.T) { @@ -85,9 +85,9 @@ func TestBlockHeight(t *testing.T) { sb, _ := td.store.Block(1) - assert.Equal(t, td.store.BlockHeight(hash.UndefHash), uint32(0)) - assert.Equal(t, td.store.BlockHeight(td.RandHash()), uint32(0)) - assert.Equal(t, td.store.BlockHeight(sb.BlockHash), uint32(1)) + assert.Equal(t, uint32(0), td.store.BlockHeight(hash.UndefHash)) + assert.Equal(t, uint32(0), td.store.BlockHeight(td.RandHash())) + assert.Equal(t, uint32(1), td.store.BlockHeight(sb.BlockHash)) } func TestUnknownTransactionID(t *testing.T) { @@ -115,14 +115,14 @@ func TestRetrieveBlockAndTransactions(t *testing.T) { assert.NoError(t, err) assert.Equal(t, lastHeight, cBlk.Height) blk, _ := cBlk.ToBlock() - assert.Equal(t, blk.PrevCertificate().Height(), lastHeight-1) + assert.Equal(t, lastHeight-1, blk.PrevCertificate().Height()) for _, trx := range blk.Transactions() { committedTx, err := td.store.Transaction(trx.ID()) assert.NoError(t, err) - assert.Equal(t, blk.Header().UnixTime(), committedTx.BlockTime) - assert.Equal(t, trx.ID(), committedTx.TxID) - assert.Equal(t, lastHeight, committedTx.Height) + assert.Equal(t, committedTx.BlockTime, blk.Header().UnixTime()) + assert.Equal(t, committedTx.TxID, trx.ID()) + assert.Equal(t, committedTx.Height, lastHeight) trx2, _ := committedTx.ToTx() assert.Equal(t, trx.ID(), trx2.ID()) } @@ -140,9 +140,9 @@ func TestIndexingPublicKeys(t *testing.T) { assert.NoError(t, err) if addr.IsAccountAddress() { - assert.Equal(t, pubKey.AccountAddress(), addr) + assert.Equal(t, addr, pubKey.AccountAddress()) } else if addr.IsValidatorAddress() { - assert.Equal(t, pubKey.ValidatorAddress(), addr) + assert.Equal(t, addr, pubKey.ValidatorAddress()) } } }) diff --git a/store/validator_test.go b/store/validator_test.go index 8601bdf05..9890d4e9e 100644 --- a/store/validator_test.go +++ b/store/validator_test.go @@ -21,7 +21,7 @@ func TestValidatorCounter(t *testing.T) { td.store.UpdateValidator(val) assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalValidators(), int32(1)) + assert.Equal(t, int32(1), td.store.TotalValidators()) }) t.Run("Update validator, should not increase the total validators number", func(t *testing.T) { @@ -29,7 +29,7 @@ func TestValidatorCounter(t *testing.T) { td.store.UpdateValidator(val) assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalValidators(), int32(1)) + assert.Equal(t, int32(1), td.store.TotalValidators()) }) t.Run("Get validator", func(t *testing.T) { @@ -40,7 +40,7 @@ func TestValidatorCounter(t *testing.T) { assert.NoError(t, err) assert.Equal(t, val1.Hash(), val2.Hash()) - assert.Equal(t, td.store.TotalValidators(), int32(1)) + assert.Equal(t, int32(1), td.store.TotalValidators()) assert.True(t, td.store.HasValidator(val.Address())) }) } @@ -55,13 +55,13 @@ func TestValidatorBatchSaving(t *testing.T) { td.store.UpdateValidator(val) } assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalValidators(), total) + assert.Equal(t, total, td.store.TotalValidators()) }) t.Run("Close and load db", func(t *testing.T) { td.store.Close() store, _ := NewStore(td.store.config) - assert.Equal(t, store.TotalValidators(), total) + assert.Equal(t, total, store.TotalValidators()) }) } @@ -91,7 +91,7 @@ func TestValidatorByNumber(t *testing.T) { td.store.UpdateValidator(val) } assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalValidators(), total) + assert.Equal(t, total, td.store.TotalValidators()) }) t.Run("Get a random Validator", func(t *testing.T) { @@ -99,7 +99,7 @@ func TestValidatorByNumber(t *testing.T) { val, err := td.store.ValidatorByNumber(num) assert.NoError(t, err) require.NotNil(t, val) - assert.Equal(t, val.Number(), num) + assert.Equal(t, num, val.Number()) }) t.Run("Negative number", func(t *testing.T) { @@ -126,7 +126,7 @@ func TestValidatorByNumber(t *testing.T) { val, err := store.ValidatorByNumber(num) assert.NoError(t, err) require.NotNil(t, val) - assert.Equal(t, val.Number(), num) + assert.Equal(t, num, val.Number()) val, err = td.store.ValidatorByNumber(total + 1) assert.Error(t, err) @@ -144,7 +144,7 @@ func TestValidatorByAddress(t *testing.T) { td.store.UpdateValidator(val) } assert.NoError(t, td.store.WriteBatch()) - assert.Equal(t, td.store.TotalValidators(), total) + assert.Equal(t, total, td.store.TotalValidators()) }) t.Run("Get random validator", func(t *testing.T) { @@ -153,7 +153,7 @@ func TestValidatorByAddress(t *testing.T) { val, err := td.store.Validator(val0.Address()) assert.NoError(t, err) require.NotNil(t, val) - assert.Equal(t, val.Number(), num) + assert.Equal(t, num, val.Number()) }) t.Run("Unknown address", func(t *testing.T) { @@ -171,7 +171,7 @@ func TestValidatorByAddress(t *testing.T) { val, err := store.Validator(val0.Address()) assert.NoError(t, err) require.NotNil(t, val) - assert.Equal(t, val.Number(), num) + assert.Equal(t, num, val.Number()) }) } diff --git a/sync/bundle/message/block_announce_test.go b/sync/bundle/message/block_announce_test.go index d0948d1b8..95756e727 100644 --- a/sync/bundle/message/block_announce_test.go +++ b/sync/bundle/message/block_announce_test.go @@ -11,7 +11,7 @@ import ( func TestBlockAnnounceType(t *testing.T) { m := &BlockAnnounceMessage{} - assert.Equal(t, m.Type(), TypeBlockAnnounce) + assert.Equal(t, TypeBlockAnnounce, m.Type()) } func TestBlockAnnounceMessage(t *testing.T) { diff --git a/sync/bundle/message/blocks_request_test.go b/sync/bundle/message/blocks_request_test.go index 9bddf1bbf..764b94d6e 100644 --- a/sync/bundle/message/blocks_request_test.go +++ b/sync/bundle/message/blocks_request_test.go @@ -9,26 +9,26 @@ import ( func TestLatestBlocksRequestType(t *testing.T) { m := &BlocksRequestMessage{} - assert.Equal(t, m.Type(), TypeBlocksRequest) + assert.Equal(t, TypeBlocksRequest, m.Type()) } func TestBlocksRequestMessage(t *testing.T) { t.Run("Invalid height", func(t *testing.T) { m := NewBlocksRequestMessage(1, 0, 0) - assert.Equal(t, errors.Code(m.BasicCheck()), errors.ErrInvalidHeight) + assert.Equal(t, errors.ErrInvalidHeight, errors.Code(m.BasicCheck())) }) t.Run("Invalid count", func(t *testing.T) { m := NewBlocksRequestMessage(1, 200, 0) - assert.Equal(t, errors.Code(m.BasicCheck()), errors.ErrInvalidMessage) + assert.Equal(t, errors.ErrInvalidMessage, errors.Code(m.BasicCheck())) }) t.Run("OK", func(t *testing.T) { m := NewBlocksRequestMessage(1, 100, 7) assert.NoError(t, m.BasicCheck()) - assert.Equal(t, m.To(), uint32(106)) + assert.Equal(t, uint32(106), m.To()) assert.Contains(t, m.String(), "100") }) } diff --git a/sync/bundle/message/blocks_response_test.go b/sync/bundle/message/blocks_response_test.go index f7c94fe99..a1aa2ea7a 100644 --- a/sync/bundle/message/blocks_response_test.go +++ b/sync/bundle/message/blocks_response_test.go @@ -10,7 +10,7 @@ import ( func TestLatestBlocksResponseType(t *testing.T) { m := &BlocksResponseMessage{} - assert.Equal(t, m.Type(), TypeBlocksResponse) + assert.Equal(t, TypeBlocksResponse, m.Type()) } func TestBlocksResponseMessage(t *testing.T) { @@ -41,7 +41,7 @@ func TestBlocksResponseMessage(t *testing.T) { assert.NoError(t, m.BasicCheck()) assert.Contains(t, m.String(), "100") - assert.Equal(t, m.Reason, ResponseCodeMoreBlocks.String()) + assert.Equal(t, ResponseCodeMoreBlocks.String(), m.Reason) }) } @@ -57,7 +57,7 @@ func TestLatestBlocksResponseCode(t *testing.T) { assert.Zero(t, m.To()) assert.Zero(t, m.Count()) assert.True(t, m.IsRequestRejected()) - assert.Equal(t, m.Reason, reason) + assert.Equal(t, reason, m.Reason) }) t.Run("OK - MoreBlocks", func(t *testing.T) { @@ -70,11 +70,11 @@ func TestLatestBlocksResponseCode(t *testing.T) { m := NewBlocksResponseMessage(ResponseCodeMoreBlocks, reason, 1, 100, [][]byte{d1, d2}, nil) assert.NoError(t, m.BasicCheck()) - assert.Equal(t, m.From, uint32(100)) - assert.Equal(t, m.To(), uint32(101)) - assert.Equal(t, m.Count(), uint32(2)) + assert.Equal(t, uint32(100), m.From) + assert.Equal(t, uint32(101), m.To()) + assert.Equal(t, uint32(2), m.Count()) assert.False(t, m.IsRequestRejected()) - assert.Equal(t, m.Reason, reason) + assert.Equal(t, reason, m.Reason) }) t.Run("OK - Synced", func(t *testing.T) { @@ -85,10 +85,10 @@ func TestLatestBlocksResponseCode(t *testing.T) { m := NewBlocksResponseMessage(ResponseCodeSynced, reason, 1, 100, nil, cert) assert.NoError(t, m.BasicCheck()) - assert.Equal(t, m.From, uint32(100)) + assert.Equal(t, uint32(100), m.From) assert.Zero(t, m.To()) assert.Zero(t, m.Count()) assert.False(t, m.IsRequestRejected()) - assert.Equal(t, m.Reason, reason) + assert.Equal(t, reason, m.Reason) }) } diff --git a/sync/bundle/message/hello_ack_test.go b/sync/bundle/message/hello_ack_test.go index f923a2fd3..0b3d54662 100644 --- a/sync/bundle/message/hello_ack_test.go +++ b/sync/bundle/message/hello_ack_test.go @@ -8,7 +8,7 @@ import ( func TestHelloAckType(t *testing.T) { m := &HelloAckMessage{} - assert.Equal(t, m.Type(), TypeHelloAck) + assert.Equal(t, TypeHelloAck, m.Type()) } func TestHelloAckMessage(t *testing.T) { diff --git a/sync/bundle/message/hello_test.go b/sync/bundle/message/hello_test.go index d54571f98..d28f694a4 100644 --- a/sync/bundle/message/hello_test.go +++ b/sync/bundle/message/hello_test.go @@ -14,7 +14,7 @@ import ( func TestHelloType(t *testing.T) { m := &HelloMessage{} - assert.Equal(t, m.Type(), TypeHello) + assert.Equal(t, TypeHello, m.Type()) } func TestHelloMessage(t *testing.T) { @@ -37,7 +37,7 @@ func TestHelloMessage(t *testing.T) { m.Sign([]*bls.ValidatorKey{valKey}) m.Signature = nil - assert.Equal(t, errors.Code(m.BasicCheck()), errors.ErrInvalidSignature) + assert.Equal(t, errors.ErrInvalidSignature, errors.Code(m.BasicCheck())) }) t.Run("PublicKeys are empty", func(t *testing.T) { @@ -47,7 +47,7 @@ func TestHelloMessage(t *testing.T) { m.Sign([]*bls.ValidatorKey{valKey}) m.PublicKeys = make([]*bls.PublicKey, 0) - assert.Equal(t, errors.Code(m.BasicCheck()), errors.ErrInvalidPublicKey) + assert.Equal(t, errors.ErrInvalidPublicKey, errors.Code(m.BasicCheck())) }) t.Run("MyTimeUnixMilli of time1 is less or equal than hello message time", func(t *testing.T) { diff --git a/sync/bundle/message/proposal_test.go b/sync/bundle/message/proposal_test.go index 20b68dd40..149bbcaef 100644 --- a/sync/bundle/message/proposal_test.go +++ b/sync/bundle/message/proposal_test.go @@ -9,7 +9,7 @@ import ( func TestProposalType(t *testing.T) { m := &ProposalMessage{} - assert.Equal(t, m.Type(), TypeProposal) + assert.Equal(t, TypeProposal, m.Type()) } func TestProposalMessage(t *testing.T) { diff --git a/sync/bundle/message/query_proposal_test.go b/sync/bundle/message/query_proposal_test.go index 9b3b16bee..733c33f2d 100644 --- a/sync/bundle/message/query_proposal_test.go +++ b/sync/bundle/message/query_proposal_test.go @@ -10,7 +10,7 @@ import ( func TestQueryProposalType(t *testing.T) { m := &QueryProposalMessage{} - assert.Equal(t, m.Type(), TypeQueryProposal) + assert.Equal(t, TypeQueryProposal, m.Type()) } func TestQueryProposalMessage(t *testing.T) { @@ -19,7 +19,7 @@ func TestQueryProposalMessage(t *testing.T) { t.Run("Invalid round", func(t *testing.T) { m := NewQueryProposalMessage(0, -1, ts.RandValAddress()) - assert.Equal(t, errors.Code(m.BasicCheck()), errors.ErrInvalidRound) + assert.Equal(t, errors.ErrInvalidRound, errors.Code(m.BasicCheck())) }) t.Run("OK", func(t *testing.T) { diff --git a/sync/bundle/message/query_votes_test.go b/sync/bundle/message/query_votes_test.go index af08e95b8..4e9757306 100644 --- a/sync/bundle/message/query_votes_test.go +++ b/sync/bundle/message/query_votes_test.go @@ -10,7 +10,7 @@ import ( func TestQueryVotesType(t *testing.T) { m := &QueryVotesMessage{} - assert.Equal(t, m.Type(), TypeQueryVote) + assert.Equal(t, TypeQueryVote, m.Type()) } func TestQueryVotesMessage(t *testing.T) { @@ -19,7 +19,7 @@ func TestQueryVotesMessage(t *testing.T) { t.Run("Invalid round", func(t *testing.T) { m := NewQueryVotesMessage(0, -1, ts.RandValAddress()) - assert.Equal(t, errors.Code(m.BasicCheck()), errors.ErrInvalidRound) + assert.Equal(t, errors.ErrInvalidRound, errors.Code(m.BasicCheck())) }) t.Run("OK", func(t *testing.T) { diff --git a/sync/bundle/message/transactions_test.go b/sync/bundle/message/transactions_test.go index afecda609..b13f2ccaa 100644 --- a/sync/bundle/message/transactions_test.go +++ b/sync/bundle/message/transactions_test.go @@ -11,7 +11,7 @@ import ( func TestTransactionsType(t *testing.T) { m := &TransactionsMessage{} - assert.Equal(t, m.Type(), TypeTransaction) + assert.Equal(t, TypeTransaction, m.Type()) } func TestTransactionsMessage(t *testing.T) { @@ -20,7 +20,7 @@ func TestTransactionsMessage(t *testing.T) { t.Run("No transactions", func(t *testing.T) { m := NewTransactionsMessage(nil) - assert.Equal(t, errors.Code(m.BasicCheck()), errors.ErrInvalidMessage) + assert.Equal(t, errors.ErrInvalidMessage, errors.Code(m.BasicCheck())) }) t.Run("OK", func(t *testing.T) { diff --git a/sync/bundle/message/vote_test.go b/sync/bundle/message/vote_test.go index 9c5441dd1..5ed86c7e5 100644 --- a/sync/bundle/message/vote_test.go +++ b/sync/bundle/message/vote_test.go @@ -10,7 +10,7 @@ import ( func TestVoteType(t *testing.T) { m := &VoteMessage{} - assert.Equal(t, m.Type(), TypeVote) + assert.Equal(t, TypeVote, m.Type()) } func TestVoteMessage(t *testing.T) { diff --git a/sync/cache/cache_test.go b/sync/cache/cache_test.go index 715454cb4..f167c2065 100644 --- a/sync/cache/cache_test.go +++ b/sync/cache/cache_test.go @@ -51,9 +51,9 @@ func TestClearCache(t *testing.T) { blk, _ := ts.GenerateTestBlock(ts.RandHeight()) cache.AddBlock(blk) - assert.Equal(t, cache.Len(), 1) + assert.Equal(t, 1, cache.Len()) cache.Clear() - assert.Equal(t, cache.Len(), 0) + assert.Equal(t, 0, cache.Len()) assert.Nil(t, cache.GetBlock(2)) } diff --git a/sync/handler_block_announce_test.go b/sync/handler_block_announce_test.go index 8f929b66b..cbbd1efe2 100644 --- a/sync/handler_block_announce_test.go +++ b/sync/handler_block_announce_test.go @@ -32,7 +32,7 @@ func TestParsingBlockAnnounceMessages(t *testing.T) { t.Run("Receiving missed block, should commit both blocks", func(t *testing.T) { td.receivingNewMessage(td.sync, msg1, pid) - assert.Equal(t, td.sync.state.LastBlockHeight(), lastHeight+2) + assert.Equal(t, lastHeight+2, td.sync.state.LastBlockHeight()) }) } @@ -44,7 +44,7 @@ func TestBroadcastingBlockAnnounceMessages(t *testing.T) { td.sync.broadcast(msg) msg1 := td.shouldPublishMessageWithThisType(t, message.TypeBlockAnnounce) - assert.Equal(t, msg1.Message.(*message.BlockAnnounceMessage).Certificate.Height(), msg.Certificate.Height()) + assert.Equal(t, msg.Certificate.Height(), msg1.Message.(*message.BlockAnnounceMessage).Certificate.Height()) } func TestCacheAnnouncedBlock(t *testing.T) { @@ -61,6 +61,6 @@ func TestCacheAnnouncedBlock(t *testing.T) { cachedBlock := td.sync.cache.GetBlock(height) cachedCert := td.sync.cache.GetCertificate(height) - assert.Equal(t, cachedBlock, blk1) - assert.Equal(t, cachedCert, cert1) + assert.Equal(t, blk1, cachedBlock) + assert.Equal(t, cert1, cachedCert) } diff --git a/sync/handler_blocks_request_test.go b/sync/handler_blocks_request_test.go index b36b12d3d..c810140a3 100644 --- a/sync/handler_blocks_request_test.go +++ b/sync/handler_blocks_request_test.go @@ -30,7 +30,7 @@ func TestBlocksRequestMessages(t *testing.T) { assert.Equal(t, message.ResponseCodeRejected, res.ResponseCode) assert.Contains(t, res.Reason, "unknown peer") assert.Zero(t, res.From) - assert.Equal(t, res.SessionID, sid) + assert.Equal(t, sid, res.SessionID) }) t.Run("Reject request from peers without handshaking", func(t *testing.T) { @@ -73,14 +73,14 @@ func TestBlocksRequestMessages(t *testing.T) { bdl1 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res1 := bdl1.Message.(*message.BlocksResponseMessage) - assert.Equal(t, res1.ResponseCode, message.ResponseCodeMoreBlocks) - assert.Equal(t, res1.From, curHeight-config.BlockPerMessage) - assert.Equal(t, res1.To(), curHeight-1) - assert.Equal(t, res1.Count(), config.BlockPerMessage) + assert.Equal(t, message.ResponseCodeMoreBlocks, res1.ResponseCode) + assert.Equal(t, curHeight-config.BlockPerMessage, res1.From) + assert.Equal(t, curHeight-1, res1.To()) + assert.Equal(t, config.BlockPerMessage, res1.Count()) bdl2 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res2 := bdl2.Message.(*message.BlocksResponseMessage) - assert.Equal(t, res2.ResponseCode, message.ResponseCodeNoMoreBlocks) + assert.Equal(t, message.ResponseCodeNoMoreBlocks, res2.ResponseCode) assert.Zero(t, res2.From) assert.Zero(t, res2.To()) assert.Zero(t, res2.Count()) @@ -92,15 +92,15 @@ func TestBlocksRequestMessages(t *testing.T) { bdl1 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res1 := bdl1.Message.(*message.BlocksResponseMessage) - assert.Equal(t, res1.ResponseCode, message.ResponseCodeMoreBlocks) - assert.Equal(t, res1.From, curHeight-config.BlockPerMessage+1) - assert.Equal(t, res1.To(), curHeight) - assert.Equal(t, res1.Count(), config.BlockPerMessage) + assert.Equal(t, message.ResponseCodeMoreBlocks, res1.ResponseCode) + assert.Equal(t, curHeight-config.BlockPerMessage+1, res1.From) + assert.Equal(t, curHeight, res1.To()) + assert.Equal(t, config.BlockPerMessage, res1.Count()) bdl2 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) res2 := bdl2.Message.(*message.BlocksResponseMessage) - assert.Equal(t, res2.ResponseCode, message.ResponseCodeSynced) - assert.Equal(t, res2.From, curHeight) + assert.Equal(t, message.ResponseCodeSynced, res2.ResponseCode) + assert.Equal(t, curHeight, res2.From) assert.Zero(t, res2.To()) assert.Zero(t, res2.Count()) }) @@ -122,10 +122,10 @@ func TestBlocksRequestMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) msg1 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) - assert.Equal(t, msg1.Message.(*message.BlocksResponseMessage).ResponseCode, message.ResponseCodeMoreBlocks) + assert.Equal(t, message.ResponseCodeMoreBlocks, msg1.Message.(*message.BlocksResponseMessage).ResponseCode) msg2 := td.shouldPublishMessageWithThisType(t, message.TypeBlocksResponse) - assert.Equal(t, msg2.Message.(*message.BlocksResponseMessage).ResponseCode, message.ResponseCodeNoMoreBlocks) + assert.Equal(t, message.ResponseCodeNoMoreBlocks, msg2.Message.(*message.BlocksResponseMessage).ResponseCode) }) }) } diff --git a/sync/handler_blocks_response_test.go b/sync/handler_blocks_response_test.go index 6e43f8990..0764dff92 100644 --- a/sync/handler_blocks_response_test.go +++ b/sync/handler_blocks_response_test.go @@ -61,7 +61,7 @@ func TestOneBlockShorter(t *testing.T) { lastHeight+1, [][]byte{d1}, cert1) td.receivingNewMessage(td.sync, msg, pid) - assert.Equal(t, td.state.LastBlockHeight(), lastHeight+1) + assert.Equal(t, lastHeight+1, td.state.LastBlockHeight()) } func TestStrippedPublicKey(t *testing.T) { @@ -140,9 +140,9 @@ func shouldPublishBlockResponse(t *testing.T, net *network.MockNetwork, bdl := shouldPublishMessageWithThisType(t, net, message.TypeBlocksResponse) msg := bdl.Message.(*message.BlocksResponseMessage) - require.Equal(t, from, msg.From) - require.Equal(t, count, msg.Count()) - require.Equal(t, code, msg.ResponseCode) + require.Equal(t, msg.From, from) + require.Equal(t, msg.Count(), count) + require.Equal(t, msg.ResponseCode, code) } type networkAliceBob struct { diff --git a/sync/handler_hello_test.go b/sync/handler_hello_test.go index 50c47bea7..841f1c66e 100644 --- a/sync/handler_hello_test.go +++ b/sync/handler_hello_test.go @@ -30,7 +30,7 @@ func TestParsingHelloMessages(t *testing.T) { from := td.RandPeerID() td.receivingNewMessage(td.sync, msg, from) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) - assert.Equal(t, bdl.Message.(*message.HelloAckMessage).ResponseCode, message.ResponseCodeRejected) + assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Receiving Hello message from a peer. Genesis hash is wrong.", @@ -45,7 +45,7 @@ func TestParsingHelloMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) - assert.Equal(t, bdl.Message.(*message.HelloAckMessage).ResponseCode, message.ResponseCodeRejected) + assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Receiving a Hello message from a peer. The time difference is greater than or equal to -10", @@ -60,7 +60,7 @@ func TestParsingHelloMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) - assert.Equal(t, bdl.Message.(*message.HelloAckMessage).ResponseCode, message.ResponseCodeRejected) + assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Receiving Hello message from a peer. Difference is less or equal than 20 seconds.", @@ -75,7 +75,7 @@ func TestParsingHelloMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) - assert.Equal(t, bdl.Message.(*message.HelloAckMessage).ResponseCode, message.ResponseCodeRejected) + assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Non supporting version.", @@ -96,7 +96,7 @@ func TestParsingHelloMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) - assert.Equal(t, bdl.Message.(*message.HelloAckMessage).ResponseCode, message.ResponseCodeRejected) + assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Invalid agent.", @@ -111,7 +111,7 @@ func TestParsingHelloMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) td.checkPeerStatus(t, pid, status.StatusBanned) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) - assert.Equal(t, bdl.Message.(*message.HelloAckMessage).ResponseCode, message.ResponseCodeRejected) + assert.Equal(t, message.ResponseCodeRejected, bdl.Message.(*message.HelloAckMessage).ResponseCode) }) t.Run("Receiving Hello message from a peer. It should be acknowledged and updates the peer info", @@ -126,18 +126,18 @@ func TestParsingHelloMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeHelloAck) - assert.Equal(t, bdl.Message.(*message.HelloAckMessage).ResponseCode, message.ResponseCodeOK) + assert.Equal(t, message.ResponseCodeOK, bdl.Message.(*message.HelloAckMessage).ResponseCode) // Check if the peer info is updated p := td.sync.peerSet.GetPeer(pid) pub := valKey.PublicKey() - assert.Equal(t, p.Status, status.StatusConnected) - assert.Equal(t, p.Agent, version.NodeAgent.String()) - assert.Equal(t, p.Moniker, "kitty") + assert.Equal(t, status.StatusConnected, p.Status) + assert.Equal(t, version.NodeAgent.String(), p.Agent) + assert.Equal(t, "kitty", p.Moniker) assert.Contains(t, p.ConsensusKeys, pub) - assert.Equal(t, p.PeerID, pid) - assert.Equal(t, p.Height, peerHeight) + assert.Equal(t, pid, p.PeerID) + assert.Equal(t, peerHeight, p.Height) assert.True(t, p.IsFullNode()) }) } diff --git a/sync/handler_query_proposal_test.go b/sync/handler_query_proposal_test.go index 1a16dc632..08d5e7900 100644 --- a/sync/handler_query_proposal_test.go +++ b/sync/handler_query_proposal_test.go @@ -52,7 +52,7 @@ func TestParsingQueryProposalMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeProposal) - assert.Equal(t, bdl.Message.(*message.ProposalMessage).Proposal.Hash(), prop.Hash()) + assert.Equal(t, prop.Hash(), bdl.Message.(*message.ProposalMessage).Proposal.Hash()) }) t.Run("doesn't have the proposal", func(t *testing.T) { diff --git a/sync/handler_query_votes_test.go b/sync/handler_query_votes_test.go index 508a50c8f..ef6c773ff 100644 --- a/sync/handler_query_votes_test.go +++ b/sync/handler_query_votes_test.go @@ -29,7 +29,7 @@ func TestParsingQueryVotesMessages(t *testing.T) { td.receivingNewMessage(td.sync, msg, pid) bdl := td.shouldPublishMessageWithThisType(t, message.TypeVote) - assert.Equal(t, bdl.Message.(*message.VoteMessage).Vote.Hash(), v1.Hash()) + assert.Equal(t, v1.Hash(), bdl.Message.(*message.VoteMessage).Vote.Hash()) }) t.Run("doesn't have any votes", func(t *testing.T) { diff --git a/sync/handler_vote_test.go b/sync/handler_vote_test.go index 63211add3..7b228e1b3 100644 --- a/sync/handler_vote_test.go +++ b/sync/handler_vote_test.go @@ -16,6 +16,6 @@ func TestParsingVoteMessages(t *testing.T) { pid := td.RandPeerID() td.receivingNewMessage(td.sync, msg, pid) - assert.Equal(t, td.consMgr.PickRandomVote(0).Hash(), v.Hash()) + assert.Equal(t, v.Hash(), td.consMgr.PickRandomVote(0).Hash()) }) } diff --git a/sync/peerset/peer/service/services_test.go b/sync/peerset/peer/service/services_test.go index 5ea288e9a..1b41f1e6b 100644 --- a/sync/peerset/peer/service/services_test.go +++ b/sync/peerset/peer/service/services_test.go @@ -7,12 +7,12 @@ import ( ) func TestServicesString(t *testing.T) { - assert.Equal(t, New(None).String(), "") - assert.Equal(t, New(FullNode).String(), "FULL") - assert.Equal(t, New(PrunedNode).String(), "PRUNED") - assert.Equal(t, New(FullNode, PrunedNode).String(), "FULL | PRUNED") - assert.Equal(t, New(5).String(), "FULL | 4") - assert.Equal(t, New(6).String(), "PRUNED | 4") + assert.Equal(t, "", New(None).String()) + assert.Equal(t, "FULL", New(FullNode).String()) + assert.Equal(t, "PRUNED", New(PrunedNode).String()) + assert.Equal(t, "FULL | PRUNED", New(FullNode, PrunedNode).String()) + assert.Equal(t, "FULL | 4", New(5).String()) + assert.Equal(t, "PRUNED | 4", New(6).String()) } func TestAppend(t *testing.T) { diff --git a/sync/peerset/peer_set_test.go b/sync/peerset/peer_set_test.go index 3091f54b4..941131307 100644 --- a/sync/peerset/peer_set_test.go +++ b/sync/peerset/peer_set_test.go @@ -99,20 +99,20 @@ func TestPeerSet(t *testing.T) { sentBytes := make(map[message.Type]int64) sentBytes[message.TypeBlocksRequest] = 450 - assert.Equal(t, peer1.InvalidBundles, 1) - assert.Equal(t, peer1.ReceivedBundles, 1) - assert.Equal(t, peer1.ReceivedBytes[message.TypeBlocksResponse], int64(100)) - assert.Equal(t, peer1.ReceivedBytes[message.TypeTransaction], int64(150)) - assert.Equal(t, peer1.SentBytes[message.TypeBlocksRequest], int64(250)) - - assert.Equal(t, peerSet.TotalReceivedBytes(), int64(250)) - assert.Equal(t, peerSet.ReceivedBytesMessageType(message.TypeBlocksResponse), int64(100)) - assert.Equal(t, peerSet.ReceivedBytesMessageType(message.TypeTransaction), int64(150)) - assert.Equal(t, peerSet.ReceivedBytes(), receivedBytes) - assert.Equal(t, peerSet.TotalSentBytes(), int64(450)) - assert.Equal(t, peerSet.SentBytesMessageType(message.TypeBlocksRequest), int64(450)) - assert.Equal(t, peerSet.SentBytes(), sentBytes) - assert.Equal(t, peerSet.TotalSentBundles(), 2) + assert.Equal(t, 1, peer1.InvalidBundles) + assert.Equal(t, 1, peer1.ReceivedBundles) + assert.Equal(t, int64(100), peer1.ReceivedBytes[message.TypeBlocksResponse]) + assert.Equal(t, int64(150), peer1.ReceivedBytes[message.TypeTransaction]) + assert.Equal(t, int64(250), peer1.SentBytes[message.TypeBlocksRequest]) + + assert.Equal(t, int64(250), peerSet.TotalReceivedBytes()) + assert.Equal(t, int64(100), peerSet.ReceivedBytesMessageType(message.TypeBlocksResponse)) + assert.Equal(t, int64(150), peerSet.ReceivedBytesMessageType(message.TypeTransaction)) + assert.Equal(t, receivedBytes, peerSet.ReceivedBytes()) + assert.Equal(t, int64(450), peerSet.TotalSentBytes()) + assert.Equal(t, int64(450), peerSet.SentBytesMessageType(message.TypeBlocksRequest)) + assert.Equal(t, sentBytes, peerSet.SentBytes()) + assert.Equal(t, 2, peerSet.TotalSentBundles()) }) t.Run("Testing UpdateHeight", func(t *testing.T) { @@ -129,7 +129,7 @@ func TestPeerSet(t *testing.T) { peerSet.UpdateStatus(pid1, status.StatusBanned) peer1 := peerSet.findPeer(pid1) - assert.Equal(t, peer1.Status, status.StatusBanned) + assert.Equal(t, status.StatusBanned, peer1.Status) }) t.Run("Testing UpdateLastSent", func(t *testing.T) { @@ -154,10 +154,10 @@ func TestPeerSet(t *testing.T) { t.Run("Testing RemovePeer", func(t *testing.T) { peerSet.RemovePeer(ts.RandPeerID()) - assert.Equal(t, peerSet.Len(), 3) + assert.Equal(t, 3, peerSet.Len()) peerSet.RemovePeer(pid2) - assert.Equal(t, peerSet.Len(), 2) + assert.Equal(t, 2, peerSet.Len()) }) } @@ -181,8 +181,8 @@ func TestOpenSession(t *testing.T) { assert.Equal(t, pid1, ssn1.PeerID) assert.Equal(t, session.Open, ssn1.Status) assert.LessOrEqual(t, ssn1.LastActivity, time.Now()) - assert.Equal(t, sid1, 0) - assert.Equal(t, sid2, 1) + assert.Equal(t, 0, sid1) + assert.Equal(t, 1, sid2) assert.True(t, ps.HasOpenSession(pid1)) assert.True(t, ps.HasOpenSession(pid2)) assert.False(t, ps.HasOpenSession(ts.RandPeerID())) @@ -376,5 +376,5 @@ func TestUpdateProtocols(t *testing.T) { ps.UpdateProtocols(pid, protocols) p := ps.GetPeer(pid) - assert.Equal(t, p.Protocols, protocols) + assert.Equal(t, protocols, p.Protocols) } diff --git a/sync/sync_test.go b/sync/sync_test.go index 553f12f67..d524e1f5d 100644 --- a/sync/sync_test.go +++ b/sync/sync_test.go @@ -93,7 +93,7 @@ func setup(t *testing.T, config *Config) *testData { } assert.NoError(t, td.sync.Start()) - assert.Equal(t, td.sync.Moniker(), config.Moniker) + assert.Equal(t, config.Moniker, td.sync.Moniker()) logger.Info("setup finished, running the tests", "name", t.Name()) @@ -222,7 +222,7 @@ func (td *testData) addValidatorToCommittee(t *testing.T, pub crypto.PublicKey) func (td *testData) checkPeerStatus(t *testing.T, pid peer.ID, code status.Status) { t.Helper() - require.Equal(t, td.sync.peerSet.GetPeerStatus(pid), code) + require.Equal(t, code, td.sync.peerSet.GetPeerStatus(pid)) } func TestStop(t *testing.T) { @@ -254,7 +254,7 @@ func TestConnectEvent(t *testing.T) { if p == nil { return false } - assert.Equal(t, p.Address, "/ip4/2.2.2.2/tcp/21888") + assert.Equal(t, "/ip4/2.2.2.2/tcp/21888", p.Address) return p.Status == status.StatusConnected }, time.Second, 100*time.Millisecond) diff --git a/tests/account_test.go b/tests/account_test.go index 8593cdea6..7f45f72be 100644 --- a/tests/account_test.go +++ b/tests/account_test.go @@ -24,5 +24,5 @@ func getAccount(t *testing.T, addr crypto.Address) *pactus.AccountInfo { func TestGetAccount(t *testing.T) { acc := getAccount(t, crypto.TreasuryAddress) require.NotNil(t, acc) - assert.Equal(t, acc.Number, int32(0)) + assert.Equal(t, int32(0), acc.Number) } diff --git a/tests/transaction_test.go b/tests/transaction_test.go index 6dcc38b03..66938236f 100644 --- a/tests/transaction_test.go +++ b/tests/transaction_test.go @@ -117,8 +117,8 @@ func TestTransactions(t *testing.T) { require.NotNil(t, accCarol) require.NotNil(t, accDave) - assert.Equal(t, accAlice.Balance, int64(80000000-50005000)) - assert.Equal(t, accBob.Balance, int64(50000000-2011)) - assert.Equal(t, accCarol.Balance, int64(10)) - assert.Equal(t, accDave.Balance, int64(1)) + assert.Equal(t, int64(80000000-50005000), accAlice.Balance) + assert.Equal(t, int64(50000000-2011), accBob.Balance) + assert.Equal(t, int64(10), accCarol.Balance) + assert.Equal(t, int64(1), accDave.Balance) } diff --git a/tests/validator_test.go b/tests/validator_test.go index de47a89ec..3020d7d6d 100644 --- a/tests/validator_test.go +++ b/tests/validator_test.go @@ -24,5 +24,5 @@ func getValidator(t *testing.T, addr crypto.Address) *pactus.ValidatorInfo { func TestGetValidator(t *testing.T) { val := getValidator(t, tValKeys[tNodeIdx2][0].Address()) require.NotNil(t, val) - assert.Equal(t, val.Number, int32(1)) + assert.Equal(t, int32(1), val.Number) } diff --git a/txpool/txpool_test.go b/txpool/txpool_test.go index f430e48f5..c9eff5e24 100644 --- a/txpool/txpool_test.go +++ b/txpool/txpool_test.go @@ -70,7 +70,7 @@ func (td *testData) shouldPublishTransaction(t *testing.T, id tx.ID) { if msg.Type() == message.TypeTransaction { m := msg.(*message.TransactionsMessage) - assert.Equal(t, m.Transactions[0].ID(), id) + assert.Equal(t, id, m.Transactions[0].ID()) return } @@ -118,7 +118,7 @@ func TestFullPool(t *testing.T) { td.sandbox.UpdateAccount(senderAddr, senderAcc) // Make sure the pool is empty - assert.Equal(t, td.pool.Size(), 0) + assert.Equal(t, 0, td.pool.Size()) for i := 0; i < len(trxs); i++ { trx := tx.NewTransferTx(randHeight+1, senderAddr, @@ -130,7 +130,7 @@ func TestFullPool(t *testing.T) { assert.False(t, td.pool.HasTx(trxs[0].ID())) assert.True(t, td.pool.HasTx(trxs[1].ID())) - assert.Equal(t, td.pool.Size(), td.pool.config.transferPoolSize()) + assert.Equal(t, td.pool.config.transferPoolSize(), td.pool.Size()) } func TestEmptyPool(t *testing.T) { @@ -190,11 +190,11 @@ func TestPrepareBlockTransactions(t *testing.T) { trxs := td.pool.PrepareBlockTransactions() assert.Len(t, trxs, 5) - assert.Equal(t, trxs[0].ID(), sortitionTx.ID()) - assert.Equal(t, trxs[1].ID(), bondTx.ID()) - assert.Equal(t, trxs[2].ID(), unbondTx.ID()) - assert.Equal(t, trxs[3].ID(), withdrawTx.ID()) - assert.Equal(t, trxs[4].ID(), transferTx.ID()) + assert.Equal(t, sortitionTx.ID(), trxs[0].ID()) + assert.Equal(t, bondTx.ID(), trxs[1].ID()) + assert.Equal(t, unbondTx.ID(), trxs[2].ID()) + assert.Equal(t, withdrawTx.ID(), trxs[3].ID()) + assert.Equal(t, transferTx.ID(), trxs[4].ID()) } func TestAppendAndBroadcast(t *testing.T) { diff --git a/types/account/account_test.go b/types/account/account_test.go index 0dd3e75d8..260d445f2 100644 --- a/types/account/account_test.go +++ b/types/account/account_test.go @@ -18,7 +18,7 @@ func TestFromBytes(t *testing.T) { acc, _ := ts.GenerateTestAccount(ts.RandInt32(10000)) bs, err := acc.Bytes() require.NoError(t, err) - require.Equal(t, acc.SerializeSize(), len(bs)) + require.Equal(t, len(bs), acc.SerializeSize()) acc2, err := account.FromBytes(bs) require.NoError(t, err) assert.Equal(t, acc, acc2) @@ -34,14 +34,14 @@ func TestDecoding(t *testing.T) { acc, err := account.FromBytes(d) require.NoError(t, err) - assert.Equal(t, acc.Number(), int32(1)) - assert.Equal(t, acc.Balance(), amount.Amount(2)) + assert.Equal(t, int32(1), acc.Number()) + assert.Equal(t, amount.Amount(2), acc.Balance()) d2, _ := acc.Bytes() assert.Equal(t, d, d2) - assert.Equal(t, acc.Hash(), hash.CalcHash(d)) + assert.Equal(t, hash.CalcHash(d), acc.Hash()) expected, _ := hash.FromString("c3b75f08e64a66cb980fdc03c3a0b78635a7b1db049096e8bbbd9a2873f3071a") - assert.Equal(t, acc.Hash(), expected) - assert.Equal(t, acc.SerializeSize(), len(d)) + assert.Equal(t, expected, acc.Hash()) + assert.Equal(t, len(d), acc.SerializeSize()) } func TestAddToBalance(t *testing.T) { @@ -50,7 +50,7 @@ func TestAddToBalance(t *testing.T) { acc, _ := ts.GenerateTestAccount(100) bal := acc.Balance() acc.AddToBalance(1) - assert.Equal(t, acc.Balance(), bal+1) + assert.Equal(t, bal+1, acc.Balance()) } func TestSubtractFromBalance(t *testing.T) { @@ -59,7 +59,7 @@ func TestSubtractFromBalance(t *testing.T) { acc, _ := ts.GenerateTestAccount(100) bal := acc.Balance() acc.SubtractFromBalance(1) - assert.Equal(t, acc.Balance(), bal-1) + assert.Equal(t, bal-1, acc.Balance()) } func TestClone(t *testing.T) { diff --git a/types/amount/amount_test.go b/types/amount/amount_test.go index 8eca21c16..a1f926c0f 100644 --- a/types/amount/amount_test.go +++ b/types/amount/amount_test.go @@ -106,7 +106,7 @@ func TestAmountCreation(t *testing.T) { "%v: Negative test Amount creation succeeded (value %v) when should fail", test.name, amt) } - assert.Equal(t, amt, test.expected, + assert.Equal(t, test.expected, amt, "%v: Created amount %v does not match expected %v", test.name, amt, test.expected) } } @@ -193,11 +193,11 @@ func TestAmountUnitConversions(t *testing.T) { for _, test := range tests { f := test.amount.ToUnit(test.unit) - assert.Equal(t, f, test.converted, + assert.Equal(t, test.converted, f, "%v: converted value %v does not match expected %v", test.name, f, test.converted) str := test.amount.Format(test.unit) - assert.Equal(t, str, test.str, + assert.Equal(t, test.str, str, "%v: format '%v' does not match expected '%v'", test.name, str, test.str) // Verify that Amount.ToPAC works as advertised. @@ -346,9 +346,9 @@ func TestCoinToChangeConversion(t *testing.T) { amt, err := amount.FromString(test.amount) if test.parsErr == nil { assert.NoError(t, err) - assert.Equal(t, amt.ToNanoPAC(), test.NanoPac) - assert.Equal(t, amt.ToPAC(), test.PAC) - assert.Equal(t, amt.String(), test.str) + assert.Equal(t, test.NanoPac, amt.ToNanoPAC()) + assert.Equal(t, test.PAC, amt.ToPAC()) + assert.Equal(t, test.str, amt.String()) } else { assert.ErrorIs(t, err, test.parsErr) } diff --git a/types/block/block_test.go b/types/block/block_test.go index 5d0006303..cfbaf4ced 100644 --- a/types/block/block_test.go +++ b/types/block/block_test.go @@ -210,7 +210,7 @@ func TestBasicCheck(t *testing.T) { b, _ := block.FromBytes(d) assert.NoError(t, b.BasicCheck()) assert.Zero(t, b.Header().UnixTime()) - assert.Equal(t, b.Header().Version(), uint8(1)) + assert.Equal(t, uint8(1), b.Header().Version()) }) } @@ -301,7 +301,7 @@ func TestBlockHash(t *testing.T) { b, err := block.FromBytes(d) assert.NoError(t, err) - assert.Equal(t, b.SerializeSize(), len(d)) + assert.Equal(t, len(d), b.SerializeSize()) d2, _ := b.Bytes() assert.Equal(t, d, d2) @@ -324,8 +324,8 @@ func TestBlockHash(t *testing.T) { expected1 := hash.CalcHash(hashData) expected2, _ := hash.FromString("43399fa59adcfb7d8c515460ec9ca27b6a1cb865f5b7d9bde8fe56c18eaec9ab") - assert.Equal(t, b.Hash(), expected1) - assert.Equal(t, b.Hash(), expected2) + assert.Equal(t, expected1, b.Hash()) + assert.Equal(t, expected2, b.Hash()) } func TestMakeBlock(t *testing.T) { diff --git a/types/block/txs_test.go b/types/block/txs_test.go index b1f1989ce..fb37994d2 100644 --- a/types/block/txs_test.go +++ b/types/block/txs_test.go @@ -17,14 +17,14 @@ func TestTxsMerkle(t *testing.T) { trx2 := ts.GenerateTestTransferTx() txs.Append(trx1) merkle := txs.Root() - assert.Equal(t, merkle, trx1.ID()) + assert.Equal(t, trx1.ID(), merkle) txs.Append(trx2) merkle = txs.Root() data := make([]byte, 64) copy(data[:32], trx1.ID().Bytes()) copy(data[32:], trx2.ID().Bytes()) - assert.Equal(t, merkle, hash.CalcHash(data)) + assert.Equal(t, hash.CalcHash(data), merkle) } func TestAppendPrependRemove(t *testing.T) { @@ -43,7 +43,7 @@ func TestAppendPrependRemove(t *testing.T) { txs.Append(trx4) txs.Remove(3) - assert.Equal(t, txs, block.Txs{trx1, trx2, trx3, trx4}) + assert.Equal(t, block.Txs{trx1, trx2, trx3, trx4}, txs) } func TestIsEmpty(t *testing.T) { diff --git a/types/certificate/block_certificate_test.go b/types/certificate/block_certificate_test.go index aa8a55cf4..6b3b1c62f 100644 --- a/types/certificate/block_certificate_test.go +++ b/types/certificate/block_certificate_test.go @@ -29,11 +29,11 @@ func TestBlockCertificate(t *testing.T) { cert := new(certificate.BlockCertificate) err := cert.Decode(r) assert.NoError(t, err) - assert.Equal(t, cert.Height(), uint32(0x01020304)) - assert.Equal(t, cert.Round(), int16(0x0001)) - assert.Equal(t, cert.Committers(), []int32{1, 2, 3, 4, 5, 6}) - assert.Equal(t, cert.Absentees(), []int32{2}) - assert.Equal(t, cert.Hash(), certHash) + assert.Equal(t, uint32(0x01020304), cert.Height()) + assert.Equal(t, int16(0x0001), cert.Round()) + assert.Equal(t, []int32{1, 2, 3, 4, 5, 6}, cert.Committers()) + assert.Equal(t, []int32{2}, cert.Absentees()) + assert.Equal(t, certHash, cert.Hash()) blockHash, _ := hash.FromString("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") expectedSignByte, _ := hex.DecodeString( diff --git a/types/certificate/vote_certificate_test.go b/types/certificate/vote_certificate_test.go index 9ee605e56..061f35b74 100644 --- a/types/certificate/vote_certificate_test.go +++ b/types/certificate/vote_certificate_test.go @@ -30,11 +30,11 @@ func TestVoteCertificate(t *testing.T) { cert := new(certificate.VoteCertificate) err := cert.Decode(r) assert.NoError(t, err) - assert.Equal(t, cert.Height(), uint32(0x01020304)) - assert.Equal(t, cert.Round(), int16(0x0001)) - assert.Equal(t, cert.Committers(), []int32{1, 2, 3, 4, 5, 6}) - assert.Equal(t, cert.Absentees(), []int32{2}) - assert.Equal(t, cert.Hash(), certHash) + assert.Equal(t, uint32(0x01020304), cert.Height()) + assert.Equal(t, int16(0x0001), cert.Round()) + assert.Equal(t, []int32{1, 2, 3, 4, 5, 6}, cert.Committers()) + assert.Equal(t, []int32{2}, cert.Absentees()) + assert.Equal(t, certHash, cert.Hash()) } func TestVoteCertificateValidatePrepare(t *testing.T) { diff --git a/types/tx/payload/bond_test.go b/types/tx/payload/bond_test.go index e03903765..2aca0192a 100644 --- a/types/tx/payload/bond_test.go +++ b/types/tx/payload/bond_test.go @@ -13,7 +13,7 @@ import ( func TestBondType(t *testing.T) { pld := BondPayload{} - assert.Equal(t, pld.Type(), TypeBond) + assert.Equal(t, TypeBond, pld.Type()) } func TestBondDecoding(t *testing.T) { @@ -251,8 +251,8 @@ func TestBondDecoding(t *testing.T) { } w := util.NewFixedWriter(pld.SerializeSize()) require.NoError(t, pld.Encode(w)) - assert.Equal(t, len(w.Bytes()), pld.SerializeSize()) - assert.Equal(t, w.Bytes(), test.raw) + assert.Equal(t, pld.SerializeSize(), len(w.Bytes())) + assert.Equal(t, test.raw, w.Bytes()) // Basic check if test.basicErr != nil { @@ -262,9 +262,9 @@ func TestBondDecoding(t *testing.T) { assert.NoError(t, pld.BasicCheck()) // Check signer - assert.Equal(t, pld.Signer(), crypto.Address(test.raw[:21])) - assert.Equal(t, *pld.Receiver(), crypto.Address(test.raw[21:42])) - assert.Equal(t, pld.Value(), test.value) + assert.Equal(t, crypto.Address(test.raw[:21]), pld.Signer()) + assert.Equal(t, crypto.Address(test.raw[21:42]), *pld.Receiver()) + assert.Equal(t, test.value, pld.Value()) } } } diff --git a/types/tx/payload/sortition_test.go b/types/tx/payload/sortition_test.go index bc27bca94..af7369981 100644 --- a/types/tx/payload/sortition_test.go +++ b/types/tx/payload/sortition_test.go @@ -12,7 +12,7 @@ import ( func TestSortitionType(t *testing.T) { pld := SortitionPayload{} - assert.Equal(t, pld.Type(), TypeSortition) + assert.Equal(t, TypeSortition, pld.Type()) } func TestSortitionDecoding(t *testing.T) { @@ -105,8 +105,8 @@ func TestSortitionDecoding(t *testing.T) { } w := util.NewFixedWriter(pld.SerializeSize()) assert.NoError(t, pld.Encode(w)) - assert.Equal(t, len(w.Bytes()), pld.SerializeSize()) - assert.Equal(t, w.Bytes(), test.raw) + assert.Equal(t, pld.SerializeSize(), len(w.Bytes())) + assert.Equal(t, test.raw, w.Bytes()) // Basic check if test.basicErr != nil { @@ -116,12 +116,12 @@ func TestSortitionDecoding(t *testing.T) { // Check signer if test.raw[0] != 0 { - assert.Equal(t, pld.Signer(), crypto.Address(test.raw[:21])) + assert.Equal(t, crypto.Address(test.raw[:21]), pld.Signer()) } else { - assert.Equal(t, pld.Signer(), crypto.TreasuryAddress) + assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) } - assert.Equal(t, pld.Value(), test.value) + assert.Equal(t, test.value, pld.Value()) assert.Nil(t, pld.Receiver()) } } diff --git a/types/tx/payload/transfer_test.go b/types/tx/payload/transfer_test.go index 59ed8e0d5..8176add36 100644 --- a/types/tx/payload/transfer_test.go +++ b/types/tx/payload/transfer_test.go @@ -12,7 +12,7 @@ import ( func TestTransferType(t *testing.T) { pld := TransferPayload{} - assert.Equal(t, pld.Type(), TypeTransfer) + assert.Equal(t, TypeTransfer, pld.Type()) } func TestTransferDecoding(t *testing.T) { @@ -136,8 +136,8 @@ func TestTransferDecoding(t *testing.T) { } w := util.NewFixedWriter(pld.SerializeSize()) assert.NoError(t, pld.Encode(w)) - assert.Equal(t, len(w.Bytes()), pld.SerializeSize()) - assert.Equal(t, w.Bytes(), test.raw) + assert.Equal(t, pld.SerializeSize(), len(w.Bytes())) + assert.Equal(t, test.raw, w.Bytes()) // Basic check if test.basicErr != nil { @@ -147,13 +147,13 @@ func TestTransferDecoding(t *testing.T) { // Check signer if test.raw[0] != 0 { - assert.Equal(t, pld.Signer(), crypto.Address(test.raw[:21])) - assert.Equal(t, *pld.Receiver(), crypto.Address(test.raw[21:42])) + assert.Equal(t, crypto.Address(test.raw[:21]), pld.Signer()) + assert.Equal(t, crypto.Address(test.raw[21:42]), *pld.Receiver()) } else { - assert.Equal(t, pld.Signer(), crypto.TreasuryAddress) - assert.Equal(t, *pld.Receiver(), crypto.Address(test.raw[1:22])) + assert.Equal(t, crypto.TreasuryAddress, pld.Signer()) + assert.Equal(t, crypto.Address(test.raw[1:22]), *pld.Receiver()) } - assert.Equal(t, pld.Value(), test.value) + assert.Equal(t, test.value, pld.Value()) } } } diff --git a/types/tx/tx_test.go b/types/tx/tx_test.go index 7a6b0a6f3..5ca28979a 100644 --- a/types/tx/tx_test.go +++ b/types/tx/tx_test.go @@ -196,7 +196,7 @@ func TestBasicCheck(t *testing.T) { assert.ErrorIs(t, err, tx.BasicCheckError{ Reason: "invalid version: 2", }) - assert.Equal(t, trx.SerializeSize(), len(d)) + assert.Equal(t, len(d), trx.SerializeSize()) }) } @@ -362,13 +362,13 @@ func TestSignBytes(t *testing.T) { h, _ := hash.FromString("1a8cedbb2ffce29df63210f112afb1c0295b27e2162323bfc774068f0573388e") trx, err := tx.FromBytes(d) assert.NoError(t, err) - assert.Equal(t, trx.SerializeSize(), len(d)) + assert.Equal(t, len(d), trx.SerializeSize()) sb := d[1 : len(d)-bls.PublicKeySize-bls.SignatureSize] assert.Equal(t, sb, trx.SignBytes()) - assert.Equal(t, trx.ID(), h) - assert.Equal(t, trx.ID(), hash.CalcHash(sb)) - assert.Equal(t, trx.LockTime(), uint32(0x04030201)) + assert.Equal(t, h, trx.ID()) + assert.Equal(t, hash.CalcHash(sb), trx.ID()) + assert.Equal(t, uint32(0x04030201), trx.LockTime()) } func TestStripPublicKey(t *testing.T) { diff --git a/types/validator/validator_test.go b/types/validator/validator_test.go index c0186af99..f460ffe16 100644 --- a/types/validator/validator_test.go +++ b/types/validator/validator_test.go @@ -52,19 +52,19 @@ func TestDecoding(t *testing.T) { val, err := validator.FromBytes(d) require.NoError(t, err) - assert.Equal(t, val.Number(), int32(1)) - assert.Equal(t, val.Stake(), amount.Amount(2)) - assert.Equal(t, val.LastBondingHeight(), uint32(3)) - assert.Equal(t, val.UnbondingHeight(), uint32(4)) - assert.Equal(t, val.LastSortitionHeight(), uint32(5)) + assert.Equal(t, int32(1), val.Number()) + assert.Equal(t, amount.Amount(2), val.Stake()) + assert.Equal(t, uint32(3), val.LastBondingHeight()) + assert.Equal(t, uint32(4), val.UnbondingHeight()) + assert.Equal(t, uint32(5), val.LastSortitionHeight()) d2, _ := val.Bytes() assert.Equal(t, d, d2) - assert.Equal(t, val.Hash(), hash.CalcHash(d)) + assert.Equal(t, hash.CalcHash(d), val.Hash()) expected, _ := hash.FromString("243e65ae04727f21d5f7618cea9ff8d4bc82fded1179cf8bd9e11a6b99ac42b2") - assert.Equal(t, val.Hash(), expected) + assert.Equal(t, expected, val.Hash()) pub, _ := bls.PublicKeyFromBytes(d[:96]) assert.True(t, val.PublicKey().EqualsTo(pub)) - assert.Equal(t, val.SerializeSize(), len(d)) + assert.Equal(t, len(d), val.SerializeSize()) } func TestPower(t *testing.T) { @@ -72,14 +72,14 @@ func TestPower(t *testing.T) { val, _ := ts.GenerateTestValidator(ts.RandInt32(1000)) val.SubtractFromStake(val.Stake()) - assert.Equal(t, val.Stake(), amount.Amount(0)) - assert.Equal(t, val.Power(), int64(1)) + assert.Equal(t, amount.Amount(0), val.Stake()) + assert.Equal(t, int64(1), val.Power()) val.AddToStake(1) - assert.Equal(t, val.Stake(), amount.Amount(1)) - assert.Equal(t, val.Power(), int64(1)) + assert.Equal(t, amount.Amount(1), val.Stake()) + assert.Equal(t, int64(1), val.Power()) val.UpdateUnbondingHeight(1) - assert.Equal(t, val.Stake(), amount.Amount(1)) - assert.Equal(t, val.Power(), int64(0)) + assert.Equal(t, amount.Amount(1), val.Stake()) + assert.Equal(t, int64(0), val.Power()) } func TestAddToStake(t *testing.T) { @@ -88,7 +88,7 @@ func TestAddToStake(t *testing.T) { val, _ := ts.GenerateTestValidator(100) stake := val.Stake() val.AddToStake(1) - assert.Equal(t, val.Stake(), stake+1) + assert.Equal(t, stake+1, val.Stake()) } func TestSubtractFromStake(t *testing.T) { @@ -97,7 +97,7 @@ func TestSubtractFromStake(t *testing.T) { val, _ := ts.GenerateTestValidator(100) stake := val.Stake() val.SubtractFromStake(1) - assert.Equal(t, val.Stake(), stake-1) + assert.Equal(t, stake-1, val.Stake()) } func TestClone(t *testing.T) { diff --git a/types/vote/vote_test.go b/types/vote/vote_test.go index 36a3122dc..132032515 100644 --- a/types/vote/vote_test.go +++ b/types/vote/vote_test.go @@ -208,16 +208,16 @@ func TestVoteMarshaling(t *testing.T) { assert.Equal(t, bz1, bz2) expectedHash := hash.CalcHash(bz1) - assert.Equal(t, v.Hash(), expectedHash) + assert.Equal(t, expectedHash, v.Hash()) v.SetSignature(ts.RandBLSSignature()) assert.NoError(t, v.BasicCheck()) expectedSignBytes, _ := hex.DecodeString(test.signBytes) - assert.Equal(t, v.SignBytes(), expectedSignBytes) + assert.Equal(t, expectedSignBytes, v.SignBytes()) if test.justType != "" { - assert.Equal(t, v.CPJust().Type().String(), test.justType) + assert.Equal(t, test.justType, v.CPJust().Type().String()) } } } @@ -259,7 +259,7 @@ func TestCPPreVote(t *testing.T) { -1, vote.CPValueYes, just, ts.RandAccAddress()) err := v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidRound) + assert.Equal(t, errors.ErrInvalidRound, errors.Code(err)) }) t.Run("Invalid value", func(t *testing.T) { @@ -267,7 +267,7 @@ func TestCPPreVote(t *testing.T) { 1, 3, just, ts.RandAccAddress()) err := v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidVote) + assert.Equal(t, errors.ErrInvalidVote, errors.Code(err)) }) t.Run("Ok", func(t *testing.T) { @@ -277,8 +277,8 @@ func TestCPPreVote(t *testing.T) { err := v.BasicCheck() assert.NoError(t, err) - assert.Equal(t, v.CPRound(), int16(1)) - assert.Equal(t, v.CPValue(), vote.CPValueNo) + assert.Equal(t, int16(1), v.CPRound()) + assert.Equal(t, vote.CPValueNo, v.CPValue()) assert.NotNil(t, v.CPJust()) }) } @@ -295,7 +295,7 @@ func TestCPMainVote(t *testing.T) { -1, vote.CPValueNo, just, ts.RandAccAddress()) err := v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidRound) + assert.Equal(t, errors.ErrInvalidRound, errors.Code(err)) }) t.Run("No CP data", func(t *testing.T) { @@ -314,7 +314,7 @@ func TestCPMainVote(t *testing.T) { 1, 3, just, ts.RandAccAddress()) err := v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidVote) + assert.Equal(t, errors.ErrInvalidVote, errors.Code(err)) }) t.Run("Ok", func(t *testing.T) { @@ -324,8 +324,8 @@ func TestCPMainVote(t *testing.T) { err := v.BasicCheck() assert.NoError(t, err) - assert.Equal(t, v.CPRound(), int16(1)) - assert.Equal(t, v.CPValue(), vote.CPValueAbstain) + assert.Equal(t, int16(1), v.CPRound()) + assert.Equal(t, vote.CPValueAbstain, v.CPValue()) assert.NotNil(t, v.CPJust()) }) } @@ -342,7 +342,7 @@ func TestCPDecided(t *testing.T) { -1, vote.CPValueNo, just, ts.RandAccAddress()) err := v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidRound) + assert.Equal(t, errors.ErrInvalidRound, errors.Code(err)) }) t.Run("No CP data", func(t *testing.T) { @@ -361,7 +361,7 @@ func TestCPDecided(t *testing.T) { 1, 3, just, ts.RandAccAddress()) err := v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidVote) + assert.Equal(t, errors.ErrInvalidVote, errors.Code(err)) }) t.Run("Ok", func(t *testing.T) { @@ -371,8 +371,8 @@ func TestCPDecided(t *testing.T) { err := v.BasicCheck() assert.NoError(t, err) - assert.Equal(t, v.CPRound(), int16(1)) - assert.Equal(t, v.CPValue(), vote.CPValueAbstain) + assert.Equal(t, int16(1), v.CPRound()) + assert.Equal(t, vote.CPValueAbstain, v.CPValue()) assert.NotNil(t, v.CPJust()) }) } @@ -388,7 +388,7 @@ func TestBasicCheck(t *testing.T) { assert.NoError(t, err) err = v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidVote) + assert.Equal(t, errors.ErrInvalidVote, errors.Code(err)) }) t.Run("Invalid height", func(t *testing.T) { @@ -409,7 +409,7 @@ func TestBasicCheck(t *testing.T) { v := vote.NewPrepareVote(ts.RandHash(), 100, 0, ts.RandAccAddress()) err := v.BasicCheck() - assert.Equal(t, errors.Code(err), errors.ErrInvalidSignature) + assert.Equal(t, errors.ErrInvalidSignature, errors.Code(err)) }) t.Run("Has CP data", func(t *testing.T) { @@ -453,11 +453,11 @@ func TestSignBytes(t *testing.T) { sb4 := v4.SignBytes() sb5 := v5.SignBytes() - assert.Equal(t, len(sb1), 45) - assert.Equal(t, len(sb2), 38) - assert.Equal(t, len(sb3), 49) - assert.Equal(t, len(sb4), 50) - assert.Equal(t, len(sb5), 48) + assert.Equal(t, 45, len(sb1)) + assert.Equal(t, 38, len(sb2)) + assert.Equal(t, 49, len(sb3)) + assert.Equal(t, 50, len(sb4)) + assert.Equal(t, 48, len(sb5)) assert.Contains(t, string(sb1), "PREPARE") assert.Contains(t, string(sb3), "PRE-VOTE") @@ -486,10 +486,10 @@ func TestLog(t *testing.T) { } func TestCPValueToString(t *testing.T) { - assert.Equal(t, vote.CPValueNo.String(), "no") - assert.Equal(t, vote.CPValueYes.String(), "yes") - assert.Equal(t, vote.CPValueAbstain.String(), "abstain") - assert.Equal(t, vote.CPValue(-1).String(), "unknown: -1") + assert.Equal(t, "no", vote.CPValueNo.String()) + assert.Equal(t, "yes", vote.CPValueYes.String()) + assert.Equal(t, "abstain", vote.CPValueAbstain.String()) + assert.Equal(t, "unknown: -1", vote.CPValue(-1).String()) } func TestCPInvalidJustType(t *testing.T) { diff --git a/util/errors/errors_test.go b/util/errors/errors_test.go index 56b4242bb..4c8e08d62 100644 --- a/util/errors/errors_test.go +++ b/util/errors/errors_test.go @@ -9,12 +9,12 @@ import ( func TestCode(t *testing.T) { err1 := Error(ErrInvalidAmount) - assert.Equal(t, Code(err1), ErrInvalidAmount) + assert.Equal(t, ErrInvalidAmount, Code(err1)) err2 := fmt.Errorf("Nope") - assert.Equal(t, Code(err2), ErrGeneric) + assert.Equal(t, ErrGeneric, Code(err2)) - assert.Equal(t, Code(nil), ErrNone) + assert.Equal(t, ErrNone, Code(nil)) } func TestMessages(t *testing.T) { @@ -28,8 +28,8 @@ func TestErrorCode(t *testing.T) { err2 := Errorf(ErrInvalidTx, err1.Error()) err3 := Errorf(ErrInvalidBlock, err1.Error()) - assert.Equal(t, Code(err2), ErrInvalidTx) - assert.Equal(t, Code(err3), ErrInvalidBlock) + assert.Equal(t, ErrInvalidTx, Code(err2)) + assert.Equal(t, ErrInvalidBlock, Code(err3)) assert.Equal(t, "invalid amount", err1.Error()) assert.Equal(t, "invalid transaction: invalid amount", err2.Error()) assert.Equal(t, "invalid block: invalid amount", err3.Error()) diff --git a/util/htpasswd/htpasswd_test.go b/util/htpasswd/htpasswd_test.go index 57c1d36ee..cd4e86f31 100644 --- a/util/htpasswd/htpasswd_test.go +++ b/util/htpasswd/htpasswd_test.go @@ -44,7 +44,7 @@ func TestExtractBasicAuth(t *testing.T) { t.Fatal(err) } - require.Equal(t, user+":"+encodedPass, tt.input) + require.Equal(t, tt.input, user+":"+encodedPass) }) } } diff --git a/util/io_test.go b/util/io_test.go index 5d4967d79..02d56e522 100644 --- a/util/io_test.go +++ b/util/io_test.go @@ -23,7 +23,7 @@ func TestWriteFile(t *testing.T) { func TestEmptyPath(t *testing.T) { p := TempDirPath() - assert.Equal(t, MakeAbs(p), p) + assert.Equal(t, p, MakeAbs(p)) assert.True(t, IsDirEmpty(p)) f := TempFilePath() diff --git a/util/linkedlist/linkedlist_test.go b/util/linkedlist/linkedlist_test.go index da9edd07a..e0feec4ce 100644 --- a/util/linkedlist/linkedlist_test.go +++ b/util/linkedlist/linkedlist_test.go @@ -14,10 +14,10 @@ func TestDoublyLink_InsertAtHead(t *testing.T) { link.InsertAtHead(3) link.InsertAtHead(4) - assert.Equal(t, link.Values(), []int{4, 3, 2, 1}) - assert.Equal(t, link.Length(), 4) - assert.Equal(t, link.Head.Data, 4) - assert.Equal(t, link.Tail.Data, 1) + assert.Equal(t, []int{4, 3, 2, 1}, link.Values()) + assert.Equal(t, 4, link.Length()) + assert.Equal(t, 4, link.Head.Data) + assert.Equal(t, 1, link.Tail.Data) } func TestSinglyLink_InsertAtTail(t *testing.T) { @@ -27,10 +27,10 @@ func TestSinglyLink_InsertAtTail(t *testing.T) { link.InsertAtTail(3) link.InsertAtTail(4) - assert.Equal(t, link.Values(), []int{1, 2, 3, 4}) - assert.Equal(t, link.Length(), 4) - assert.Equal(t, link.Head.Data, 1) - assert.Equal(t, link.Tail.Data, 4) + assert.Equal(t, []int{1, 2, 3, 4}, link.Values()) + assert.Equal(t, 4, link.Length()) + assert.Equal(t, 1, link.Head.Data) + assert.Equal(t, 4, link.Tail.Data) } func TestDeleteAtHead(t *testing.T) { @@ -40,20 +40,20 @@ func TestDeleteAtHead(t *testing.T) { link.InsertAtTail(3) link.DeleteAtHead() - assert.Equal(t, link.Values(), []int{2, 3}) - assert.Equal(t, link.Length(), 2) + assert.Equal(t, []int{2, 3}, link.Values()) + assert.Equal(t, 2, link.Length()) link.DeleteAtHead() - assert.Equal(t, link.Values(), []int{3}) - assert.Equal(t, link.Length(), 1) + assert.Equal(t, []int{3}, link.Values()) + assert.Equal(t, 1, link.Length()) link.DeleteAtHead() - assert.Equal(t, link.Values(), []int{}) - assert.Equal(t, link.Length(), 0) + assert.Equal(t, []int{}, link.Values()) + assert.Equal(t, 0, link.Length()) link.DeleteAtHead() - assert.Equal(t, link.Values(), []int{}) - assert.Equal(t, link.Length(), 0) + assert.Equal(t, []int{}, link.Values()) + assert.Equal(t, 0, link.Length()) } func TestDeleteAtTail(t *testing.T) { @@ -63,20 +63,20 @@ func TestDeleteAtTail(t *testing.T) { link.InsertAtTail(3) link.DeleteAtTail() - assert.Equal(t, link.Values(), []int{1, 2}) - assert.Equal(t, link.Length(), 2) + assert.Equal(t, []int{1, 2}, link.Values()) + assert.Equal(t, 2, link.Length()) link.DeleteAtTail() - assert.Equal(t, link.Values(), []int{1}) - assert.Equal(t, link.Length(), 1) + assert.Equal(t, []int{1}, link.Values()) + assert.Equal(t, 1, link.Length()) link.DeleteAtTail() - assert.Equal(t, link.Values(), []int{}) - assert.Equal(t, link.Length(), 0) + assert.Equal(t, []int{}, link.Values()) + assert.Equal(t, 0, link.Length()) link.DeleteAtTail() - assert.Equal(t, link.Values(), []int{}) - assert.Equal(t, link.Length(), 0) + assert.Equal(t, []int{}, link.Values()) + assert.Equal(t, 0, link.Length()) } func TestDelete(t *testing.T) { @@ -87,20 +87,20 @@ func TestDelete(t *testing.T) { n4 := link.InsertAtTail(4) link.Delete(n1) - assert.Equal(t, link.Values(), []int{2, 3, 4}) - assert.Equal(t, link.Length(), 3) + assert.Equal(t, []int{2, 3, 4}, link.Values()) + assert.Equal(t, 3, link.Length()) link.Delete(n4) - assert.Equal(t, link.Values(), []int{2, 3}) - assert.Equal(t, link.Length(), 2) + assert.Equal(t, []int{2, 3}, link.Values()) + assert.Equal(t, 2, link.Length()) link.Delete(n2) - assert.Equal(t, link.Values(), []int{3}) - assert.Equal(t, link.Length(), 1) + assert.Equal(t, []int{3}, link.Values()) + assert.Equal(t, 1, link.Length()) link.Delete(n3) - assert.Equal(t, link.Values(), []int{}) - assert.Equal(t, link.Length(), 0) + assert.Equal(t, []int{}, link.Values()) + assert.Equal(t, 0, link.Length()) } func TestClear(t *testing.T) { @@ -110,8 +110,8 @@ func TestClear(t *testing.T) { link.InsertAtTail(3) link.Clear() - assert.Equal(t, link.Values(), []int{}) - assert.Equal(t, link.Length(), 0) + assert.Equal(t, []int{}, link.Values()) + assert.Equal(t, 0, link.Length()) } func TestInsertAfter(t *testing.T) { diff --git a/util/persistentmerkle/merkle_test.go b/util/persistentmerkle/merkle_test.go index 72d1e74da..e07df1bbb 100644 --- a/util/persistentmerkle/merkle_test.go +++ b/util/persistentmerkle/merkle_test.go @@ -8,38 +8,38 @@ import ( ) func TestNodeID(t *testing.T) { - assert.Equal(t, nodeID(0, 0), 0x00000000) - assert.Equal(t, nodeID(0, 1), 0x01000000) - assert.Equal(t, nodeID(1, 0), 0x00000001) - assert.Equal(t, nodeID(1, 1), 0x01000001) - assert.Equal(t, nodeID(0xffffff, 0xff), 0xffffffff) - assert.Equal(t, nodeID(0xffffff, 0x00), 0x00ffffff) - assert.Equal(t, nodeID(0xff00ff, 0x77), 0x77ff00ff) + assert.Equal(t, 0x00000000, nodeID(0, 0)) + assert.Equal(t, 0x01000000, nodeID(0, 1)) + assert.Equal(t, 0x00000001, nodeID(1, 0)) + assert.Equal(t, 0x01000001, nodeID(1, 1)) + assert.Equal(t, 0xffffffff, nodeID(0xffffff, 0xff)) + assert.Equal(t, 0x00ffffff, nodeID(0xffffff, 0x00)) + assert.Equal(t, 0x77ff00ff, nodeID(0xff00ff, 0x77)) } func TestCalculateHeight(t *testing.T) { tree := New() tree.recalculateHeight(0) - assert.Equal(t, tree.maxHeight, 0) + assert.Equal(t, 0, tree.maxHeight) tree.recalculateHeight(1) - assert.Equal(t, tree.maxHeight, 1) + assert.Equal(t, 1, tree.maxHeight) tree.recalculateHeight(2) - assert.Equal(t, tree.maxHeight, 2) + assert.Equal(t, 2, tree.maxHeight) tree.recalculateHeight(4) - assert.Equal(t, tree.maxHeight, 3) + assert.Equal(t, 3, tree.maxHeight) tree.recalculateHeight(5) - assert.Equal(t, tree.maxHeight, 4) + assert.Equal(t, 4, tree.maxHeight) tree.recalculateHeight(8) - assert.Equal(t, tree.maxHeight, 4) + assert.Equal(t, 4, tree.maxHeight) tree.recalculateHeight(9) - assert.Equal(t, tree.maxHeight, 5) + assert.Equal(t, 5, tree.maxHeight) } func TestMerkleTree(t *testing.T) { @@ -81,12 +81,12 @@ func TestMerkleTree(t *testing.T) { for i, d := range data { tree.SetData(i, []byte(d)) expected, _ := hex.DecodeString(roots[i]) - assert.Equal(t, tree.Root().Bytes(), expected, "Root %d not matched", i) + assert.Equal(t, expected, tree.Root().Bytes(), "Root %d not matched", i) } // Modifying some data blocks tree.SetData(0, []byte("a")) tree.SetData(21, []byte("v")) expected, _ := hex.DecodeString("ec4446ea16b8f82083cc2d727b8f9e7b9c318e35bb37295a2e87064393572800") - assert.Equal(t, tree.Root().Bytes(), expected) + assert.Equal(t, expected, tree.Root().Bytes()) } diff --git a/util/simplemerkle/merkle_test.go b/util/simplemerkle/merkle_test.go index b6fd19d12..dafec9507 100644 --- a/util/simplemerkle/merkle_test.go +++ b/util/simplemerkle/merkle_test.go @@ -84,8 +84,8 @@ func TestMerkleTree_Bitcoin_Block100000(t *testing.T) { } tree := NewTreeFromHashes(hashes) - assert.Equal(t, tree.Root(), root) - assert.Equal(t, tree.Depth(), 2) + assert.Equal(t, root, tree.Root()) + assert.Equal(t, 2, tree.Depth()) } func TestMerkleTree_Bitcoin_Block153342(t *testing.T) { @@ -120,8 +120,8 @@ func TestMerkleTree_Bitcoin_Block153342(t *testing.T) { } tree := NewTreeFromHashes(hashes) - assert.Equal(t, tree.Root(), root) - assert.Equal(t, tree.Depth(), 4) + assert.Equal(t, root, tree.Root()) + assert.Equal(t, 4, tree.Depth()) fmt.Println(tree.ToString()) assert.Contains(t, tree.ToString(), root.String()) diff --git a/util/slice_test.go b/util/slice_test.go index 2fed79e8b..ef88c8b72 100644 --- a/util/slice_test.go +++ b/util/slice_test.go @@ -25,12 +25,12 @@ func TestSliceToInt16(t *testing.T) { s1 := Uint16ToSlice(uint16(test.in)) s2 := Int16ToSlice(test.in) assert.Equal(t, s1, s2) - assert.Equal(t, s1, test.slice) + assert.Equal(t, test.slice, s1) v1 := SliceToInt16(test.slice) v2 := SliceToUint16(test.slice) - assert.Equal(t, v1, int16(v2)) - assert.Equal(t, v1, test.in) + assert.Equal(t, int16(v2), v1) + assert.Equal(t, test.in, v1) } } @@ -52,12 +52,12 @@ func TestSliceToInt32(t *testing.T) { s1 := Uint32ToSlice(uint32(test.in)) s2 := Int32ToSlice(test.in) assert.Equal(t, s1, s2) - assert.Equal(t, s1, test.slice) + assert.Equal(t, test.slice, s1) v1 := SliceToInt32(test.slice) v2 := SliceToUint32(test.slice) - assert.Equal(t, v1, int32(v2)) - assert.Equal(t, v1, test.in) + assert.Equal(t, int32(v2), v1) + assert.Equal(t, test.in, v1) } } @@ -79,12 +79,12 @@ func TestSliceToInt64(t *testing.T) { s1 := Uint64ToSlice(uint64(test.in)) s2 := Int64ToSlice(test.in) assert.Equal(t, s1, s2) - assert.Equal(t, s1, test.slice) + assert.Equal(t, test.slice, s1) v1 := SliceToInt64(test.slice) v2 := SliceToUint64(test.slice) - assert.Equal(t, v1, int64(v2)) - assert.Equal(t, v1, test.in) + assert.Equal(t, int64(v2), v1) + assert.Equal(t, test.in, v1) } } @@ -114,42 +114,42 @@ func TestSubtractAndSubset(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{1, 2, 3} s3 := Subtracts(s1, s2) - assert.Equal(t, s3, []int32{4}) + assert.Equal(t, []int32{4}, s3) }) t.Run("Case 2", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{2, 3, 5} s3 := Subtracts(s1, s2) - assert.Equal(t, s3, []int32{1, 4}) + assert.Equal(t, []int32{1, 4}, s3) }) t.Run("Case 3", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{} s3 := Subtracts(s1, s2) - assert.Equal(t, s3, []int32{1, 2, 3, 4}) + assert.Equal(t, []int32{1, 2, 3, 4}, s3) }) t.Run("Case 4", func(t *testing.T) { s1 := []int32{} s2 := []int32{1, 2, 3, 4} s3 := Subtracts(s1, s2) - assert.Equal(t, s3, []int32{}) + assert.Equal(t, []int32{}, s3) }) t.Run("Case 5", func(t *testing.T) { s1 := []int32{1, 2, 3, 4} s2 := []int32{1, 2, 3, 4} s3 := Subtracts(s1, s2) - assert.Equal(t, s3, []int32{}) + assert.Equal(t, []int32{}, s3) }) t.Run("Case 6", func(t *testing.T) { s1 := []int32{1, 3, 5} s2 := []int32{1, 2, 3, 4, 5} s3 := Subtracts(s1, s2) - assert.Equal(t, s3, []int32{}) + assert.Equal(t, []int32{}, s3) }) t.Run("Case 7", func(t *testing.T) { @@ -161,7 +161,7 @@ func TestSubtractAndSubset(t *testing.T) { t.Run("Case 8", func(t *testing.T) { s2 := []int32{1, 2, 3, 4} s3 := Subtracts(nil, s2) - assert.Equal(t, s3, []int32{}) + assert.Equal(t, []int32{}, s3) }) } @@ -201,7 +201,7 @@ func TestMerge(t *testing.T) { for _, test := range tests { merged := Merge(test.slices...) - assert.Equal(t, merged, test.merged) + assert.Equal(t, test.merged, merged) } } @@ -237,7 +237,7 @@ func TestExtendSlice(t *testing.T) { for _, c := range cases { inCopy := c.in Extend(&inCopy, c.size) - assert.Equal(t, inCopy, c.want, "ExtendSlice(%v, %v) == %v, want %v", c.in, c.size, c.in, c.want) + assert.Equal(t, c.want, inCopy, "ExtendSlice(%v, %v) == %v, want %v", c.in, c.size, c.in, c.want) } } @@ -258,7 +258,7 @@ func TestIsSubset(t *testing.T) { for _, tt := range tests { got := IsSubset(tt.arr1, tt.arr2) - assert.Equal(t, got, tt.want, + assert.Equal(t, tt.want, got, "isSubset(%v, %v) = %v; want %v", tt.arr1, tt.arr2, got, tt.want) } } @@ -275,7 +275,7 @@ func TestStringToBytes(t *testing.T) { for _, test := range tests { got := StringToBytes(test.input) - assert.Equal(t, got, test.output, "StringToBytes('%s') = %v, want %v", test.input, got, test.output) + assert.Equal(t, test.output, got, "StringToBytes('%s') = %v, want %v", test.input, got, test.output) } } @@ -344,7 +344,7 @@ func TestTrimSlice(t *testing.T) { for _, tt := range tests { got := Trim(tt.input, tt.newLength) - assert.Equal(t, got, tt.want, "Trim() = %v, want %v", got, tt.want) + assert.Equal(t, tt.want, got, "Trim() = %v, want %v", got, tt.want) } } diff --git a/util/time_test.go b/util/time_test.go index d0d905001..b9769073b 100644 --- a/util/time_test.go +++ b/util/time_test.go @@ -14,10 +14,10 @@ func TestNow(t *testing.T) { assert.NotEqual(t, c1, c2) assert.Equal(t, c1.Second(), c2.Second()) - assert.Equal(t, c2.UnixMicro()%1000000, int64(0)) - assert.Equal(t, c2.UnixMilli()%1000, int64(0)) - assert.Equal(t, c3.Nanosecond(), 0) - assert.Equal(t, c3.Second()%5, 0) + assert.Equal(t, int64(0), c2.UnixMicro()%1000000) + assert.Equal(t, int64(0), c2.UnixMilli()%1000) + assert.Equal(t, 0, c3.Nanosecond()) + assert.Equal(t, 0, c3.Second()%5) } func TestRoundingTime(t *testing.T) { @@ -32,15 +32,15 @@ func TestRoundingTime(t *testing.T) { c4 := roundDownTime(t4, 10) c5 := roundDownTime(t5, 10) - assert.Equal(t, c1.Nanosecond(), 0) - assert.Equal(t, c2.Nanosecond(), 0) - assert.Equal(t, c3.Nanosecond(), 0) - assert.Equal(t, c4.Nanosecond(), 0) - assert.Equal(t, c5.Nanosecond(), 0) + assert.Equal(t, 0, c1.Nanosecond()) + assert.Equal(t, 0, c2.Nanosecond()) + assert.Equal(t, 0, c3.Nanosecond()) + assert.Equal(t, 0, c4.Nanosecond()) + assert.Equal(t, 0, c5.Nanosecond()) - assert.Equal(t, c1.Second(), 10) - assert.Equal(t, c2.Second(), 20) - assert.Equal(t, c3.Second(), 30) - assert.Equal(t, c4.Second(), 40) - assert.Equal(t, c5.Second(), 50) + assert.Equal(t, 10, c1.Second()) + assert.Equal(t, 20, c2.Second()) + assert.Equal(t, 30, c3.Second()) + assert.Equal(t, 40, c4.Second()) + assert.Equal(t, 50, c5.Second()) } diff --git a/util/utils_test.go b/util/utils_test.go index 0b248535d..db4169e94 100644 --- a/util/utils_test.go +++ b/util/utils_test.go @@ -8,28 +8,28 @@ import ( ) func TestUtils(t *testing.T) { - assert.Equal(t, Min(int32(1), 1), int32(1)) - assert.Equal(t, Min(int32(1), 2), int32(1)) - assert.Equal(t, Min(2, int32(1)), int32(1)) - assert.Equal(t, Max(int32(2), 2), int32(2)) - assert.Equal(t, Max(1, int32(2)), int32(2)) - assert.Equal(t, Max(int32(2), 1), int32(2)) - - assert.Equal(t, Min(uint32(1), 1), uint32(1)) - assert.Equal(t, Min(uint32(1), 2), uint32(1)) - assert.Equal(t, Min(2, uint32(1)), uint32(1)) - assert.Equal(t, Max(uint32(2), 2), uint32(2)) - assert.Equal(t, Max(1, uint32(2)), uint32(2)) - assert.Equal(t, Max(uint32(2), 1), uint32(2)) + assert.Equal(t, int32(1), Min(int32(1), 1)) + assert.Equal(t, int32(1), Min(int32(1), 2)) + assert.Equal(t, int32(1), Min(2, int32(1))) + assert.Equal(t, int32(2), Max(int32(2), 2)) + assert.Equal(t, int32(2), Max(1, int32(2))) + assert.Equal(t, int32(2), Max(int32(2), 1)) + + assert.Equal(t, uint32(1), Min(uint32(1), 1)) + assert.Equal(t, uint32(1), Min(uint32(1), 2)) + assert.Equal(t, uint32(1), Min(2, uint32(1))) + assert.Equal(t, uint32(2), Max(uint32(2), 2)) + assert.Equal(t, uint32(2), Max(1, uint32(2))) + assert.Equal(t, uint32(2), Max(uint32(2), 1)) assert.Equal(t, MaxUint32, uint32(0xffffffff)) assert.Equal(t, MaxUint64, uint64(0xffffffffffffffff)) assert.Equal(t, MaxInt32, int32(0x7fffffff)) assert.Equal(t, MaxInt64, int64(0x7fffffffffffffff)) - assert.Equal(t, Max(MaxInt64, 1), MaxInt64) - assert.Equal(t, Max(MinInt64, MaxInt64), MaxInt64) - assert.Equal(t, Min(MaxInt64, 1), int64(1)) - assert.Equal(t, Min(MinInt64, MaxInt64), MinInt64) + assert.Equal(t, MaxInt64, Max(MaxInt64, 1)) + assert.Equal(t, MaxInt64, Max(MinInt64, MaxInt64)) + assert.Equal(t, int64(1), Min(MaxInt64, 1)) + assert.Equal(t, MinInt64, Min(MinInt64, MaxInt64)) } func TestSetFlags(t *testing.T) { @@ -86,19 +86,19 @@ func TestRandUint64(t *testing.T) { func TestI2OSP(t *testing.T) { assert.Nil(t, I2OSP(big.NewInt(int64(-1)), 2)) - assert.Equal(t, I2OSP(big.NewInt(int64(0)), 2), []byte{0, 0}) - assert.Equal(t, I2OSP(big.NewInt(int64(1)), 2), []byte{0, 1}) - assert.Equal(t, I2OSP(big.NewInt(int64(255)), 2), []byte{0, 255}) - assert.Equal(t, I2OSP(big.NewInt(int64(256)), 2), []byte{1, 0}) - assert.Equal(t, I2OSP(big.NewInt(int64(65535)), 2), []byte{255, 255}) + assert.Equal(t, []byte{0, 0}, I2OSP(big.NewInt(int64(0)), 2)) + assert.Equal(t, []byte{0, 1}, I2OSP(big.NewInt(int64(1)), 2)) + assert.Equal(t, []byte{0, 255}, I2OSP(big.NewInt(int64(255)), 2)) + assert.Equal(t, []byte{1, 0}, I2OSP(big.NewInt(int64(256)), 2)) + assert.Equal(t, []byte{255, 255}, I2OSP(big.NewInt(int64(65535)), 2)) } func TestIS2OP(t *testing.T) { - assert.Equal(t, OS2IP([]byte{0, 0}).Int64(), int64(0)) - assert.Equal(t, OS2IP([]byte{0, 1}).Int64(), int64(1)) - assert.Equal(t, OS2IP([]byte{0, 255}).Int64(), int64(255)) - assert.Equal(t, OS2IP([]byte{1, 0}).Int64(), int64(256)) - assert.Equal(t, OS2IP([]byte{255, 255}).Int64(), int64(65535)) + assert.Equal(t, int64(0), OS2IP([]byte{0, 0}).Int64()) + assert.Equal(t, int64(1), OS2IP([]byte{0, 1}).Int64()) + assert.Equal(t, int64(255), OS2IP([]byte{0, 255}).Int64()) + assert.Equal(t, int64(256), OS2IP([]byte{1, 0}).Int64()) + assert.Equal(t, int64(65535), OS2IP([]byte{255, 255}).Int64()) } func TestLogScale(t *testing.T) { diff --git a/wallet/addresspath/path_test.go b/wallet/addresspath/path_test.go index 637451659..8d3632a67 100644 --- a/wallet/addresspath/path_test.go +++ b/wallet/addresspath/path_test.go @@ -22,7 +22,7 @@ func TestPathToString(t *testing.T) { {NewPath(h, h+1, h+1000000000), "m/0'/1'/1000000000'"}, } for i, test := range tests { - assert.Equal(t, test.path.String(), test.wantStr, "case %d failed", i) + assert.Equal(t, test.wantStr, test.path.String(), "case %d failed", i) } } @@ -46,7 +46,7 @@ func TestStringToPath(t *testing.T) { } for i, test := range tests { path, err := FromString(test.str) - assert.Equal(t, path, test.wantPath, "case %d failed", i) + assert.Equal(t, test.wantPath, path, "case %d failed", i) assert.ErrorIsf(t, err, test.wantErr, "case %d failed", i) } } diff --git a/wallet/encrypter/encrypter_test.go b/wallet/encrypter/encrypter_test.go index bf8a000ae..363c8a081 100644 --- a/wallet/encrypter/encrypter_test.go +++ b/wallet/encrypter/encrypter_test.go @@ -8,7 +8,7 @@ import ( func TestNopeEncrypter(t *testing.T) { e := NopeEncrypter() - assert.Equal(t, e.Method, "") + assert.Equal(t, "", e.Method) assert.Nil(t, e.Params) assert.False(t, e.IsEncrypted()) @@ -17,13 +17,13 @@ func TestNopeEncrypter(t *testing.T) { assert.ErrorIs(t, err, ErrInvalidPassword) enc, err := e.Encrypt(msg, "") assert.NoError(t, err) - assert.Equal(t, enc, msg) + assert.Equal(t, msg, enc) _, err = e.Decrypt(enc, "password") assert.ErrorIs(t, err, ErrInvalidPassword) dec, err := e.Decrypt(enc, "") assert.NoError(t, err) - assert.Equal(t, dec, msg) + assert.Equal(t, msg, dec) } func TestDefaultEncrypter(t *testing.T) { @@ -33,10 +33,10 @@ func TestDefaultEncrypter(t *testing.T) { OptionParallelism(5), } e := DefaultEncrypter(opts...) - assert.Equal(t, e.Method, "ARGON2ID-AES_256_CTR-MACV1") - assert.Equal(t, e.Params["iterations"], "3") - assert.Equal(t, e.Params["memory"], "4") - assert.Equal(t, e.Params["parallelism"], "5") + assert.Equal(t, "ARGON2ID-AES_256_CTR-MACV1", e.Method) + assert.Equal(t, "3", e.Params["iterations"]) + assert.Equal(t, "4", e.Params["memory"]) + assert.Equal(t, "5", e.Params["parallelism"]) assert.True(t, e.IsEncrypted()) } diff --git a/wallet/vault/utils_test.go b/wallet/vault/utils_test.go index d2edfe46f..64b08d8ae 100644 --- a/wallet/vault/utils_test.go +++ b/wallet/vault/utils_test.go @@ -49,7 +49,7 @@ func TestValidateMnemonic(t *testing.T) { for i, test := range tests { err := CheckMnemonic(test.mnenomic) if err != nil { - assert.Equal(t, err.Error(), test.errStr, "test %v failed", i) + assert.Equal(t, test.errStr, err.Error(), "test %v failed", i) } } } diff --git a/wallet/vault/vault_test.go b/wallet/vault/vault_test.go index 3f93886fa..627b19428 100644 --- a/wallet/vault/vault_test.go +++ b/wallet/vault/vault_test.go @@ -87,36 +87,36 @@ func TestAddressInfo(t *testing.T) { switch path.Purpose() { case H(PurposeBLS12381): if addr.IsValidatorAddress() { - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/1'/%d", - PurposeBLS12381, td.vault.CoinType, path.AddressIndex())) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/1'/%d", + PurposeBLS12381, td.vault.CoinType, path.AddressIndex()), info.Path) } if addr.IsAccountAddress() { - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/2'/%d", - PurposeBLS12381, td.vault.CoinType, path.AddressIndex())) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/2'/%d", + PurposeBLS12381, td.vault.CoinType, path.AddressIndex()), info.Path) } case H(PurposeImportPrivateKey): if addr.IsValidatorAddress() { - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/1'/%d'", - PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart)) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/1'/%d'", + PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart), info.Path) } if addr.IsAccountAddress() { - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/2'/%d'", - PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart)) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/2'/%d'", + PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart), info.Path) } } } // Neutered neutered := td.vault.Neuter() - assert.Equal(t, neutered.AddressCount(), 6) + assert.Equal(t, 6, neutered.AddressCount()) } func TestSortAddressInfo(t *testing.T) { td := setup(t) - assert.Equal(t, td.vault.AddressCount(), 6) + assert.Equal(t, 6, td.vault.AddressCount()) infos := td.vault.AddressInfos() assert.Equal(t, "m/12381'/21888'/1'/0", infos[0].Path) @@ -140,7 +140,7 @@ func TestAllAccountAddresses(t *testing.T) { func TestAllValidatorAddresses(t *testing.T) { td := setup(t) - assert.Equal(t, td.vault.AddressCount(), 6) + assert.Equal(t, 6, td.vault.AddressCount()) validatorAddrs := td.vault.AllValidatorAddresses() for _, i := range validatorAddrs { @@ -151,11 +151,11 @@ func TestAllValidatorAddresses(t *testing.T) { switch path.Purpose() { case H(PurposeBLS12381): - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/1'/%d", - PurposeBLS12381, td.vault.CoinType, path.AddressIndex())) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/1'/%d", + PurposeBLS12381, td.vault.CoinType, path.AddressIndex()), info.Path) case H(PurposeImportPrivateKey): - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/1'/%d'", - PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart)) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/1'/%d'", + PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart), info.Path) } } } @@ -208,13 +208,13 @@ func TestAllImportedPrivateKeysAddresses(t *testing.T) { path, _ := addresspath.FromString(info.Path) if addr.IsValidatorAddress() { - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/1'/%d'", - PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart)) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/1'/%d'", + PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart), info.Path) } if addr.IsAccountAddress() { - assert.Equal(t, info.Path, fmt.Sprintf("m/%d'/%d'/2'/%d'", - PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart)) + assert.Equal(t, fmt.Sprintf("m/%d'/%d'/2'/%d'", + PurposeImportPrivateKey, td.vault.CoinType, path.AddressIndex()-hdkeychain.HardenedKeyStart), info.Path) } } } @@ -228,7 +228,7 @@ func TestNewBLSAccountAddress(t *testing.T) { assert.NotEmpty(t, addressInfo.Address) assert.NotEmpty(t, addressInfo.PublicKey) assert.Contains(t, addressInfo.Path, "m/12381'/21888'/2'") - assert.Equal(t, addressInfo.Label, label) + assert.Equal(t, label, addressInfo.Label) } func TestNewValidatorAddress(t *testing.T) { @@ -240,7 +240,7 @@ func TestNewValidatorAddress(t *testing.T) { assert.NotEmpty(t, addressInfo.Address) assert.NotEmpty(t, addressInfo.PublicKey) assert.Contains(t, addressInfo.Path, "m/12381'/21888'/1'") - assert.Equal(t, addressInfo.Label, label) + assert.Equal(t, label, addressInfo.Label) } func TestRecover(t *testing.T) { @@ -394,14 +394,14 @@ func TestSetLabel(t *testing.T) { invAddr := td.RandAccAddress().String() err := td.vault.SetLabel(invAddr, "i have label") assert.ErrorIs(t, err, NewErrAddressNotFound(invAddr)) - assert.Equal(t, td.vault.Label(invAddr), "") + assert.Equal(t, "", td.vault.Label(invAddr)) }) t.Run("Update label", func(t *testing.T) { testAddr := td.vault.AddressInfos()[0].Address - err := td.vault.SetLabel(testAddr, "i have label") + err := td.vault.SetLabel(testAddr, "I have a label") assert.NoError(t, err) - assert.Equal(t, td.vault.Label(testAddr), "i have label") + assert.Equal(t, "I have a label", td.vault.Label(testAddr)) }) t.Run("Remove label", func(t *testing.T) { diff --git a/wallet/wallet_test.go b/wallet/wallet_test.go index fae4ccbc8..9704b91fc 100644 --- a/wallet/wallet_test.go +++ b/wallet/wallet_test.go @@ -58,8 +58,8 @@ func setup(t *testing.T) *testData { wallet.WithCustomServers([]string{gRPCServer.Address()})) assert.NoError(t, err) assert.False(t, wlt.IsEncrypted()) - assert.Equal(t, wlt.Path(), walletPath) - assert.Equal(t, wlt.Name(), path.Base(walletPath)) + assert.Equal(t, walletPath, wlt.Path()) + assert.Equal(t, path.Base(walletPath), wlt.Name()) return &testData{ TestSuite: ts, @@ -195,7 +195,7 @@ func TestSignMessage(t *testing.T) { sig, err := td.wallet.SignMessage(td.password, td.wallet.AllAccountAddresses()[0].Address, msg) assert.NoError(t, err) - assert.Equal(t, sig, expectedSig) + assert.Equal(t, expectedSig, sig) } func TestKeyInfo(t *testing.T) { @@ -337,7 +337,7 @@ func TestMakeTransferTx(t *testing.T) { td.Close() _, err := td.wallet.MakeTransferTx(td.RandAccAddress().String(), receiverInfo.String(), amt) - assert.Equal(t, errors.Code(err), errors.ErrGeneric) + assert.Equal(t, errors.ErrGeneric, errors.Code(err)) }) } @@ -462,7 +462,7 @@ func TestMakeBondTx(t *testing.T) { td.Close() _, err := td.wallet.MakeBondTx(td.RandAccAddress().String(), receiver.Address().String(), "", amt) - assert.Equal(t, errors.Code(err), errors.ErrGeneric) + assert.Equal(t, errors.ErrGeneric, errors.Code(err)) }) } @@ -506,7 +506,7 @@ func TestMakeUnbondTx(t *testing.T) { td.Close() _, err := td.wallet.MakeUnbondTx(td.RandAccAddress().String()) - assert.Equal(t, errors.Code(err), errors.ErrGeneric) + assert.Equal(t, errors.ErrGeneric, errors.Code(err)) }) } @@ -556,7 +556,7 @@ func TestMakeWithdrawTx(t *testing.T) { td.Close() _, err := td.wallet.MakeWithdrawTx(td.RandAccAddress().String(), receiverInfo.Address, amt) - assert.Equal(t, errors.Code(err), errors.ErrGeneric) + assert.Equal(t, errors.ErrGeneric, errors.Code(err)) }) } diff --git a/www/grpc/basicauth/basicauth_test.go b/www/grpc/basicauth/basicauth_test.go index 3e88e6048..613e551fc 100644 --- a/www/grpc/basicauth/basicauth_test.go +++ b/www/grpc/basicauth/basicauth_test.go @@ -3,6 +3,8 @@ package basicauth import ( "fmt" "testing" + + "github.com/stretchr/testify/assert" ) func TestMakeCredentials(t *testing.T) { @@ -24,9 +26,7 @@ func TestMakeCredentials(t *testing.T) { result := EncodeBasicAuth(tc.username, tc.password) // Check if the result matches the expected output - if result != tc.expected { - t.Errorf("basicAuth(%s, %s) = %s; want %s", tc.username, tc.password, result, tc.expected) - } + assert.Equal(t, tc.expected, result) }) } } diff --git a/www/grpc/blockchain_test.go b/www/grpc/blockchain_test.go index 1e8a16850..8a9113030 100644 --- a/www/grpc/blockchain_test.go +++ b/www/grpc/blockchain_test.go @@ -33,9 +33,9 @@ func TestGetBlock(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, res) - assert.Equal(t, res.Height, height) - assert.Equal(t, res.Hash, b.Hash().String()) - assert.Equal(t, res.Data, hex.EncodeToString(data)) + assert.Equal(t, height, res.Height) + assert.Equal(t, b.Hash().String(), res.Hash) + assert.Equal(t, hex.EncodeToString(data), res.Data) assert.Empty(t, res.Header) assert.Empty(t, res.Txs) }) @@ -46,18 +46,18 @@ func TestGetBlock(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, res) - assert.Equal(t, res.Height, height) - assert.Equal(t, res.Hash, b.Hash().String()) + assert.Equal(t, height, res.Height) + assert.Equal(t, b.Hash().String(), res.Hash) assert.Empty(t, res.Data) assert.NotEmpty(t, res.Header) - assert.Equal(t, res.PrevCert.Committers, b.PrevCertificate().Committers()) - assert.Equal(t, res.PrevCert.Absentees, b.PrevCertificate().Absentees()) + assert.Equal(t, b.PrevCertificate().Committers(), res.PrevCert.Committers) + assert.Equal(t, b.PrevCertificate().Absentees(), res.PrevCert.Absentees) for i, trx := range res.Txs { blockTrx := b.Transactions()[i] b, err := blockTrx.Bytes() assert.NoError(t, err) - assert.Equal(t, blockTrx.ID().String(), trx.Id) - assert.Equal(t, hex.EncodeToString(b), trx.Data) + assert.Equal(t, trx.Id, blockTrx.ID().String()) + assert.Equal(t, trx.Data, hex.EncodeToString(b)) assert.Zero(t, trx.LockTime) assert.Empty(t, trx.Signature) assert.Empty(t, trx.PublicKey) @@ -70,19 +70,19 @@ func TestGetBlock(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, res) - assert.Equal(t, res.Height, height) - assert.Equal(t, res.Hash, b.Hash().String()) + assert.Equal(t, height, res.Height) + assert.Equal(t, b.Hash().String(), res.Hash) assert.Empty(t, res.Data) assert.NotEmpty(t, res.Header) assert.NotEmpty(t, res.Txs) for i, trx := range res.Txs { blockTrx := b.Transactions()[i] - assert.Equal(t, blockTrx.ID().String(), trx.Id) + assert.Equal(t, trx.Id, blockTrx.ID().String()) assert.Empty(t, trx.Data) - assert.Equal(t, blockTrx.LockTime(), trx.LockTime) - assert.Equal(t, blockTrx.Signature().String(), trx.Signature) - assert.Equal(t, blockTrx.PublicKey().String(), trx.PublicKey) + assert.Equal(t, trx.LockTime, blockTrx.LockTime()) + assert.Equal(t, trx.Signature, blockTrx.Signature().String()) + assert.Equal(t, trx.PublicKey, blockTrx.PublicKey().String()) } }) @@ -197,8 +197,8 @@ func TestGetAccount(t *testing.T) { assert.Nil(t, err) assert.NotNil(t, res) - assert.Equal(t, res.Account.Balance, acc.Balance().ToNanoPAC()) - assert.Equal(t, res.Account.Number, acc.Number()) + assert.Equal(t, acc.Balance().ToNanoPAC(), res.Account.Balance) + assert.Equal(t, acc.Number(), res.Account.Number) }) assert.Nil(t, conn.Close(), "Error closing connection") @@ -324,7 +324,7 @@ func TestGetPublicKey(t *testing.T) { assert.Nil(t, err) assert.NotNil(t, res) - assert.Equal(t, res.PublicKey, val.PublicKey().String()) + assert.Equal(t, val.PublicKey().String(), res.PublicKey) }) assert.Nil(t, conn.Close(), "Error closing connection") @@ -349,8 +349,8 @@ func TestConsensusInfo(t *testing.T) { assert.NotNil(t, res) assert.False(t, res.Instances[0].Active, true) assert.True(t, res.Instances[1].Active, true) - assert.Equal(t, res.Instances[1].Height, uint32(100)) - assert.Equal(t, res.Instances[0].Votes[0].Type, pactus.VoteType_VOTE_PREPARE) + assert.Equal(t, uint32(100), res.Instances[1].Height) + assert.Equal(t, pactus.VoteType_VOTE_PREPARE, res.Instances[0].Votes[0].Type) }) assert.Nil(t, conn.Close(), "Error closing connection") diff --git a/www/grpc/middleware_test.go b/www/grpc/middleware_test.go index d1064dd6f..117982354 100644 --- a/www/grpc/middleware_test.go +++ b/www/grpc/middleware_test.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "testing" + "github.com/stretchr/testify/assert" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" @@ -64,9 +65,8 @@ func TestBasicAuth(t *testing.T) { _, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, mockUnaryHandler) - if got, want := status.Code(err), tt.expectedError; got != want { - t.Errorf("expected error code %v, got %v", want, got) - } + got, want := status.Code(err), tt.expectedError + assert.Equal(t, want, got) }) } } @@ -77,7 +77,5 @@ func TestGrpcRecovery(t *testing.T) { interceptor := s.server.Recovery() _, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{}, mockUnaryPanicHandler) - if status.Code(err) != codes.Unknown { - t.Errorf("expected error code %v, got %v", codes.Unknown, err) - } + assert.Equal(t, codes.Unknown, status.Code(err)) } diff --git a/www/grpc/server_test.go b/www/grpc/server_test.go index 3f8d9091d..1970a65d8 100644 --- a/www/grpc/server_test.go +++ b/www/grpc/server_test.go @@ -114,9 +114,7 @@ func (td *testData) blockchainClient(t *testing.T) (*grpc.ClientConn, pactus.Blo conn, err := grpc.NewClient("passthrough://bufnet", grpc.WithContextDialer(td.bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatalf("Failed to dial blockchain server: %v", err) - } + assert.NoError(t, err) return conn, pactus.NewBlockchainClient(conn) } @@ -127,9 +125,7 @@ func (td *testData) networkClient(t *testing.T) (*grpc.ClientConn, pactus.Networ conn, err := grpc.NewClient("passthrough://bufnet", grpc.WithContextDialer(td.bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatalf("Failed to dial network server: %v", err) - } + assert.NoError(t, err) return conn, pactus.NewNetworkClient(conn) } @@ -140,9 +136,7 @@ func (td *testData) transactionClient(t *testing.T) (*grpc.ClientConn, pactus.Tr conn, err := grpc.NewClient("passthrough://bufnet", grpc.WithContextDialer(td.bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatalf("Failed to dial transaction server: %v", err) - } + assert.NoError(t, err) return conn, pactus.NewTransactionClient(conn) } @@ -153,9 +147,7 @@ func (td *testData) walletClient(t *testing.T) (*grpc.ClientConn, pactus.WalletC conn, err := grpc.NewClient("passthrough://bufnet", grpc.WithContextDialer(td.bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatalf("Failed to dial wallet server: %v", err) - } + assert.NoError(t, err) return conn, pactus.NewWalletClient(conn) } @@ -166,9 +158,7 @@ func (td *testData) utilClient(t *testing.T) (*grpc.ClientConn, pactus.UtilsClie conn, err := grpc.NewClient("passthrough://bufnet", grpc.WithContextDialer(td.bufDialer), grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatalf("Failed to dial wallet server: %v", err) - } + assert.NoError(t, err) return conn, pactus.NewUtilsClient(conn) } diff --git a/www/grpc/transaction_test.go b/www/grpc/transaction_test.go index 76a4f5c57..7a3a9dd08 100644 --- a/www/grpc/transaction_test.go +++ b/www/grpc/transaction_test.go @@ -232,8 +232,8 @@ func TestCalculateFee(t *testing.T) { FixedAmount: false, }) assert.NoError(t, err) - assert.Equal(t, res.Amount, amt.ToNanoPAC()) - assert.Equal(t, res.Fee, expectedFee.ToNanoPAC()) + assert.Equal(t, amt.ToNanoPAC(), res.Amount) + assert.Equal(t, expectedFee.ToNanoPAC(), res.Fee) }) t.Run("Fixed amount", func(t *testing.T) { @@ -246,8 +246,8 @@ func TestCalculateFee(t *testing.T) { FixedAmount: true, }) assert.NoError(t, err) - assert.Equal(t, res.Amount, (amt - expectedFee).ToNanoPAC()) - assert.Equal(t, res.Fee, expectedFee.ToNanoPAC()) + assert.Equal(t, (amt - expectedFee).ToNanoPAC(), res.Amount) + assert.Equal(t, expectedFee.ToNanoPAC(), res.Fee) }) t.Run("Insufficient amount to pay fee", func(t *testing.T) { @@ -261,7 +261,7 @@ func TestCalculateFee(t *testing.T) { }) assert.NoError(t, err) assert.Negative(t, res.Amount) - assert.Equal(t, res.Fee, expectedFee.ToNanoPAC()) + assert.Equal(t, expectedFee.ToNanoPAC(), res.Fee) }) assert.Nil(t, conn.Close(), "Error closing connection") diff --git a/www/grpc/utils_test.go b/www/grpc/utils_test.go index 2060d2893..5a9f79dad 100644 --- a/www/grpc/utils_test.go +++ b/www/grpc/utils_test.go @@ -26,7 +26,7 @@ func TestSignMessageWithPrivateKey(t *testing.T) { }) assert.Nil(t, err) - assert.Equal(t, res.Signature, expectedSig) + assert.Equal(t, expectedSig, res.Signature) }) t.Run("", func(t *testing.T) { diff --git a/www/grpc/wallet_test.go b/www/grpc/wallet_test.go index 96c534df3..0ad88944f 100644 --- a/www/grpc/wallet_test.go +++ b/www/grpc/wallet_test.go @@ -277,7 +277,7 @@ func TestGetTotalBalance(t *testing.T) { WalletName: walletName, }) assert.NoError(t, err) - assert.Equal(t, res.WalletName, walletName) + assert.Equal(t, walletName, res.WalletName) assert.Zero(t, res.TotalBalance) }) diff --git a/www/http/blockchain_test.go b/www/http/blockchain_test.go index 4463ed3e0..7dcc24872 100644 --- a/www/http/blockchain_test.go +++ b/www/http/blockchain_test.go @@ -21,7 +21,7 @@ func TestBlockchainInfo(t *testing.T) { td.httpServer.BlockchainHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "10") td.StopServers() @@ -38,7 +38,7 @@ func TestBlock(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"hash": b.Hash().String()}) td.httpServer.GetBlockByHashHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), b.Hash().String()) }) @@ -48,7 +48,7 @@ func TestBlock(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"height": "100"}) td.httpServer.GetBlockByHeightHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) }) t.Run("Shall return an error, invalid height", func(t *testing.T) { @@ -57,7 +57,7 @@ func TestBlock(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"height": "x"}) td.httpServer.GetBlockByHeightHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, non exists", func(t *testing.T) { @@ -66,7 +66,7 @@ func TestBlock(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"hash": td.RandHash().String()}) td.httpServer.GetBlockByHashHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, invalid hash", func(t *testing.T) { @@ -76,7 +76,7 @@ func TestBlock(t *testing.T) { td.httpServer.GetBlockByHashHandler(w, r) fmt.Println(w.Body) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, empty hash", func(t *testing.T) { @@ -86,7 +86,7 @@ func TestBlock(t *testing.T) { td.httpServer.GetBlockByHashHandler(w, r) fmt.Println(w.Body) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, no hash", func(t *testing.T) { @@ -95,7 +95,7 @@ func TestBlock(t *testing.T) { td.httpServer.GetBlockByHashHandler(w, r) fmt.Println(w.Body) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) }) td.StopServers() @@ -112,7 +112,7 @@ func TestAccount(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"address": addr.String()}) td.httpServer.GetAccountHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), acc.Balance().String()) fmt.Println(w.Body) }) @@ -123,7 +123,7 @@ func TestAccount(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"address": td.RandAccAddress().String()}) td.httpServer.GetAccountHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, invalid address", func(t *testing.T) { @@ -132,7 +132,7 @@ func TestAccount(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"address": "invalid-address"}) td.httpServer.GetAccountHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -142,7 +142,7 @@ func TestAccount(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"address": ""}) td.httpServer.GetAccountHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -151,7 +151,7 @@ func TestAccount(t *testing.T) { r := new(http.Request) td.httpServer.GetAccountHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -169,7 +169,7 @@ func TestValidator(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"address": td.RandAccAddress().String()}) td.httpServer.GetValidatorHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) }) t.Run("Shall return an error, invalid address", func(t *testing.T) { @@ -178,7 +178,7 @@ func TestValidator(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"address": "invalid-address"}) td.httpServer.GetValidatorHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -188,7 +188,7 @@ func TestValidator(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"address": ""}) td.httpServer.GetValidatorHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -197,7 +197,7 @@ func TestValidator(t *testing.T) { r := new(http.Request) td.httpServer.GetValidatorHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -208,7 +208,7 @@ func TestValidator(t *testing.T) { td.httpServer.GetValidatorHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "0.987") fmt.Println(w.Body) }) @@ -229,7 +229,7 @@ func TestValidatorByNumber(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"number": strconv.Itoa(int(val.Number()))}) td.httpServer.GetValidatorByNumberHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) fmt.Println(w.Body) }) @@ -241,7 +241,7 @@ func TestValidatorByNumber(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"number": strconv.Itoa(int(val.Number() + 1))}) td.httpServer.GetValidatorByNumberHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -251,7 +251,7 @@ func TestValidatorByNumber(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"number": ""}) td.httpServer.GetValidatorByNumberHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -261,7 +261,7 @@ func TestValidatorByNumber(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"number": "not-a-number"}) td.httpServer.GetValidatorByNumberHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -270,7 +270,7 @@ func TestValidatorByNumber(t *testing.T) { r := new(http.Request) td.httpServer.GetValidatorByNumberHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) @@ -291,7 +291,7 @@ func TestConsensusInfo(t *testing.T) { td.httpServer.ConsensusHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "2") assert.Contains(t, w.Body.String(), v2.Signer().String()) diff --git a/www/http/http_test.go b/www/http/http_test.go index 6e6fdb4ea..4cba5e117 100644 --- a/www/http/http_test.go +++ b/www/http/http_test.go @@ -91,7 +91,7 @@ func TestRootHandler(t *testing.T) { w := httptest.NewRecorder() r := new(http.Request) td.httpServer.RootHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) fmt.Println(w.Body) td.StopServers() diff --git a/www/http/network_test.go b/www/http/network_test.go index 72370e343..31a04cb42 100644 --- a/www/http/network_test.go +++ b/www/http/network_test.go @@ -34,7 +34,7 @@ func TestNetworkInfo(t *testing.T) { td.httpServer.NetworkHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), "Network Name") assert.Contains(t, w.Body.String(), "Connected Peers Count") diff --git a/www/http/transaction_test.go b/www/http/transaction_test.go index 4c32f91eb..a23ec104a 100644 --- a/www/http/transaction_test.go +++ b/www/http/transaction_test.go @@ -22,7 +22,7 @@ func TestTransaction(t *testing.T) { r = mux.SetURLVars(r, map[string]string{"id": testTx.ID().String()}) td.httpServer.GetTransactionHandler(w, r) - assert.Equal(t, w.Code, 200) + assert.Equal(t, 200, w.Code) assert.Contains(t, w.Body.String(), testTx.Signature().String()) assert.Contains(t, w.Body.String(), testTx.Signature().String()) fmt.Println(w.Body) @@ -33,7 +33,7 @@ func TestTransaction(t *testing.T) { r := new(http.Request) td.httpServer.GetTransactionHandler(w, r) - assert.Equal(t, w.Code, 400) + assert.Equal(t, 400, w.Code) fmt.Println(w.Body) }) diff --git a/www/nanomsg/event/event_test.go b/www/nanomsg/event/event_test.go index 96c43f326..eec2bc1ee 100644 --- a/www/nanomsg/event/event_test.go +++ b/www/nanomsg/event/event_test.go @@ -12,30 +12,30 @@ func TestCreateBlockEvent(t *testing.T) { h, _ := hash.FromString("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") height := uint32(0x2134) e := CreateBlockEvent(h, height) - assert.Equal(t, e, Event{ + assert.Equal(t, Event{ 0x1, 0x1, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x34, 0x21, 0x0, 0x0, - }) + }, e) } func TestCreateNewTransactionEvent(t *testing.T) { h, _ := hash.FromString("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") height := uint32(0x2134) e := CreateTransactionEvent(h, height) - assert.Equal(t, e, Event{ + assert.Equal(t, Event{ 0x1, 0x2, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x34, 0x21, 0x0, 0x0, - }) + }, e) } func TestCreateAccountChangeEvent(t *testing.T) { addr, _ := crypto.AddressFromString("pc1p0hrct7eflrpw4ccrttxzs4qud2axex4dcdzdfr") height := uint32(0x2134) e := CreateAccountChangeEvent(addr, height) - assert.Equal(t, e, Event{ + assert.Equal(t, Event{ 0x01, 0x03, 0x1, 0x7d, 0xc7, 0x85, 0xfb, 0x29, 0xf8, 0xc2, 0xea, 0xe3, 0x3, 0x5a, 0xcc, 0x28, 0x54, 0x1c, 0x6a, 0xba, 0x6c, 0x9a, 0xad, 0x34, 0x21, 0x0, 0x0, - }) + }, e) }