diff --git a/abci/example/kvstore/kvstore_test.go b/abci/example/kvstore/kvstore_test.go index f3640f731..cb402ef71 100644 --- a/abci/example/kvstore/kvstore_test.go +++ b/abci/example/kvstore/kvstore_test.go @@ -344,7 +344,7 @@ func testClient(ctx context.Context, t *testing.T, app abciclient.Client, tx []b Path: "/store", Data: []byte(key), }) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, code.CodeTypeOK, resQuery.Code) require.Equal(t, key, string(resQuery.Key)) require.Equal(t, value, string(resQuery.Value)) @@ -356,7 +356,7 @@ func testClient(ctx context.Context, t *testing.T, app abciclient.Client, tx []b Data: []byte(key), Prove: true, }) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, code.CodeTypeOK, resQuery.Code) require.Equal(t, key, string(resQuery.Key)) require.Equal(t, value, string(resQuery.Value)) diff --git a/abci/types/messages_test.go b/abci/types/messages_test.go index 491d10c7f..fb219fe07 100644 --- a/abci/types/messages_test.go +++ b/abci/types/messages_test.go @@ -14,7 +14,7 @@ import ( func TestMarshalJSON(t *testing.T) { b, err := json.Marshal(&ResponseDeliverTx{}) - assert.Nil(t, err) + assert.NoError(t, err) // include empty fields. assert.True(t, strings.Contains(string(b), "code")) r1 := ResponseCheckTx{ @@ -31,11 +31,11 @@ func TestMarshalJSON(t *testing.T) { }, } b, err = json.Marshal(&r1) - assert.Nil(t, err) + assert.NoError(t, err) var r2 ResponseCheckTx err = json.Unmarshal(b, &r2) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, r1, r2) } @@ -49,11 +49,11 @@ func TestWriteReadMessageSimple(t *testing.T) { for _, c := range cases { buf := new(bytes.Buffer) err := WriteMessage(c, buf) - assert.Nil(t, err) + assert.NoError(t, err) msg := new(RequestEcho) err = ReadMessage(buf, msg) - assert.Nil(t, err) + assert.NoError(t, err) assert.True(t, proto.Equal(c, msg)) } @@ -71,11 +71,11 @@ func TestWriteReadMessage(t *testing.T) { for _, c := range cases { buf := new(bytes.Buffer) err := WriteMessage(c, buf) - assert.Nil(t, err) + assert.NoError(t, err) msg := new(tmproto.Header) err = ReadMessage(buf, msg) - assert.Nil(t, err) + assert.NoError(t, err) assert.True(t, proto.Equal(c, msg)) } @@ -103,11 +103,11 @@ func TestWriteReadMessage2(t *testing.T) { for _, c := range cases { buf := new(bytes.Buffer) err := WriteMessage(c, buf) - assert.Nil(t, err) + assert.NoError(t, err) msg := new(ResponseCheckTx) err = ReadMessage(buf, msg) - assert.Nil(t, err) + assert.NoError(t, err) assert.True(t, proto.Equal(c, msg)) } diff --git a/cmd/tendermint/commands/root_test.go b/cmd/tendermint/commands/root_test.go index 6d5143f4e..fcde3eb69 100644 --- a/cmd/tendermint/commands/root_test.go +++ b/cmd/tendermint/commands/root_test.go @@ -74,7 +74,7 @@ func TestRootHome(t *testing.T) { idxString := strconv.Itoa(i) err := testSetup(defaultRoot, tc.args, tc.env) - require.Nil(t, err, idxString) + require.NoError(t, err, idxString) assert.Equal(t, tc.root, config.RootDir, idxString) assert.Equal(t, tc.root, config.P2P.RootDir, idxString) @@ -106,7 +106,7 @@ func TestRootFlagsEnv(t *testing.T) { idxString := strconv.Itoa(i) err := testSetup(defaultRoot, tc.args, tc.env) - require.Nil(t, err, idxString) + require.NoError(t, err, idxString) assert.Equal(t, tc.logLevel, config.LogLevel, idxString) } @@ -139,12 +139,12 @@ func TestRootConfig(t *testing.T) { // XXX: path must match cfg.defaultConfigPath configFilePath := filepath.Join(defaultRoot, "config") err := tmos.EnsureDir(configFilePath, 0700) - require.Nil(t, err) + require.NoError(t, err) // write the non-defaults to a different path // TODO: support writing sub configs so we can test that too err = WriteConfigVals(configFilePath, cvals) - require.Nil(t, err) + require.NoError(t, err) rootCmd := testRootCmd() cmd := cli.PrepareBaseCmd(rootCmd, "TM", defaultRoot) @@ -152,7 +152,7 @@ func TestRootConfig(t *testing.T) { // run with the args and env tc.args = append([]string{rootCmd.Use}, tc.args...) err = cli.RunWithArgs(cmd, tc.args, tc.env) - require.Nil(t, err, idxString) + require.NoError(t, err, idxString) assert.Equal(t, tc.logLvl, config.LogLevel, idxString) } diff --git a/config/config_test.go b/config/config_test.go index b3dabfb08..d768a1702 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -10,21 +10,19 @@ import ( ) func TestDefaultConfig(t *testing.T) { - assert := assert.New(t) - // set up some defaults cfg := DefaultConfig() - assert.NotNil(cfg.P2P) - assert.NotNil(cfg.Mempool) - assert.NotNil(cfg.Consensus) + assert.NotNil(t, cfg.P2P) + assert.NotNil(t, cfg.Mempool) + assert.NotNil(t, cfg.Consensus) // check the root dir stuff... cfg.SetRoot("/foo") cfg.Genesis = "bar" cfg.DBPath = "/opt/data" - assert.Equal("/foo/bar", cfg.GenesisFile()) - assert.Equal("/opt/data", cfg.DBDir()) + assert.Equal(t, "/foo/bar", cfg.GenesisFile()) + assert.Equal(t, "/opt/data", cfg.DBDir()) } func TestConfigValidateBasic(t *testing.T) { @@ -37,19 +35,18 @@ func TestConfigValidateBasic(t *testing.T) { } func TestTLSConfiguration(t *testing.T) { - assert := assert.New(t) cfg := DefaultConfig() cfg.SetRoot("/home/user") cfg.RPC.TLSCertFile = "file.crt" - assert.Equal("/home/user/config/file.crt", cfg.RPC.CertFile()) + assert.Equal(t, "/home/user/config/file.crt", cfg.RPC.CertFile()) cfg.RPC.TLSKeyFile = "file.key" - assert.Equal("/home/user/config/file.key", cfg.RPC.KeyFile()) + assert.Equal(t, "/home/user/config/file.key", cfg.RPC.KeyFile()) cfg.RPC.TLSCertFile = "/abs/path/to/file.crt" - assert.Equal("/abs/path/to/file.crt", cfg.RPC.CertFile()) + assert.Equal(t, "/abs/path/to/file.crt", cfg.RPC.CertFile()) cfg.RPC.TLSKeyFile = "/abs/path/to/file.key" - assert.Equal("/abs/path/to/file.key", cfg.RPC.KeyFile()) + assert.Equal(t, "/abs/path/to/file.key", cfg.RPC.KeyFile()) } func TestBaseConfigValidateBasic(t *testing.T) { diff --git a/config/toml_test.go b/config/toml_test.go index c062d25e4..fa7e88da0 100644 --- a/config/toml_test.go +++ b/config/toml_test.go @@ -14,26 +14,24 @@ func ensureFiles(t *testing.T, rootDir string, files ...string) { for _, f := range files { p := rootify(rootDir, f) _, err := os.Stat(p) - assert.Nil(t, err, p) + assert.NoError(t, err, p) } } func TestEnsureRoot(t *testing.T) { - require := require.New(t) - // setup temp dir for test tmpDir, err := os.MkdirTemp("", "config-test") - require.NoError(err) + require.NoError(t, err) defer os.RemoveAll(tmpDir) // create root dir EnsureRoot(tmpDir) - require.NoError(WriteConfigFile(tmpDir, DefaultConfig())) + require.NoError(t, WriteConfigFile(tmpDir, DefaultConfig())) // make sure config is set properly data, err := os.ReadFile(filepath.Join(tmpDir, defaultConfigFilePath)) - require.NoError(err) + require.NoError(t, err) checkConfig(t, string(data)) @@ -41,19 +39,17 @@ func TestEnsureRoot(t *testing.T) { } func TestEnsureTestRoot(t *testing.T) { - require := require.New(t) - testName := "ensureTestRoot" // create root dir cfg, err := ResetTestRoot(testName) - require.NoError(err) + require.NoError(t, err) defer os.RemoveAll(cfg.RootDir) rootDir := cfg.RootDir // make sure config is set properly data, err := os.ReadFile(filepath.Join(rootDir, defaultConfigFilePath)) - require.Nil(err) + require.NoError(t, err) checkConfig(t, string(data)) diff --git a/crypto/ed25519/ed25519_test.go b/crypto/ed25519/ed25519_test.go index 63c781a3b..a6acafc58 100644 --- a/crypto/ed25519/ed25519_test.go +++ b/crypto/ed25519/ed25519_test.go @@ -17,7 +17,7 @@ func TestSignAndValidateEd25519(t *testing.T) { msg := crypto.CRandBytes(128) sig, err := privKey.Sign(msg) - require.Nil(t, err) + require.NoError(t, err) // Test the signature assert.True(t, pubKey.VerifySignature(msg, sig)) diff --git a/crypto/merkle/proof_key_path_test.go b/crypto/merkle/proof_key_path_test.go index 0cc947643..75e48669f 100644 --- a/crypto/merkle/proof_key_path_test.go +++ b/crypto/merkle/proof_key_path_test.go @@ -34,7 +34,7 @@ func TestKeyPath(t *testing.T) { } res, err := KeyPathToKeys(path.String()) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, len(keys), len(res)) for i, key := range keys { diff --git a/crypto/merkle/proof_test.go b/crypto/merkle/proof_test.go index f0d2f8689..05a5ca369 100644 --- a/crypto/merkle/proof_test.go +++ b/crypto/merkle/proof_test.go @@ -79,58 +79,58 @@ func TestProofOperators(t *testing.T) { // Good popz := ProofOperators([]ProofOperator{op1, op2, op3, op4}) err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.Nil(t, err) + assert.NoError(t, err) err = popz.VerifyValue(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", bz("INPUT1")) - assert.Nil(t, err) + assert.NoError(t, err) // BAD INPUT err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1_WRONG")}) - assert.NotNil(t, err) + assert.Error(t, err) err = popz.VerifyValue(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", bz("INPUT1_WRONG")) - assert.NotNil(t, err) + assert.Error(t, err) // BAD KEY 1 err = popz.Verify(bz("OUTPUT4"), "/KEY3/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD KEY 2 err = popz.Verify(bz("OUTPUT4"), "KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD KEY 3 err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1/", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD KEY 4 err = popz.Verify(bz("OUTPUT4"), "//KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD KEY 5 err = popz.Verify(bz("OUTPUT4"), "/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD OUTPUT 1 err = popz.Verify(bz("OUTPUT4_WRONG"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD OUTPUT 2 err = popz.Verify(bz(""), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD POPZ 1 popz = []ProofOperator{op1, op2, op4} err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD POPZ 2 popz = []ProofOperator{op4, op3, op2, op1} err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) // BAD POPZ 3 popz = []ProofOperator{} err = popz.Verify(bz("OUTPUT4"), "/KEY4/KEY2/KEY1", [][]byte{bz("INPUT1")}) - assert.NotNil(t, err) + assert.Error(t, err) } func bz(s string) []byte { diff --git a/crypto/secp256k1/secp256k1_test.go b/crypto/secp256k1/secp256k1_test.go index 7a1109293..6cd53704c 100644 --- a/crypto/secp256k1/secp256k1_test.go +++ b/crypto/secp256k1/secp256k1_test.go @@ -52,7 +52,7 @@ func TestSignAndValidateSecp256k1(t *testing.T) { msg := crypto.CRandBytes(128) sig, err := privKey.Sign(msg) - require.Nil(t, err) + require.NoError(t, err) assert.True(t, pubKey.VerifySignature(msg, sig)) diff --git a/crypto/sr25519/sr25519_test.go b/crypto/sr25519/sr25519_test.go index de5c125f4..84283eaca 100644 --- a/crypto/sr25519/sr25519_test.go +++ b/crypto/sr25519/sr25519_test.go @@ -18,7 +18,7 @@ func TestSignAndValidateSr25519(t *testing.T) { msg := crypto.CRandBytes(128) sig, err := privKey.Sign(msg) - require.Nil(t, err) + require.NoError(t, err) // Test the signature assert.True(t, pubKey.VerifySignature(msg, sig)) diff --git a/crypto/xsalsa20symmetric/symmetric_test.go b/crypto/xsalsa20symmetric/symmetric_test.go index 160d49a9e..391d6e005 100644 --- a/crypto/xsalsa20symmetric/symmetric_test.go +++ b/crypto/xsalsa20symmetric/symmetric_test.go @@ -18,7 +18,7 @@ func TestSimple(t *testing.T) { ciphertext := EncryptSymmetric(plaintext, secret) plaintext2, err := DecryptSymmetric(ciphertext, secret) - require.Nil(t, err, "%+v", err) + require.NoError(t, err, "%+v", err) assert.Equal(t, plaintext, plaintext2) } @@ -35,6 +35,6 @@ func TestSimpleWithKDF(t *testing.T) { ciphertext := EncryptSymmetric(plaintext, secret) plaintext2, err := DecryptSymmetric(ciphertext, secret) - require.Nil(t, err, "%+v", err) + require.NoError(t, err, "%+v", err) assert.Equal(t, plaintext, plaintext2) } diff --git a/internal/consensus/replay_test.go b/internal/consensus/replay_test.go index 3972974d8..4e57dc592 100644 --- a/internal/consensus/replay_test.go +++ b/internal/consensus/replay_test.go @@ -380,7 +380,7 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { require.NoError(t, err) newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower) err = assertMempool(css[0].txNotifier).CheckTx(ctx, newValidatorTx1, nil, mempool.TxInfo{}) - assert.Nil(t, err) + assert.NoError(t, err) propBlock, _, err := css[0].createProposalBlock() // changeProposer(t, cs1, vs2) require.NoError(t, err) propBlockParts, err := propBlock.MakePartSet(partSize) @@ -414,7 +414,7 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { require.NoError(t, err) updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25) err = assertMempool(css[0].txNotifier).CheckTx(ctx, updateValidatorTx1, nil, mempool.TxInfo{}) - assert.Nil(t, err) + assert.NoError(t, err) propBlock, _, err = css[0].createProposalBlock() // changeProposer(t, cs1, vs2) require.NoError(t, err) propBlockParts, err = propBlock.MakePartSet(partSize) @@ -448,14 +448,14 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { require.NoError(t, err) newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower) err = assertMempool(css[0].txNotifier).CheckTx(ctx, newValidatorTx2, nil, mempool.TxInfo{}) - assert.Nil(t, err) + assert.NoError(t, err) newValidatorPubKey3, err := css[nVals+2].privValidator.GetPubKey(ctx) require.NoError(t, err) newVal3ABCI, err := encoding.PubKeyToProto(newValidatorPubKey3) require.NoError(t, err) newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower) err = assertMempool(css[0].txNotifier).CheckTx(ctx, newValidatorTx3, nil, mempool.TxInfo{}) - assert.Nil(t, err) + assert.NoError(t, err) propBlock, _, err = css[0].createProposalBlock() // changeProposer(t, cs1, vs2) require.NoError(t, err) propBlockParts, err = propBlock.MakePartSet(partSize) @@ -497,7 +497,7 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { removeValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0) err = assertMempool(css[0].txNotifier).CheckTx(ctx, removeValidatorTx2, nil, mempool.TxInfo{}) - assert.Nil(t, err) + assert.NoError(t, err) rs = css[0].GetRoundState() for i := 0; i < nVals+1; i++ { @@ -536,7 +536,7 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { incrementHeight(vss...) removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0) err = assertMempool(css[0].txNotifier).CheckTx(ctx, removeValidatorTx3, nil, mempool.TxInfo{}) - assert.Nil(t, err) + assert.NoError(t, err) propBlock, _, err = css[0].createProposalBlock() // changeProposer(t, cs1, vs2) require.NoError(t, err) propBlockParts, err = propBlock.MakePartSet(partSize) diff --git a/internal/libs/tempfile/tempfile_test.go b/internal/libs/tempfile/tempfile_test.go index 212525d44..5c38f9736 100644 --- a/internal/libs/tempfile/tempfile_test.go +++ b/internal/libs/tempfile/tempfile_test.go @@ -114,7 +114,7 @@ func TestWriteFileAtomicManyDuplicates(t *testing.T) { fileRand := randWriteFileSuffix() fname := "/tmp/" + atomicWriteFilePrefix + fileRand f, err := os.OpenFile(fname, atomicWriteFileFlag, 0777) - require.Nil(t, err) + require.NoError(t, err) _, err = f.WriteString(fmt.Sprintf(testString, i)) require.NoError(t, err) defer os.Remove(fname) @@ -132,13 +132,13 @@ func TestWriteFileAtomicManyDuplicates(t *testing.T) { fileRand := randWriteFileSuffix() fname := "/tmp/" + atomicWriteFilePrefix + fileRand firstAtomicFileBytes, err := os.ReadFile(fname) - require.Nil(t, err, "Error reading first atomic file") + require.NoError(t, err, "Error reading first atomic file") require.Equal(t, []byte(fmt.Sprintf(testString, i)), firstAtomicFileBytes, "atomic write file %d was overwritten", i) } // Check that the resultant file is correct resultantFileBytes, err := os.ReadFile(fileToWrite) - require.Nil(t, err, "Error reading resultant file") + require.NoError(t, err, "Error reading resultant file") require.Equal(t, []byte(expectedString), resultantFileBytes, "Written file had incorrect bytes") } diff --git a/internal/p2p/conn/connection_test.go b/internal/p2p/conn/connection_test.go index 0700db1b0..dbbfe23bd 100644 --- a/internal/p2p/conn/connection_test.go +++ b/internal/p2p/conn/connection_test.go @@ -55,7 +55,7 @@ func TestMConnectionSendFlushStop(t *testing.T) { clientConn := createTestMConnection(log.TestingLogger(), client) err := clientConn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(clientConn)) msg := []byte("abc") @@ -92,7 +92,7 @@ func TestMConnectionSend(t *testing.T) { mconn := createTestMConnection(log.TestingLogger(), client) err := mconn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn)) msg := []byte("Ant-Man") @@ -139,12 +139,12 @@ func TestMConnectionReceive(t *testing.T) { mconn1 := createMConnectionWithCallbacks(logger, client, onReceive, onError) err := mconn1.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn1)) mconn2 := createTestMConnection(logger, server) err = mconn2.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn2)) msg := []byte("Cyclops") @@ -184,7 +184,7 @@ func TestMConnectionPongTimeoutResultsInError(t *testing.T) { mconn := createMConnectionWithCallbacks(log.TestingLogger(), client, onReceive, onError) err := mconn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn)) serverGotPing := make(chan struct{}) @@ -232,7 +232,7 @@ func TestMConnectionMultiplePongsInTheBeginning(t *testing.T) { mconn := createMConnectionWithCallbacks(log.TestingLogger(), client, onReceive, onError) err := mconn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn)) // sending 3 pongs in a row (abuse) @@ -295,7 +295,7 @@ func TestMConnectionMultiplePings(t *testing.T) { mconn := createMConnectionWithCallbacks(log.TestingLogger(), client, onReceive, onError) err := mconn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn)) // sending 3 pings in a row (abuse) @@ -352,7 +352,7 @@ func TestMConnectionPingPongs(t *testing.T) { mconn := createMConnectionWithCallbacks(log.TestingLogger(), client, onReceive, onError) err := mconn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn)) serverGotPing := make(chan struct{}) @@ -418,7 +418,7 @@ func TestMConnectionStopsAndReturnsError(t *testing.T) { mconn := createMConnectionWithCallbacks(log.TestingLogger(), client, onReceive, onError) err := mconn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn)) if err := client.Close(); err != nil { @@ -455,7 +455,7 @@ func newClientAndServerConnsForReadErrors( mconnClient := NewMConnection(logger.With("module", "client"), client, chDescs, onReceive, onError) err := mconnClient.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) // create server conn with 1 channel // it fires on chOnErr when there's an error @@ -469,7 +469,7 @@ func newClientAndServerConnsForReadErrors( mconnServer := createMConnectionWithCallbacks(serverLogger, server, onReceive, onError) err = mconnServer.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) return mconnClient, mconnServer } @@ -583,7 +583,7 @@ func TestMConnectionTrySend(t *testing.T) { mconn := createTestMConnection(log.TestingLogger(), client) err := mconn.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(waitAll(mconn)) msg := []byte("Semicolon-Woman") diff --git a/internal/p2p/conn/secret_connection_test.go b/internal/p2p/conn/secret_connection_test.go index 8868972a0..7bc5e0b34 100644 --- a/internal/p2p/conn/secret_connection_test.go +++ b/internal/p2p/conn/secret_connection_test.go @@ -240,15 +240,15 @@ func TestDeriveSecretsAndChallengeGolden(t *testing.T) { line := scanner.Text() params := strings.Split(line, ",") randSecretVector, err := hex.DecodeString(params[0]) - require.Nil(t, err) + require.NoError(t, err) randSecret := new([32]byte) copy((*randSecret)[:], randSecretVector) locIsLeast, err := strconv.ParseBool(params[1]) - require.Nil(t, err) + require.NoError(t, err) expectedRecvSecret, err := hex.DecodeString(params[2]) - require.Nil(t, err) + require.NoError(t, err) expectedSendSecret, err := hex.DecodeString(params[3]) - require.Nil(t, err) + require.NoError(t, err) recvSecret, sendSecret := deriveSecrets(randSecret, locIsLeast) require.Equal(t, expectedRecvSecret, (*recvSecret)[:], "Recv Secrets aren't equal") diff --git a/internal/state/execution_test.go b/internal/state/execution_test.go index 66b72f21c..7689a9f04 100644 --- a/internal/state/execution_test.go +++ b/internal/state/execution_test.go @@ -45,7 +45,7 @@ func TestApplyBlock(t *testing.T) { defer cancel() err := proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) state, stateDB, _ := makeState(1, 1) stateStore := sm.NewStore(stateDB) @@ -60,7 +60,7 @@ func TestApplyBlock(t *testing.T) { blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} state, err = blockExec.ApplyBlock(ctx, state, blockID, block) - require.Nil(t, err) + require.NoError(t, err) // TODO check state and mempool assert.EqualValues(t, 1, state.Version.Consensus.App, "App version wasn't updated") @@ -76,7 +76,7 @@ func TestBeginBlockValidators(t *testing.T) { proxyApp := proxy.NewAppConns(cc, log.TestingLogger(), proxy.NopMetrics()) err := proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) state, stateDB, _ := makeState(2, 2) stateStore := sm.NewStore(stateDB) @@ -116,7 +116,7 @@ func TestBeginBlockValidators(t *testing.T) { require.NoError(t, err) _, err = sm.ExecCommitBlock(ctx, nil, proxyApp.Consensus(), block, log.TestingLogger(), stateStore, 1, state) - require.Nil(t, err, tc.desc) + require.NoError(t, err, tc.desc) // -> app receives a list of validators with a bool indicating if they signed ctr := 0 @@ -142,7 +142,7 @@ func TestBeginBlockByzantineValidators(t *testing.T) { cc := abciclient.NewLocalCreator(app) proxyApp := proxy.NewAppConns(cc, log.TestingLogger(), proxy.NopMetrics()) err := proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) state, stateDB, privVals := makeState(1, 1) stateStore := sm.NewStore(stateDB) @@ -228,7 +228,7 @@ func TestBeginBlockByzantineValidators(t *testing.T) { blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} _, err = blockExec.ApplyBlock(ctx, state, blockID, block) - require.Nil(t, err) + require.NoError(t, err) // TODO check state and mempool assert.Equal(t, abciEv, app.ByzantineValidators) @@ -374,7 +374,7 @@ func TestEndBlockValidatorUpdates(t *testing.T) { logger := log.TestingLogger() proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics()) err := proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) state, stateDB, _ := makeState(1, 1) stateStore := sm.NewStore(stateDB) @@ -416,7 +416,7 @@ func TestEndBlockValidatorUpdates(t *testing.T) { } state, err = blockExec.ApplyBlock(ctx, state, blockID, block) - require.Nil(t, err) + require.NoError(t, err) // test new validator was added to NextValidators if assert.Equal(t, state.Validators.Size()+1, state.NextValidators.Size()) { idx, _ := state.NextValidators.GetByAddress(pubkey.Address()) @@ -449,7 +449,7 @@ func TestEndBlockValidatorUpdatesResultingInEmptySet(t *testing.T) { logger := log.TestingLogger() proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics()) err := proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) state, stateDB, _ := makeState(1, 1) stateStore := sm.NewStore(stateDB) @@ -477,7 +477,7 @@ func TestEndBlockValidatorUpdatesResultingInEmptySet(t *testing.T) { } assert.NotPanics(t, func() { state, err = blockExec.ApplyBlock(ctx, state, blockID, block) }) - assert.NotNil(t, err) + assert.Error(t, err) assert.NotEmpty(t, state.NextValidators.Validators) } diff --git a/internal/state/indexer/indexer_service_test.go b/internal/state/indexer/indexer_service_test.go index 00a8b3fd4..47be1e28e 100644 --- a/internal/state/indexer/indexer_service_test.go +++ b/internal/state/indexer/indexer_service_test.go @@ -55,7 +55,7 @@ func TestIndexerServiceIndexesBlocks(t *testing.T) { // event sink setup pool, err := setupDB(t) - assert.Nil(t, err) + assert.NoError(t, err) store := dbm.NewMemDB() eventSinks := []indexer.EventSink{kv.NewEventSink(store), pSink} @@ -126,17 +126,17 @@ func readSchema() ([]*schema.Migration, error) { func resetDB(t *testing.T) { q := "DROP TABLE IF EXISTS block_events,tx_events,tx_results" _, err := psqldb.Exec(q) - assert.Nil(t, err) + assert.NoError(t, err) q = "DROP TYPE IF EXISTS block_event_type" _, err = psqldb.Exec(q) - assert.Nil(t, err) + assert.NoError(t, err) } func setupDB(t *testing.T) (*dockertest.Pool, error) { t.Helper() pool, err := dockertest.NewPool(os.Getenv("DOCKER_URL")) - assert.Nil(t, err) + assert.NoError(t, err) resource, err = pool.RunWithOptions(&dockertest.RunOptions{ Repository: "postgres", @@ -156,7 +156,7 @@ func setupDB(t *testing.T) (*dockertest.Pool, error) { } }) - assert.Nil(t, err) + assert.NoError(t, err) // Set the container to expire in a minute to avoid orphaned containers // hanging around @@ -178,11 +178,11 @@ func setupDB(t *testing.T) (*dockertest.Pool, error) { resetDB(t) sm, err := readSchema() - assert.Nil(t, err) + assert.NoError(t, err) migrator := schema.NewMigrator() err = migrator.Apply(psqldb, sm) - assert.Nil(t, err) + assert.NoError(t, err) return pool, nil } diff --git a/internal/state/indexer/sink/null/null_test.go b/internal/state/indexer/sink/null/null_test.go index 0cb5a552c..6de7669ce 100644 --- a/internal/state/indexer/sink/null/null_test.go +++ b/internal/state/indexer/sink/null/null_test.go @@ -19,16 +19,16 @@ func TestNullEventSink(t *testing.T) { assert.Nil(t, nullIndexer.IndexBlockEvents(types.EventDataNewBlockHeader{})) val1, err1 := nullIndexer.SearchBlockEvents(ctx, nil) assert.Nil(t, val1) - assert.Nil(t, err1) + assert.NoError(t, err1) val2, err2 := nullIndexer.SearchTxEvents(ctx, nil) assert.Nil(t, val2) - assert.Nil(t, err2) + assert.NoError(t, err2) val3, err3 := nullIndexer.GetTxByHash(nil) assert.Nil(t, val3) - assert.Nil(t, err3) + assert.NoError(t, err3) val4, err4 := nullIndexer.HasBlock(0) assert.False(t, val4) - assert.Nil(t, err4) + assert.NoError(t, err4) } func TestType(t *testing.T) { diff --git a/internal/state/indexer/sink/psql/psql_test.go b/internal/state/indexer/sink/psql/psql_test.go index 2526ef182..2168eb556 100644 --- a/internal/state/indexer/sink/psql/psql_test.go +++ b/internal/state/indexer/sink/psql/psql_test.go @@ -336,7 +336,7 @@ func verifyNotImplemented(t *testing.T, label string, f func() (bool, error)) { want := label + " is not supported via the postgres event sink" ok, err := f() assert.False(t, ok) - require.NotNil(t, err) + require.Error(t, err) assert.Equal(t, want, err.Error()) } diff --git a/internal/state/state_test.go b/internal/state/state_test.go index 10b0c356e..d5c6a649d 100644 --- a/internal/state/state_test.go +++ b/internal/state/state_test.go @@ -51,18 +51,16 @@ func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, sm.State) { func TestStateCopy(t *testing.T) { tearDown, _, state := setupTestCase(t) defer tearDown(t) - assert := assert.New(t) stateCopy := state.Copy() - assert.True(state.Equals(stateCopy), - fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", - stateCopy, state)) + assert.True(t, state.Equals(stateCopy), + "expected state and its copy to be identical.\ngot: %v\nexpected: %v", + stateCopy, state) stateCopy.LastBlockHeight++ stateCopy.LastValidators = state.Validators - assert.False(state.Equals(stateCopy), fmt.Sprintf(`expected states to be different. got same - %v`, state)) + assert.False(t, state.Equals(stateCopy), "expected states to be different. got same %v", state) } // TestMakeGenesisStateNilValidators tests state's consistency when genesis file's validators field is nil. @@ -73,7 +71,7 @@ func TestMakeGenesisStateNilValidators(t *testing.T) { } require.Nil(t, doc.ValidateAndComplete()) state, err := sm.MakeGenesisState(&doc) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, 0, len(state.Validators.Validators)) require.Equal(t, 0, len(state.NextValidators.Validators)) } @@ -83,7 +81,6 @@ func TestStateSaveLoad(t *testing.T) { tearDown, stateDB, state := setupTestCase(t) defer tearDown(t) stateStore := sm.NewStore(stateDB) - assert := assert.New(t) state.LastBlockHeight++ state.LastValidators = state.Validators @@ -92,9 +89,9 @@ func TestStateSaveLoad(t *testing.T) { loadedState, err := stateStore.Load() require.NoError(t, err) - assert.True(state.Equals(loadedState), - fmt.Sprintf("expected state and its copy to be identical.\ngot: %v\nexpected: %v\n", - loadedState, state)) + assert.True(t, state.Equals(loadedState), + "expected state and its copy to be identical.\ngot: %v\nexpected: %v", + loadedState, state) } // TestABCIResponsesSaveLoad tests saving and loading ABCIResponses. @@ -102,7 +99,6 @@ func TestABCIResponsesSaveLoad1(t *testing.T) { tearDown, stateDB, state := setupTestCase(t) defer tearDown(t) stateStore := sm.NewStore(stateDB) - assert := assert.New(t) state.LastBlockHeight++ @@ -123,17 +119,16 @@ func TestABCIResponsesSaveLoad1(t *testing.T) { err = stateStore.SaveABCIResponses(block.Height, abciResponses) require.NoError(t, err) loadedABCIResponses, err := stateStore.LoadABCIResponses(block.Height) - assert.Nil(err) - assert.Equal(abciResponses, loadedABCIResponses, - fmt.Sprintf("ABCIResponses don't match:\ngot: %v\nexpected: %v\n", - loadedABCIResponses, abciResponses)) + require.NoError(t, err) + assert.Equal(t, abciResponses, loadedABCIResponses, + "ABCIResponses don't match:\ngot: %v\nexpected: %v\n", + loadedABCIResponses, abciResponses) } // TestResultsSaveLoad tests saving and loading ABCI results. func TestABCIResponsesSaveLoad2(t *testing.T) { tearDown, stateDB, _ := setupTestCase(t) defer tearDown(t) - assert := assert.New(t) stateStore := sm.NewStore(stateDB) @@ -186,7 +181,7 @@ func TestABCIResponsesSaveLoad2(t *testing.T) { for i := range cases { h := int64(i + 1) res, err := stateStore.LoadABCIResponses(h) - assert.Error(err, "%d: %#v", i, res) + assert.Error(t, err, "%d: %#v", i, res) } // Add all cases. @@ -205,14 +200,14 @@ func TestABCIResponsesSaveLoad2(t *testing.T) { for i, tc := range cases { h := int64(i + 1) res, err := stateStore.LoadABCIResponses(h) - if assert.NoError(err, "%d", i) { + if assert.NoError(t, err, "%d", i) { t.Log(res) responses := &tmstate.ABCIResponses{ BeginBlock: &abci.ResponseBeginBlock{}, DeliverTxs: tc.expected, EndBlock: &abci.ResponseEndBlock{}, } - assert.Equal(sm.ABCIResponsesResultsHash(responses), sm.ABCIResponsesResultsHash(res), "%d", i) + assert.Equal(t, sm.ABCIResponsesResultsHash(responses), sm.ABCIResponsesResultsHash(res), "%d", i) } } } @@ -221,23 +216,22 @@ func TestABCIResponsesSaveLoad2(t *testing.T) { func TestValidatorSimpleSaveLoad(t *testing.T) { tearDown, stateDB, state := setupTestCase(t) defer tearDown(t) - assert := assert.New(t) statestore := sm.NewStore(stateDB) // Can't load anything for height 0. _, err := statestore.LoadValidators(0) - assert.IsType(sm.ErrNoValSetForHeight{}, err, "expected err at height 0") + assert.IsType(t, sm.ErrNoValSetForHeight{}, err, "expected err at height 0") // Should be able to load for height 1. v, err := statestore.LoadValidators(1) - assert.Nil(err, "expected no err at height 1") - assert.Equal(v.Hash(), state.Validators.Hash(), "expected validator hashes to match") + require.NoError(t, err, "expected no err at height 1") + assert.Equal(t, v.Hash(), state.Validators.Hash(), "expected validator hashes to match") // Should be able to load for height 2. v, err = statestore.LoadValidators(2) - assert.Nil(err, "expected no err at height 2") - assert.Equal(v.Hash(), state.NextValidators.Hash(), "expected validator hashes to match") + require.NoError(t, err, "expected no err at height 2") + assert.Equal(t, v.Hash(), state.NextValidators.Hash(), "expected validator hashes to match") // Increment height, save; should be able to load for next & next next height. state.LastBlockHeight++ @@ -245,11 +239,11 @@ func TestValidatorSimpleSaveLoad(t *testing.T) { err = statestore.Save(state) require.NoError(t, err) vp0, err := statestore.LoadValidators(nextHeight + 0) - assert.Nil(err, "expected no err") + assert.NoError(t, err) vp1, err := statestore.LoadValidators(nextHeight + 1) - assert.Nil(err, "expected no err") - assert.Equal(vp0.Hash(), state.Validators.Hash(), "expected validator hashes to match") - assert.Equal(vp1.Hash(), state.NextValidators.Hash(), "expected next validator hashes to match") + assert.NoError(t, err) + assert.Equal(t, vp0.Hash(), state.Validators.Hash(), "expected validator hashes to match") + assert.Equal(t, vp1.Hash(), state.NextValidators.Hash(), "expected next validator hashes to match") } // TestValidatorChangesSaveLoad tests saving and loading a validator set with changes. @@ -301,7 +295,7 @@ func TestOneValidatorChangesSaveLoad(t *testing.T) { for i, power := range testCases { v, err := stateStore.LoadValidators(int64(i + 1 + 1)) // +1 because vset changes delayed by 1 block. - assert.Nil(t, err, fmt.Sprintf("expected no err at height %d", i)) + assert.NoError(t, err, fmt.Sprintf("expected no err at height %d", i)) assert.Equal(t, v.Size(), 1, "validator set size is greater than 1: %d", v.Size()) _, val := v.GetByIndex(0) @@ -958,11 +952,11 @@ func TestStoreLoadValidatorsIncrementsProposerPriority(t *testing.T) { nextHeight := state.LastBlockHeight + 1 v0, err := stateStore.LoadValidators(nextHeight) - assert.Nil(t, err) + assert.NoError(t, err) acc0 := v0.Validators[0].ProposerPriority v1, err := stateStore.LoadValidators(nextHeight + 1) - assert.Nil(t, err) + assert.NoError(t, err) acc1 := v1.Validators[0].ProposerPriority assert.NotEqual(t, acc1, acc0, "expected ProposerPriority value to change between heights") @@ -993,14 +987,14 @@ func TestManyValidatorChangesSaveLoad(t *testing.T) { validatorUpdates, err = types.PB2TM.ValidatorUpdates(responses.EndBlock.ValidatorUpdates) require.NoError(t, err) state, err = sm.UpdateState(state, blockID, &header, responses, validatorUpdates) - require.Nil(t, err) + require.NoError(t, err) nextHeight := state.LastBlockHeight + 1 err = stateStore.Save(state) require.NoError(t, err) // Load nextheight, it should be the oldpubkey. v0, err := stateStore.LoadValidators(nextHeight) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, valSetSize, v0.Size()) index, val := v0.GetByAddress(pubkeyOld.Address()) assert.NotNil(t, val) @@ -1010,7 +1004,7 @@ func TestManyValidatorChangesSaveLoad(t *testing.T) { // Load nextheight+1, it should be the new pubkey. v1, err := stateStore.LoadValidators(nextHeight + 1) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, valSetSize, v1.Size()) index, val = v1.GetByAddress(pubkey.Address()) assert.NotNil(t, val) @@ -1072,7 +1066,7 @@ func TestConsensusParamsChangesSaveLoad(t *testing.T) { require.NoError(t, err) state, err = sm.UpdateState(state, blockID, &header, responses, validatorUpdates) - require.Nil(t, err) + require.NoError(t, err) err := stateStore.Save(state) require.NoError(t, err) } @@ -1094,7 +1088,7 @@ func TestConsensusParamsChangesSaveLoad(t *testing.T) { for _, testCase := range testCases { p, err := stateStore.LoadConsensusParams(testCase.height) - assert.Nil(t, err, fmt.Sprintf("expected no err at height %d", testCase.height)) + assert.NoError(t, err, fmt.Sprintf("expected no err at height %d", testCase.height)) assert.EqualValues(t, testCase.params, p, fmt.Sprintf(`unexpected consensus params at height %d`, testCase.height)) } diff --git a/internal/statesync/dispatcher_test.go b/internal/statesync/dispatcher_test.go index 7441327a8..3b0b6f5c9 100644 --- a/internal/statesync/dispatcher_test.go +++ b/internal/statesync/dispatcher_test.go @@ -88,7 +88,7 @@ func TestDispatcherReturnsNoBlock(t *testing.T) { <-ctx.Done() require.Nil(t, lb) - require.Nil(t, err) + require.NoError(t, err) } func TestDispatcherTimeOutWaitingOnLightBlock(t *testing.T) { diff --git a/internal/store/store_test.go b/internal/store/store_test.go index db71bb4b0..46d758130 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -289,7 +289,7 @@ func TestBlockStoreSaveLoadBlock(t *testing.T) { } assert.Nil(t, panicErr, "#%d: unexpected panic", i) - assert.Nil(t, err, "#%d: expecting a non-nil error", i) + assert.NoError(t, err, "#%d: expecting a non-nil error", i) qua, ok := res.(*quad) if !ok || qua == nil { t.Errorf("#%d: got nil quad back; gotType=%T", i, res) diff --git a/libs/bits/bit_array_test.go b/libs/bits/bit_array_test.go index 96f2e2257..4bc896e39 100644 --- a/libs/bits/bit_array_test.go +++ b/libs/bits/bit_array_test.go @@ -99,11 +99,11 @@ func TestSub(t *testing.T) { for _, tc := range testCases { var bA *BitArray err := json.Unmarshal([]byte(tc.initBA), &bA) - require.Nil(t, err) + require.NoError(t, err) var o *BitArray err = json.Unmarshal([]byte(tc.subtractingBA), &o) - require.Nil(t, err) + require.NoError(t, err) got, _ := json.Marshal(bA.Sub(o)) require.Equal( diff --git a/libs/bytes/bytes_test.go b/libs/bytes/bytes_test.go index 6a9ca7c3d..ce39935e8 100644 --- a/libs/bytes/bytes_test.go +++ b/libs/bytes/bytes_test.go @@ -14,12 +14,12 @@ func TestMarshal(t *testing.T) { bz := []byte("hello world") dataB := HexBytes(bz) bz2, err := dataB.Marshal() - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, bz, bz2) var dataB2 HexBytes err = (&dataB2).Unmarshal(bz) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, dataB, dataB2) } diff --git a/libs/cli/setup_test.go b/libs/cli/setup_test.go index fec49e5c1..573c52f97 100644 --- a/libs/cli/setup_test.go +++ b/libs/cli/setup_test.go @@ -49,7 +49,7 @@ func TestSetupEnv(t *testing.T) { viper.Reset() args := append([]string{cmd.Use}, tc.args...) err := RunWithArgs(cmd, args, tc.env) - require.Nil(t, err, i) + require.NoError(t, err, i) assert.Equal(t, tc.expected, foo, i) } } @@ -68,7 +68,7 @@ func TestSetupConfig(t *testing.T) { cval1 := "fubble" conf1 := tempDir() err := WriteConfigVals(conf1, map[string]string{"boo": cval1}) - require.Nil(t, err) + require.NoError(t, err) cases := []struct { args []string @@ -109,7 +109,7 @@ func TestSetupConfig(t *testing.T) { viper.Reset() args := append([]string{cmd.Use}, tc.args...) err := RunWithArgs(cmd, args, tc.env) - require.Nil(t, err, i) + require.NoError(t, err, i) assert.Equal(t, tc.expected, foo, i) assert.Equal(t, tc.expectedTwo, two, i) } @@ -127,11 +127,11 @@ func TestSetupUnmarshal(t *testing.T) { cval1, cval2 := "someone", "else" conf1 := tempDir() err := WriteConfigVals(conf1, map[string]string{"name": cval1}) - require.Nil(t, err) + require.NoError(t, err) // even with some ignored fields, should be no problem conf2 := tempDir() err = WriteConfigVals(conf2, map[string]string{"name": cval2, "foo": "bar"}) - require.Nil(t, err) + require.NoError(t, err) // unused is not declared on a flag and remains from base base := DemoConfig{ @@ -188,7 +188,7 @@ func TestSetupUnmarshal(t *testing.T) { viper.Reset() args := append([]string{cmd.Use}, tc.args...) err := RunWithArgs(cmd, args, tc.env) - require.Nil(t, err, i) + require.NoError(t, err, i) assert.Equal(t, tc.expected, cfg, i) } } @@ -221,7 +221,7 @@ func TestSetupTrace(t *testing.T) { viper.Reset() args := append([]string{cmd.Use}, tc.args...) stdout, stderr, err := RunCaptureWithArgs(cmd, args, tc.env) - require.NotNil(t, err, i) + require.Error(t, err, i) require.Equal(t, "", stdout, i) require.NotEqual(t, "", stderr, i) msg := strings.Split(stderr, "\n") diff --git a/light/provider/http/http_test.go b/light/provider/http/http_test.go index 1f695d442..c0f3833e6 100644 --- a/light/provider/http/http_test.go +++ b/light/provider/http/http_test.go @@ -52,7 +52,7 @@ func TestProvider(t *testing.T) { t.Log("chainID:", chainID) c, err := rpchttp.New(rpcAddr) - require.Nil(t, err) + require.NoError(t, err) p := lighthttp.NewWithClient(chainID, c) require.NoError(t, err) diff --git a/node/node_test.go b/node/node_test.go index 9a6750b61..ee134b4dd 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -265,7 +265,7 @@ func TestCreateProposalBlock(t *testing.T) { cc := abciclient.NewLocalCreator(kvstore.NewApplication()) proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics()) err = proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) const height int64 = 1 state, stateDB, privVals := state(t, 1, height) @@ -361,7 +361,7 @@ func TestMaxTxsProposalBlockSize(t *testing.T) { cc := abciclient.NewLocalCreator(kvstore.NewApplication()) proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics()) err = proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) const height int64 = 1 state, stateDB, _ := state(t, 1, height) @@ -427,7 +427,7 @@ func TestMaxProposalBlockSize(t *testing.T) { cc := abciclient.NewLocalCreator(kvstore.NewApplication()) proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics()) err = proxyApp.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) state, stateDB, _ := state(t, types.MaxVotesCount, int64(1)) stateStore := sm.NewStore(stateDB) diff --git a/privval/file_test.go b/privval/file_test.go index 571836e69..931099fb2 100644 --- a/privval/file_test.go +++ b/privval/file_test.go @@ -21,12 +21,10 @@ import ( ) func TestGenLoadValidator(t *testing.T) { - assert := assert.New(t) - tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") - require.Nil(t, err) + require.NoError(t, err) tempStateFile, err := os.CreateTemp("", "priv_validator_state_") - require.Nil(t, err) + require.NoError(t, err) privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") require.NoError(t, err) @@ -37,16 +35,16 @@ func TestGenLoadValidator(t *testing.T) { addr := privVal.GetAddress() privVal, err = LoadFilePV(tempKeyFile.Name(), tempStateFile.Name()) - assert.NoError(err) - assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same") - assert.Equal(height, privVal.LastSignState.Height, "expected privval.LastHeight to have been saved") + assert.NoError(t, err) + assert.Equal(t, addr, privVal.GetAddress(), "expected privval addr to be the same") + assert.Equal(t, height, privVal.LastSignState.Height, "expected privval.LastHeight to have been saved") } func TestResetValidator(t *testing.T) { tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") - require.Nil(t, err) + require.NoError(t, err) tempStateFile, err := os.CreateTemp("", "priv_validator_state_") - require.Nil(t, err) + require.NoError(t, err) privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") require.NoError(t, err) @@ -73,12 +71,10 @@ func TestResetValidator(t *testing.T) { } func TestLoadOrGenValidator(t *testing.T) { - assert := assert.New(t) - tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") - require.Nil(t, err) + require.NoError(t, err) tempStateFile, err := os.CreateTemp("", "priv_validator_state_") - require.Nil(t, err) + require.NoError(t, err) tempKeyFilePath := tempKeyFile.Name() if err := os.Remove(tempKeyFilePath); err != nil { @@ -94,12 +90,10 @@ func TestLoadOrGenValidator(t *testing.T) { addr := privVal.GetAddress() privVal, err = LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath) require.NoError(t, err) - assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same") + assert.Equal(t, addr, privVal.GetAddress(), "expected privval addr to be the same") } func TestUnmarshalValidatorState(t *testing.T) { - assert, require := assert.New(t), require.New(t) - // create some fixed values serialized := `{ "height": "1", @@ -109,22 +103,20 @@ func TestUnmarshalValidatorState(t *testing.T) { val := FilePVLastSignState{} err := tmjson.Unmarshal([]byte(serialized), &val) - require.Nil(err, "%+v", err) + require.NoError(t, err) // make sure the values match - assert.EqualValues(val.Height, 1) - assert.EqualValues(val.Round, 1) - assert.EqualValues(val.Step, 1) + assert.EqualValues(t, val.Height, 1) + assert.EqualValues(t, val.Round, 1) + assert.EqualValues(t, val.Step, 1) // export it and make sure it is the same out, err := tmjson.Marshal(val) - require.Nil(err, "%+v", err) - assert.JSONEq(serialized, string(out)) + require.NoError(t, err) + assert.JSONEq(t, serialized, string(out)) } func TestUnmarshalValidatorKey(t *testing.T) { - assert, require := assert.New(t), require.New(t) - // create some fixed values privKey := ed25519.GenPrivKey() pubKey := privKey.PubKey() @@ -148,26 +140,24 @@ func TestUnmarshalValidatorKey(t *testing.T) { val := FilePVKey{} err := tmjson.Unmarshal([]byte(serialized), &val) - require.Nil(err, "%+v", err) + require.NoError(t, err) // make sure the values match - assert.EqualValues(addr, val.Address) - assert.EqualValues(pubKey, val.PubKey) - assert.EqualValues(privKey, val.PrivKey) + assert.EqualValues(t, addr, val.Address) + assert.EqualValues(t, pubKey, val.PubKey) + assert.EqualValues(t, privKey, val.PrivKey) // export it and make sure it is the same out, err := tmjson.Marshal(val) - require.Nil(err, "%+v", err) - assert.JSONEq(serialized, string(out)) + require.NoError(t, err) + assert.JSONEq(t, serialized, string(out)) } func TestSignVote(t *testing.T) { - assert := assert.New(t) - tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") - require.Nil(t, err) + require.NoError(t, err) tempStateFile, err := os.CreateTemp("", "priv_validator_state_") - require.Nil(t, err) + require.NoError(t, err) privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") require.NoError(t, err) @@ -187,11 +177,11 @@ func TestSignVote(t *testing.T) { vote := newVote(privVal.Key.Address, 0, height, round, voteType, block1) v := vote.ToProto() err = privVal.SignVote(context.Background(), "mychainid", v) - assert.NoError(err, "expected no error signing vote") + assert.NoError(t, err, "expected no error signing vote") // try to sign the same vote again; should be fine err = privVal.SignVote(context.Background(), "mychainid", v) - assert.NoError(err, "expected no error on signing same vote") + assert.NoError(t, err, "expected no error on signing same vote") // now try some bad votes cases := []*types.Vote{ @@ -202,26 +192,22 @@ func TestSignVote(t *testing.T) { } for _, c := range cases { - cpb := c.ToProto() - err = privVal.SignVote(context.Background(), "mychainid", cpb) - assert.Error(err, "expected error on signing conflicting vote") + assert.Error(t, privVal.SignVote(context.Background(), "mychainid", c.ToProto()), + "expected error on signing conflicting vote") } // try signing a vote with a different time stamp sig := vote.Signature vote.Timestamp = vote.Timestamp.Add(time.Duration(1000)) - err = privVal.SignVote(context.Background(), "mychainid", v) - assert.NoError(err) - assert.Equal(sig, vote.Signature) + assert.NoError(t, privVal.SignVote(context.Background(), "mychainid", v)) + assert.Equal(t, sig, vote.Signature) } func TestSignProposal(t *testing.T) { - assert := assert.New(t) - tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") - require.Nil(t, err) + require.NoError(t, err) tempStateFile, err := os.CreateTemp("", "priv_validator_state_") - require.Nil(t, err) + require.NoError(t, err) privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") require.NoError(t, err) @@ -239,11 +225,11 @@ func TestSignProposal(t *testing.T) { proposal := newProposal(height, round, block1) pbp := proposal.ToProto() err = privVal.SignProposal(context.Background(), "mychainid", pbp) - assert.NoError(err, "expected no error signing proposal") + assert.NoError(t, err, "expected no error signing proposal") // try to sign the same proposal again; should be fine err = privVal.SignProposal(context.Background(), "mychainid", pbp) - assert.NoError(err, "expected no error on signing same proposal") + assert.NoError(t, err, "expected no error on signing same proposal") // now try some bad Proposals cases := []*types.Proposal{ @@ -254,16 +240,16 @@ func TestSignProposal(t *testing.T) { } for _, c := range cases { - err = privVal.SignProposal(context.Background(), "mychainid", c.ToProto()) - assert.Error(err, "expected error on signing conflicting proposal") + assert.Error(t, privVal.SignProposal(context.Background(), "mychainid", c.ToProto()), + "expected error on signing conflicting proposal") } // try signing a proposal with a different time stamp sig := proposal.Signature proposal.Timestamp = proposal.Timestamp.Add(time.Duration(1000)) err = privVal.SignProposal(context.Background(), "mychainid", pbp) - assert.NoError(err) - assert.Equal(sig, proposal.Signature) + assert.NoError(t, err) + assert.Equal(t, sig, proposal.Signature) } func TestDifferByTimestamp(t *testing.T) { @@ -271,9 +257,9 @@ func TestDifferByTimestamp(t *testing.T) { defer cancel() tempKeyFile, err := os.CreateTemp("", "priv_validator_key_") - require.Nil(t, err) + require.NoError(t, err) tempStateFile, err := os.CreateTemp("", "priv_validator_state_") - require.Nil(t, err) + require.NoError(t, err) privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") require.NoError(t, err) diff --git a/rpc/client/event_test.go b/rpc/client/event_test.go index 3b91de107..0bed656d4 100644 --- a/rpc/client/event_test.go +++ b/rpc/client/event_test.go @@ -52,7 +52,7 @@ func testTxEventsSent(ctx context.Context, t *testing.T, broadcastMethod string, // and wait for confirmation evt, err := client.WaitForOneEvent(c, types.EventTxValue, waitForEventTimeout) - require.Nil(t, err) + require.NoError(t, err) // and make sure it has the proper info txe, ok := evt.(types.EventDataTx) diff --git a/rpc/client/helpers_test.go b/rpc/client/helpers_test.go index 60732b991..72d9fce45 100644 --- a/rpc/client/helpers_test.go +++ b/rpc/client/helpers_test.go @@ -14,8 +14,6 @@ import ( ) func TestWaitForHeight(t *testing.T) { - assert, require := assert.New(t), require.New(t) - // test with error result - immediate failure m := &mock.StatusMock{ Call: mock.Call{ @@ -26,10 +24,10 @@ func TestWaitForHeight(t *testing.T) { // connection failure always leads to error err := client.WaitForHeight(r, 8, nil) - require.NotNil(err) - require.Equal("bye", err.Error()) + require.Error(t, err) + require.Equal(t, "bye", err.Error()) // we called status once to check - require.Equal(1, len(r.Calls)) + require.Equal(t, 1, len(r.Calls)) // now set current block height to 10 m.Call = mock.Call{ @@ -38,16 +36,16 @@ func TestWaitForHeight(t *testing.T) { // we will not wait for more than 10 blocks err = client.WaitForHeight(r, 40, nil) - require.NotNil(err) - require.True(strings.Contains(err.Error(), "aborting")) + require.Error(t, err) + require.True(t, strings.Contains(err.Error(), "aborting")) // we called status once more to check - require.Equal(2, len(r.Calls)) + require.Equal(t, 2, len(r.Calls)) // waiting for the past returns immediately err = client.WaitForHeight(r, 5, nil) - require.Nil(err) + require.NoError(t, err) // we called status once more to check - require.Equal(3, len(r.Calls)) + require.Equal(t, 3, len(r.Calls)) // since we can't update in a background goroutine (test --race) // we use the callback to update the status height @@ -59,19 +57,19 @@ func TestWaitForHeight(t *testing.T) { // we wait for a few blocks err = client.WaitForHeight(r, 12, myWaiter) - require.Nil(err) + require.NoError(t, err) // we called status once to check - require.Equal(5, len(r.Calls)) + require.Equal(t, 5, len(r.Calls)) pre := r.Calls[3] - require.Nil(pre.Error) + require.Nil(t, pre.Error) prer, ok := pre.Response.(*coretypes.ResultStatus) - require.True(ok) - assert.Equal(int64(10), prer.SyncInfo.LatestBlockHeight) + require.True(t, ok) + assert.Equal(t, int64(10), prer.SyncInfo.LatestBlockHeight) post := r.Calls[4] - require.Nil(post.Error) + require.Nil(t, post.Error) postr, ok := post.Response.(*coretypes.ResultStatus) - require.True(ok) - assert.Equal(int64(15), postr.SyncInfo.LatestBlockHeight) + require.True(t, ok) + assert.Equal(t, int64(15), postr.SyncInfo.LatestBlockHeight) } diff --git a/rpc/client/mock/abci_test.go b/rpc/client/mock/abci_test.go index 25fbbc05d..abf2f74f0 100644 --- a/rpc/client/mock/abci_test.go +++ b/rpc/client/mock/abci_test.go @@ -19,8 +19,6 @@ import ( ) func TestABCIMock(t *testing.T) { - assert, require := assert.New(t), require.New(t) - key, value := []byte("foo"), []byte("bar") height := int64(10) goodTx := types.Tx{0x01, 0xff} @@ -47,40 +45,38 @@ func TestABCIMock(t *testing.T) { // now, let's try to make some calls _, err := m.ABCIInfo(context.Background()) - require.NotNil(err) - assert.Equal("foobar", err.Error()) + require.NoError(t, err) + assert.Equal(t, "foobar", err.Error()) // query always returns the response _query, err := m.ABCIQueryWithOptions(context.Background(), "/", nil, client.ABCIQueryOptions{Prove: false}) query := _query.Response - require.Nil(err) - require.NotNil(query) - assert.EqualValues(key, query.Key) - assert.EqualValues(value, query.Value) - assert.Equal(height, query.Height) + require.NoError(t, err) + require.NotNil(t, query) + assert.EqualValues(t, key, query.Key) + assert.EqualValues(t, value, query.Value) + assert.Equal(t, height, query.Height) // non-commit calls always return errors _, err = m.BroadcastTxSync(context.Background(), goodTx) - require.NotNil(err) - assert.Equal("must commit", err.Error()) + require.NoError(t, err) + assert.Equal(t, "must commit", err.Error()) _, err = m.BroadcastTxAsync(context.Background(), goodTx) - require.NotNil(err) - assert.Equal("must commit", err.Error()) + require.Error(t, err) + assert.Equal(t, "must commit", err.Error()) // commit depends on the input _, err = m.BroadcastTxCommit(context.Background(), badTx) - require.NotNil(err) - assert.Equal("bad tx", err.Error()) + require.NoError(t, err) + assert.Equal(t, "bad tx", err.Error()) bres, err := m.BroadcastTxCommit(context.Background(), goodTx) - require.Nil(err, "%+v", err) - assert.EqualValues(0, bres.CheckTx.Code) - assert.EqualValues("stand", bres.CheckTx.Data) - assert.EqualValues("deliver", bres.DeliverTx.Data) + require.NoError(t, err, "%+v", err) + assert.EqualValues(t, 0, bres.CheckTx.Code) + assert.EqualValues(t, "stand", bres.CheckTx.Data) + assert.EqualValues(t, "deliver", bres.DeliverTx.Data) } func TestABCIRecorder(t *testing.T) { - assert, require := assert.New(t), require.New(t) - // This mock returns errors on everything but Query m := mock.ABCIMock{ Info: mock.Call{Response: abci.ResponseInfo{ @@ -93,10 +89,10 @@ func TestABCIRecorder(t *testing.T) { } r := mock.NewABCIRecorder(m) - require.Equal(0, len(r.Calls)) + require.Equal(t, 0, len(r.Calls)) _, err := r.ABCIInfo(context.Background()) - assert.Nil(err, "expected no err on info") + assert.NoError(t, err, "expected no err on info") _, err = r.ABCIQueryWithOptions( context.Background(), @@ -104,79 +100,78 @@ func TestABCIRecorder(t *testing.T) { bytes.HexBytes("data"), client.ABCIQueryOptions{Prove: false}, ) - assert.NotNil(err, "expected error on query") - require.Equal(2, len(r.Calls)) + assert.NoError(t, err, "expected error on query") + require.Equal(t, 2, len(r.Calls)) info := r.Calls[0] - assert.Equal("abci_info", info.Name) - assert.Nil(info.Error) - assert.Nil(info.Args) - require.NotNil(info.Response) + assert.Equal(t, "abci_info", info.Name) + assert.Nil(t, info.Error) + assert.Nil(t, info.Args) + require.NotNil(t, info.Response) ir, ok := info.Response.(*coretypes.ResultABCIInfo) - require.True(ok) - assert.Equal("data", ir.Response.Data) - assert.Equal("v0.9.9", ir.Response.Version) + require.True(t, ok) + assert.Equal(t, "data", ir.Response.Data) + assert.Equal(t, "v0.9.9", ir.Response.Version) query := r.Calls[1] - assert.Equal("abci_query", query.Name) - assert.Nil(query.Response) - require.NotNil(query.Error) - assert.Equal("query", query.Error.Error()) - require.NotNil(query.Args) + assert.Equal(t, "abci_query", query.Name) + assert.Nil(t, query.Response) + require.NotNil(t, query.Error) + assert.Equal(t, "query", query.Error.Error()) + require.NotNil(t, query.Args) qa, ok := query.Args.(mock.QueryArgs) - require.True(ok) - assert.Equal("path", qa.Path) - assert.EqualValues("data", qa.Data) - assert.False(qa.Prove) + require.True(t, ok) + assert.Equal(t, "path", qa.Path) + assert.EqualValues(t, "data", qa.Data) + assert.False(t, qa.Prove) // now add some broadcasts (should all err) txs := []types.Tx{{1}, {2}, {3}} _, err = r.BroadcastTxCommit(context.Background(), txs[0]) - assert.NotNil(err, "expected err on broadcast") + assert.Error(t, err, "expected err on broadcast") _, err = r.BroadcastTxSync(context.Background(), txs[1]) - assert.NotNil(err, "expected err on broadcast") + assert.Error(t, err, "expected err on broadcast") _, err = r.BroadcastTxAsync(context.Background(), txs[2]) - assert.NotNil(err, "expected err on broadcast") + assert.Error(t, err, "expected err on broadcast") - require.Equal(5, len(r.Calls)) + require.Equal(t, 5, len(r.Calls)) bc := r.Calls[2] - assert.Equal("broadcast_tx_commit", bc.Name) - assert.Nil(bc.Response) - require.NotNil(bc.Error) - assert.EqualValues(bc.Args, txs[0]) + assert.Equal(t, "broadcast_tx_commit", bc.Name) + assert.Nil(t, bc.Response) + require.NotNil(t, bc.Error) + assert.EqualValues(t, bc.Args, txs[0]) bs := r.Calls[3] - assert.Equal("broadcast_tx_sync", bs.Name) - assert.Nil(bs.Response) - require.NotNil(bs.Error) - assert.EqualValues(bs.Args, txs[1]) + assert.Equal(t, "broadcast_tx_sync", bs.Name) + assert.Nil(t, bs.Response) + require.NotNil(t, bs.Error) + assert.EqualValues(t, bs.Args, txs[1]) ba := r.Calls[4] - assert.Equal("broadcast_tx_async", ba.Name) - assert.Nil(ba.Response) - require.NotNil(ba.Error) - assert.EqualValues(ba.Args, txs[2]) + assert.Equal(t, "broadcast_tx_async", ba.Name) + assert.Nil(t, ba.Response) + require.NotNil(t, ba.Error) + assert.EqualValues(t, ba.Args, txs[2]) } func TestABCIApp(t *testing.T) { - assert, require := assert.New(t), require.New(t) app := kvstore.NewApplication() m := mock.ABCIApp{app} // get some info info, err := m.ABCIInfo(context.Background()) - require.Nil(err) - assert.Equal(`{"size":0}`, info.Response.GetData()) + require.NoError(t, err) + assert.Equal(t, `{"size":0}`, info.Response.GetData()) // add a key key, value := "foo", "bar" tx := fmt.Sprintf("%s=%s", key, value) res, err := m.BroadcastTxCommit(context.Background(), types.Tx(tx)) - require.Nil(err) - assert.True(res.CheckTx.IsOK()) - require.NotNil(res.DeliverTx) - assert.True(res.DeliverTx.IsOK()) + require.NoError(t, err) + assert.True(t, res.CheckTx.IsOK()) + require.NotNil(t, res.DeliverTx) + assert.True(t, res.DeliverTx.IsOK()) // commit // TODO: This may not be necessary in the future @@ -192,8 +187,8 @@ func TestABCIApp(t *testing.T) { client.ABCIQueryOptions{Prove: true}, ) qres := _qres.Response - require.Nil(err) - assert.EqualValues(value, qres.Value) + require.NoError(t, err) + assert.EqualValues(t, value, qres.Value) // XXX Check proof } diff --git a/rpc/client/mock/status_test.go b/rpc/client/mock/status_test.go index 98655280e..9411b4f75 100644 --- a/rpc/client/mock/status_test.go +++ b/rpc/client/mock/status_test.go @@ -14,8 +14,6 @@ import ( ) func TestStatus(t *testing.T) { - assert, require := assert.New(t), require.New(t) - m := &mock.StatusMock{ Call: mock.Call{ Response: &coretypes.ResultStatus{ @@ -38,37 +36,37 @@ func TestStatus(t *testing.T) { } r := mock.NewStatusRecorder(m) - require.Equal(0, len(r.Calls)) + require.Equal(t, 0, len(r.Calls)) // make sure response works proper status, err := r.Status(context.Background()) - require.Nil(err, "%+v", err) - assert.EqualValues("block", status.SyncInfo.LatestBlockHash) - assert.EqualValues(10, status.SyncInfo.LatestBlockHeight) - assert.EqualValues(20, status.SyncInfo.MaxPeerBlockHeight) - assert.EqualValues(time.Second, status.SyncInfo.TotalSyncedTime) - assert.EqualValues(time.Minute, status.SyncInfo.RemainingTime) + require.NoError(t, err) + assert.EqualValues(t, "block", status.SyncInfo.LatestBlockHash) + assert.EqualValues(t, 10, status.SyncInfo.LatestBlockHeight) + assert.EqualValues(t, 20, status.SyncInfo.MaxPeerBlockHeight) + assert.EqualValues(t, time.Second, status.SyncInfo.TotalSyncedTime) + assert.EqualValues(t, time.Minute, status.SyncInfo.RemainingTime) // make sure recorder works properly - require.Equal(1, len(r.Calls)) + require.Equal(t, 1, len(r.Calls)) rs := r.Calls[0] - assert.Equal("status", rs.Name) - assert.Nil(rs.Args) - assert.Nil(rs.Error) - require.NotNil(rs.Response) + assert.Equal(t, "status", rs.Name) + assert.Nil(t, rs.Args) + assert.Nil(t, rs.Error) + require.NotNil(t, rs.Response) st, ok := rs.Response.(*coretypes.ResultStatus) - require.True(ok) - assert.EqualValues("block", st.SyncInfo.LatestBlockHash) - assert.EqualValues(10, st.SyncInfo.LatestBlockHeight) - assert.EqualValues(20, st.SyncInfo.MaxPeerBlockHeight) - assert.EqualValues(time.Second, status.SyncInfo.TotalSyncedTime) - assert.EqualValues(time.Minute, status.SyncInfo.RemainingTime) + require.True(t, ok) + assert.EqualValues(t, "block", st.SyncInfo.LatestBlockHash) + assert.EqualValues(t, 10, st.SyncInfo.LatestBlockHeight) + assert.EqualValues(t, 20, st.SyncInfo.MaxPeerBlockHeight) + assert.EqualValues(t, time.Second, status.SyncInfo.TotalSyncedTime) + assert.EqualValues(t, time.Minute, status.SyncInfo.RemainingTime) - assert.EqualValues(10, st.SyncInfo.TotalSnapshots) - assert.EqualValues(time.Duration(10), st.SyncInfo.ChunkProcessAvgTime) - assert.EqualValues(10, st.SyncInfo.SnapshotHeight) - assert.EqualValues(9, status.SyncInfo.SnapshotChunksCount) - assert.EqualValues(10, status.SyncInfo.SnapshotChunksTotal) - assert.EqualValues(9, status.SyncInfo.BackFilledBlocks) - assert.EqualValues(10, status.SyncInfo.BackFillBlocksTotal) + assert.EqualValues(t, 10, st.SyncInfo.TotalSnapshots) + assert.EqualValues(t, time.Duration(10), st.SyncInfo.ChunkProcessAvgTime) + assert.EqualValues(t, 10, st.SyncInfo.SnapshotHeight) + assert.EqualValues(t, 9, status.SyncInfo.SnapshotChunksCount) + assert.EqualValues(t, 10, status.SyncInfo.SnapshotChunksTotal) + assert.EqualValues(t, 9, status.SyncInfo.BackFilledBlocks) + assert.EqualValues(t, 10, status.SyncInfo.BackFillBlocksTotal) } diff --git a/rpc/client/rpc_test.go b/rpc/client/rpc_test.go index 591fe9bb0..42975e10e 100644 --- a/rpc/client/rpc_test.go +++ b/rpc/client/rpc_test.go @@ -108,7 +108,7 @@ func TestClientOperations(t *testing.T) { t.Run("CustomHTTPClient", func(t *testing.T) { remote := conf.RPC.ListenAddress c, err := rpchttp.NewWithClient(remote, http.DefaultClient) - require.Nil(t, err) + require.NoError(t, err) status, err := c.Status(ctx) require.NoError(t, err) require.NotNil(t, status) @@ -118,10 +118,10 @@ func TestClientOperations(t *testing.T) { remote := strings.ReplaceAll(conf.RPC.ListenAddress, "tcp", "http") req, err := http.NewRequestWithContext(ctx, "GET", remote, nil) - require.Nil(t, err, "%+v", err) + require.NoError(t, err, "%+v", err) req.Header.Set("Origin", origin) resp, err := http.DefaultClient.Do(req) - require.Nil(t, err, "%+v", err) + require.NoError(t, err, "%+v", err) defer resp.Body.Close() assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin) @@ -208,7 +208,7 @@ func TestClientMethodCalls(t *testing.T) { t.Run(fmt.Sprintf("%T", c), func(t *testing.T) { t.Run("Status", func(t *testing.T) { status, err := c.Status(ctx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.Equal(t, conf.Moniker, status.NodeInfo.Moniker) }) t.Run("Info", func(t *testing.T) { @@ -225,7 +225,7 @@ func TestClientMethodCalls(t *testing.T) { nc, ok := c.(client.NetworkClient) require.True(t, ok, "%d", i) netinfo, err := nc.NetInfo(ctx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.True(t, netinfo.Listening) assert.Equal(t, 0, len(netinfo.Peers)) }) @@ -234,7 +234,7 @@ func TestClientMethodCalls(t *testing.T) { nc, ok := c.(client.NetworkClient) require.True(t, ok, "%d", i) cons, err := nc.DumpConsensusState(ctx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.NotEmpty(t, cons.RoundState) assert.Empty(t, cons.Peers) }) @@ -243,19 +243,19 @@ func TestClientMethodCalls(t *testing.T) { nc, ok := c.(client.NetworkClient) require.True(t, ok, "%d", i) cons, err := nc.ConsensusState(ctx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.NotEmpty(t, cons.RoundState) }) t.Run("Health", func(t *testing.T) { nc, ok := c.(client.NetworkClient) require.True(t, ok, "%d", i) _, err := nc.Health(ctx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) }) t.Run("GenesisAndValidators", func(t *testing.T) { // make sure this is the right genesis file gen, err := c.Genesis(ctx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) // get the genesis validator require.Equal(t, 1, len(gen.Genesis.Validators)) gval := gen.Genesis.Validators[0] @@ -263,7 +263,7 @@ func TestClientMethodCalls(t *testing.T) { // get the current validators h := int64(1) vals, err := c.Validators(ctx, &h, nil, nil) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) require.Equal(t, 1, len(vals.Validators)) require.Equal(t, 1, vals.Count) require.Equal(t, 1, vals.Total) @@ -415,17 +415,17 @@ func TestClientMethodCalls(t *testing.T) { require.NoError(t, err) res, err := c.BlockchainInfo(ctx, 0, 0) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.True(t, res.LastHeight > 0) assert.True(t, len(res.BlockMetas) > 0) res, err = c.BlockchainInfo(ctx, 1, 1) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.True(t, res.LastHeight > 0) assert.True(t, len(res.BlockMetas) == 1) res, err = c.BlockchainInfo(ctx, 1, 10000) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.True(t, res.LastHeight > 0) assert.True(t, len(res.BlockMetas) < 100) for _, m := range res.BlockMetas { @@ -433,14 +433,14 @@ func TestClientMethodCalls(t *testing.T) { } res, err = c.BlockchainInfo(ctx, 10000, 1) - require.NotNil(t, err) + require.Error(t, err) assert.Nil(t, res) assert.Contains(t, err.Error(), "can't be greater than max") }) t.Run("BroadcastTxCommit", func(t *testing.T) { _, _, tx := MakeTxKV() bres, err := c.BroadcastTxCommit(ctx, tx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) require.True(t, bres.CheckTx.IsOK()) require.True(t, bres.DeliverTx.IsOK()) @@ -450,7 +450,7 @@ func TestClientMethodCalls(t *testing.T) { _, _, tx := MakeTxKV() initMempoolSize := pool.Size() bres, err := c.BroadcastTxSync(ctx, tx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) require.Equal(t, bres.Code, abci.CodeTypeOK) // FIXME require.Equal(t, initMempoolSize+1, pool.Size()) @@ -476,11 +476,11 @@ func TestClientMethodCalls(t *testing.T) { // if so, then we start it, listen, and stop it. err := c.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) } t.Run("Header", func(t *testing.T) { evt, err := client.WaitForOneEvent(c, types.EventNewBlockHeaderValue, waitForEventTimeout) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) _, ok := evt.(types.EventDataNewBlockHeader) require.True(t, ok, "%d: %#v", i, evt) // TODO: more checks... @@ -637,7 +637,7 @@ func TestClientMethodCallsAdvanced(t *testing.T) { mc, ok := c.(client.MempoolClient) require.True(t, ok, "%d", i) res, err := mc.NumUnconfirmedTxs(ctx) - require.Nil(t, err, "%d: %+v", i, err) + require.NoError(t, err, "%d: %+v", i, err) assert.Equal(t, mempoolSize, res.Count) assert.Equal(t, mempoolSize, res.Total) @@ -652,7 +652,7 @@ func TestClientMethodCallsAdvanced(t *testing.T) { // first we broadcast a tx _, _, tx := MakeTxKV() bres, err := c.BroadcastTxCommit(ctx, tx) - require.Nil(t, err, "%+v", err) + require.NoError(t, err, "%+v", err) txHeight := bres.Height txHash := bres.Hash @@ -682,9 +682,9 @@ func TestClientMethodCallsAdvanced(t *testing.T) { ptx, err := c.Tx(ctx, tc.hash, tc.prove) if !tc.valid { - require.NotNil(t, err) + require.Error(t, err) } else { - require.Nil(t, err, "%+v", err) + require.NoError(t, err, "%+v", err) assert.EqualValues(t, txHeight, ptx.Height) assert.EqualValues(t, tx, ptx.Tx) assert.Zero(t, ptx.Index) @@ -711,7 +711,7 @@ func TestClientMethodCallsAdvanced(t *testing.T) { // query using a compositeKey (see kvstore application) result, err := timeoutClient.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") }) t.Run("TxSearch", func(t *testing.T) { @@ -739,7 +739,7 @@ func TestClientMethodCallsAdvanced(t *testing.T) { t.Run(fmt.Sprintf("%T", c), func(t *testing.T) { // now we query for the tx. result, err := c.TxSearch(ctx, fmt.Sprintf("tx.hash='%v'", find.Hash), true, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Len(t, result.Txs, 1) require.Equal(t, find.Hash, result.Txs[0].Hash) @@ -757,51 +757,51 @@ func TestClientMethodCallsAdvanced(t *testing.T) { // query by height result, err = c.TxSearch(ctx, fmt.Sprintf("tx.height=%d", find.Height), true, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Len(t, result.Txs, 1) // query for non existing tx result, err = c.TxSearch(ctx, fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Len(t, result.Txs, 0) // query using a compositeKey (see kvstore application) result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") // query using an index key result, err = c.TxSearch(ctx, "app.index_key='index is working'", false, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") // query using an noindex key result, err = c.TxSearch(ctx, "app.noindex_key='index is working'", false, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, len(result.Txs), 0, "expected a lot of transactions") // query using a compositeKey (see kvstore application) and height result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Greater(t, len(result.Txs), 0, "expected a lot of transactions") // query a non existing tx with page 1 and txsPerPage 1 perPage := 1 result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Neetowoko'", true, nil, &perPage, "asc") - require.Nil(t, err) + require.NoError(t, err) require.Len(t, result.Txs, 0) // check sorting result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "asc") - require.Nil(t, err) + require.NoError(t, err) for k := 0; k < len(result.Txs)-1; k++ { require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height) require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index) } result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "desc") - require.Nil(t, err) + require.NoError(t, err) for k := 0; k < len(result.Txs)-1; k++ { require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height) require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index) diff --git a/rpc/jsonrpc/client/http_json_client_test.go b/rpc/jsonrpc/client/http_json_client_test.go index fd433d458..d6b455d63 100644 --- a/rpc/jsonrpc/client/http_json_client_test.go +++ b/rpc/jsonrpc/client/http_json_client_test.go @@ -27,7 +27,7 @@ func TestHTTPClientMakeHTTPDialer(t *testing.T) { u, err := newParsedURL(testURL) require.NoError(t, err) dialFn, err := makeHTTPDialer(testURL) - require.Nil(t, err) + require.NoError(t, err) addr, err := dialFn(u.Scheme, u.GetHostWithPath()) require.NoError(t, err) @@ -92,7 +92,7 @@ func TestMakeHTTPDialerURL(t *testing.T) { u, err := newParsedURL(remote) require.NoError(t, err) dialFn, err := makeHTTPDialer(remote) - require.Nil(t, err) + require.NoError(t, err) addr, err := dialFn(u.Scheme, u.GetHostWithPath()) require.NoError(t, err) @@ -105,7 +105,7 @@ func TestMakeHTTPDialerURL(t *testing.T) { u, err := newParsedURL(errorURL) require.NoError(t, err) dialFn, err := makeHTTPDialer(errorURL) - require.Nil(t, err) + require.NoError(t, err) addr, err := dialFn(u.Scheme, u.GetHostWithPath()) require.Error(t, err) diff --git a/rpc/jsonrpc/client/integration_test.go b/rpc/jsonrpc/client/integration_test.go index 26f24d255..a8353aced 100644 --- a/rpc/jsonrpc/client/integration_test.go +++ b/rpc/jsonrpc/client/integration_test.go @@ -31,7 +31,7 @@ func TestWSClientReconnectWithJitter(t *testing.T) { logger := log.NewTMLogger(buf) for i := 0; i < n; i++ { c, err := NewWS("tcp://foo", "/websocket") - require.Nil(t, err) + require.NoError(t, err) c.Dialer = func(string, string) (net.Conn, error) { return nil, errNotConnected } diff --git a/rpc/jsonrpc/client/ws_client_test.go b/rpc/jsonrpc/client/ws_client_test.go index 13ac8444a..99fab2f65 100644 --- a/rpc/jsonrpc/client/ws_client_test.go +++ b/rpc/jsonrpc/client/ws_client_test.go @@ -225,9 +225,9 @@ func startClient(ctx context.Context, t *testing.T, addr string) *WSClient { opts.SkipMetrics = true c, err := NewWSWithOptions(addr, "/websocket", opts) - require.Nil(t, err) + require.NoError(t, err) err = c.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) c.Logger = log.NewTestingLogger(t) return c } diff --git a/rpc/jsonrpc/jsonrpc_test.go b/rpc/jsonrpc/jsonrpc_test.go index 1ee15d5d3..8868d507f 100644 --- a/rpc/jsonrpc/jsonrpc_test.go +++ b/rpc/jsonrpc/jsonrpc_test.go @@ -186,22 +186,22 @@ func echoDataBytesViaHTTP(ctx context.Context, cl client.Caller, bytes tmbytes.H func testWithHTTPClient(ctx context.Context, t *testing.T, cl client.HTTPClient) { val := testVal got, err := echoViaHTTP(ctx, cl, val) - require.Nil(t, err) + require.NoError(t, err) assert.Equal(t, got, val) val2 := randBytes(t) got2, err := echoBytesViaHTTP(ctx, cl, val2) - require.Nil(t, err) + require.NoError(t, err) assert.Equal(t, got2, val2) val3 := tmbytes.HexBytes(randBytes(t)) got3, err := echoDataBytesViaHTTP(ctx, cl, val3) - require.Nil(t, err) + require.NoError(t, err) assert.Equal(t, got3, val3) val4 := mrand.Intn(10000) got4, err := echoIntViaHTTP(ctx, cl, val4) - require.Nil(t, err) + require.NoError(t, err) assert.Equal(t, got4, val4) } @@ -252,12 +252,12 @@ func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) { func testWithWSClient(t *testing.T, cl *client.WSClient) { val := testVal got, err := echoViaWS(cl, val) - require.Nil(t, err) + require.NoError(t, err) assert.Equal(t, got, val) val2 := randBytes(t) got2, err := echoBytesViaWS(cl, val2) - require.Nil(t, err) + require.NoError(t, err) assert.Equal(t, got2, val2) } @@ -276,15 +276,15 @@ func TestServersAndClientsBasic(t *testing.T) { logger := log.NewTestingLogger(t) cl2, err := client.New(addr) - require.Nil(t, err) + require.NoError(t, err) fmt.Printf("=== testing server on %s using JSONRPC client", addr) testWithHTTPClient(ctx, t, cl2) cl3, err := client.NewWS(addr, websocketEndpoint) - require.Nil(t, err) + require.NoError(t, err) cl3.Logger = logger err = cl3.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) fmt.Printf("=== testing server on %s using WS client", addr) testWithWSClient(t, cl3) cancel() @@ -297,10 +297,10 @@ func TestWSNewWSRPCFunc(t *testing.T) { defer cancel() cl, err := client.NewWS(tcpAddr, websocketEndpoint) - require.Nil(t, err) + require.NoError(t, err) cl.Logger = log.NewTestingLogger(t) err = cl.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(func() { if err := cl.Stop(); err != nil { t.Error(err) @@ -312,7 +312,7 @@ func TestWSNewWSRPCFunc(t *testing.T) { "arg": val, } err = cl.Call(context.Background(), "echo_ws", params) - require.Nil(t, err) + require.NoError(t, err) msg := <-cl.ResponsesCh if msg.Error != nil { @@ -320,7 +320,7 @@ func TestWSNewWSRPCFunc(t *testing.T) { } result := new(ResultEcho) err = json.Unmarshal(msg.Result, result) - require.Nil(t, err) + require.NoError(t, err) got := result.Value assert.Equal(t, got, val) } @@ -330,7 +330,7 @@ func TestWSHandlesArrayParams(t *testing.T) { defer cancel() cl, err := client.NewWS(tcpAddr, websocketEndpoint) - require.Nil(t, err) + require.NoError(t, err) cl.Logger = log.NewTestingLogger(t) require.Nil(t, cl.Start(ctx)) @@ -343,7 +343,7 @@ func TestWSHandlesArrayParams(t *testing.T) { val := testVal params := []interface{}{val} err = cl.CallWithArrayParams(context.Background(), "echo_ws", params) - require.Nil(t, err) + require.NoError(t, err) msg := <-cl.ResponsesCh if msg.Error != nil { @@ -351,7 +351,7 @@ func TestWSHandlesArrayParams(t *testing.T) { } result := new(ResultEcho) err = json.Unmarshal(msg.Result, result) - require.Nil(t, err) + require.NoError(t, err) got := result.Value assert.Equal(t, got, val) } @@ -363,10 +363,10 @@ func TestWSClientPingPong(t *testing.T) { defer cancel() cl, err := client.NewWS(tcpAddr, websocketEndpoint) - require.Nil(t, err) + require.NoError(t, err) cl.Logger = log.NewTestingLogger(t) err = cl.Start(ctx) - require.Nil(t, err) + require.NoError(t, err) t.Cleanup(func() { if err := cl.Stop(); err != nil { t.Error(err) @@ -380,6 +380,6 @@ func randBytes(t *testing.T) []byte { n := mrand.Intn(10) + 2 buf := make([]byte, n) _, err := crand.Read(buf) - require.Nil(t, err) + require.NoError(t, err) return bytes.ReplaceAll(buf, []byte("="), []byte{100}) } diff --git a/rpc/jsonrpc/server/http_json_handler_test.go b/rpc/jsonrpc/server/http_json_handler_test.go index 94c241ca0..1a65d414d 100644 --- a/rpc/jsonrpc/server/http_json_handler_test.go +++ b/rpc/jsonrpc/server/http_json_handler_test.go @@ -121,7 +121,7 @@ func TestJSONRPCID(t *testing.T) { recv := new(rpctypes.RPCResponse) err = json.Unmarshal(blob, recv) - assert.Nil(t, err, "#%d: expecting successful parsing of an RPCResponse:\nblob: %s", i, blob) + assert.NoError(t, err, "#%d: expecting successful parsing of an RPCResponse:\nblob: %s", i, blob) if !tt.wantErr { assert.NotEqual(t, recv, new(rpctypes.RPCResponse), "#%d: not expecting a blank RPCResponse", i) assert.Equal(t, tt.expectedID, recv.ID, "#%d: expected ID not matched in RPCResponse", i) @@ -144,7 +144,7 @@ func TestRPCNotification(t *testing.T) { require.True(t, statusOK(res.StatusCode), "should always return 2XX") blob, err := io.ReadAll(res.Body) res.Body.Close() - require.Nil(t, err, "reading from the body should not give back an error") + require.NoError(t, err, "reading from the body should not give back an error") require.Equal(t, len(blob), 0, "a notification SHOULD NOT be responded to by the server") } @@ -241,7 +241,7 @@ func TestRPCResponseCache(t *testing.T) { _, err := io.ReadAll(res.Body) res.Body.Close() - require.Nil(t, err, "reading from the body should not give back an error") + require.NoError(t, err, "reading from the body should not give back an error") // send a request with default height. body = strings.NewReader(`{"jsonrpc": "2.0","method":"block","id": 0, "params": ["0"]}`) @@ -256,5 +256,5 @@ func TestRPCResponseCache(t *testing.T) { _, err = io.ReadAll(res.Body) res.Body.Close() - require.Nil(t, err, "reading from the body should not give back an error") + require.NoError(t, err, "reading from the body should not give back an error") } diff --git a/rpc/jsonrpc/server/parse_test.go b/rpc/jsonrpc/server/parse_test.go index 92ea6f2c0..6e7464739 100644 --- a/rpc/jsonrpc/server/parse_test.go +++ b/rpc/jsonrpc/server/parse_test.go @@ -19,7 +19,7 @@ func TestParseJSONMap(t *testing.T) { // naive is float,string var p1 map[string]interface{} err := json.Unmarshal(input, &p1) - if assert.Nil(t, err) { + if assert.NoError(t, err) { h, ok := p1["height"].(float64) if assert.True(t, ok, "%#v", p1["height"]) { assert.EqualValues(t, 22, h) @@ -37,7 +37,7 @@ func TestParseJSONMap(t *testing.T) { "height": &tmp, } err = json.Unmarshal(input, &p2) - if assert.Nil(t, err) { + if assert.NoError(t, err) { h, ok := p2["height"].(float64) if assert.True(t, ok, "%#v", p2["height"]) { assert.EqualValues(t, 22, h) @@ -59,7 +59,7 @@ func TestParseJSONMap(t *testing.T) { Value: &bytes.HexBytes{}, } err = json.Unmarshal(input, &p3) - if assert.Nil(t, err) { + if assert.NoError(t, err) { h, ok := p3.Height.(*int) if assert.True(t, ok, "%#v", p3.Height) { assert.Equal(t, 22, *h) @@ -76,7 +76,7 @@ func TestParseJSONMap(t *testing.T) { Height int `json:"height"` }{} err = json.Unmarshal(input, &p4) - if assert.Nil(t, err) { + if assert.NoError(t, err) { assert.EqualValues(t, 22, p4.Height) assert.EqualValues(t, []byte{0x12, 0x34}, p4.Value) } @@ -85,16 +85,16 @@ func TestParseJSONMap(t *testing.T) { // dynamic keys on map, and we can deserialize to the desired types var p5 map[string]*json.RawMessage err = json.Unmarshal(input, &p5) - if assert.Nil(t, err) { + if assert.NoError(t, err) { var h int err = json.Unmarshal(*p5["height"], &h) - if assert.Nil(t, err) { + if assert.NoError(t, err) { assert.Equal(t, 22, h) } var v bytes.HexBytes err = json.Unmarshal(*p5["value"], &v) - if assert.Nil(t, err) { + if assert.NoError(t, err) { assert.Equal(t, bytes.HexBytes{0x12, 0x34}, v) } } @@ -106,7 +106,7 @@ func TestParseJSONArray(t *testing.T) { // naive is float,string var p1 []interface{} err := json.Unmarshal(input, &p1) - if assert.Nil(t, err) { + if assert.NoError(t, err) { v, ok := p1[0].(string) if assert.True(t, ok, "%#v", p1[0]) { assert.EqualValues(t, "1234", v) @@ -121,7 +121,7 @@ func TestParseJSONArray(t *testing.T) { tmp := 0 p2 := []interface{}{&bytes.HexBytes{}, &tmp} err = json.Unmarshal(input, &p2) - if assert.Nil(t, err) { + if assert.NoError(t, err) { v, ok := p2[0].(*bytes.HexBytes) if assert.True(t, ok, "%#v", p2[0]) { assert.EqualValues(t, []byte{0x12, 0x34}, *v) @@ -158,9 +158,9 @@ func TestParseJSONRPC(t *testing.T) { data := []byte(tc.raw) vals, err := jsonParamsToArgs(call, data) if tc.fail { - assert.NotNil(t, err, i) + assert.Error(t, err, i) } else { - assert.Nil(t, err, "%s: %+v", i, err) + assert.NoError(t, err, "%s: %+v", i, err) if assert.Equal(t, 2, len(vals), i) { assert.Equal(t, tc.height, vals[0].Int(), i) assert.Equal(t, tc.name, vals[1].String(), i) @@ -200,9 +200,9 @@ func TestParseURI(t *testing.T) { assert.NoError(t, err) vals, err := httpParamsToArgs(call, req) if tc.fail { - assert.NotNil(t, err, i) + assert.Error(t, err, i) } else { - assert.Nil(t, err, "%s: %+v", i, err) + assert.NoError(t, err, "%s: %+v", i, err) if assert.Equal(t, 2, len(vals), i) { assert.Equal(t, tc.height, vals[0].Int(), i) assert.Equal(t, tc.name, vals[1].String(), i) diff --git a/rpc/jsonrpc/types/types_test.go b/rpc/jsonrpc/types/types_test.go index d57a0403d..477d83788 100644 --- a/rpc/jsonrpc/types/types_test.go +++ b/rpc/jsonrpc/types/types_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type SampleResult struct { @@ -30,41 +31,40 @@ var responseTests = []responseTest{ } func TestResponses(t *testing.T) { - assert := assert.New(t) for _, tt := range responseTests { jsonid := tt.id a := NewRPCSuccessResponse(jsonid, &SampleResult{"hello"}) b, _ := json.Marshal(a) s := fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"Value":"hello"}}`, tt.expected) - assert.Equal(s, string(b)) + assert.Equal(t, s, string(b)) d := RPCParseError(errors.New("hello world")) e, _ := json.Marshal(d) f := `{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"hello world"}}` - assert.Equal(f, string(e)) + assert.Equal(t, f, string(e)) g := RPCMethodNotFoundError(jsonid) h, _ := json.Marshal(g) i := fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"error":{"code":-32601,"message":"Method not found"}}`, tt.expected) - assert.Equal(string(h), i) + assert.Equal(t, string(h), i) } } func TestUnmarshallResponses(t *testing.T) { - assert := assert.New(t) for _, tt := range responseTests { response := &RPCResponse{} err := json.Unmarshal( []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"Value":"hello"}}`, tt.expected)), response, ) - assert.Nil(err) + require.NoError(t, err) + a := NewRPCSuccessResponse(tt.id, &SampleResult{"hello"}) - assert.Equal(*response, a) + assert.Equal(t, *response, a) } response := &RPCResponse{} err := json.Unmarshal([]byte(`{"jsonrpc":"2.0","id":true,"result":{"Value":"hello"}}`), response) - assert.NotNil(err) + require.Error(t, err) } func TestRPCError(t *testing.T) { diff --git a/types/block_test.go b/types/block_test.go index 64d98131f..17eef2889 100644 --- a/types/block_test.go +++ b/types/block_test.go @@ -606,7 +606,7 @@ func TestCommitToVoteSetWithVotesForNilBlock(t *testing.T) { commit := voteSet.MakeCommit() // panics without > 2/3 valid votes assert.NotNil(t, commit) err := valSet.VerifyCommit(voteSet.ChainID(), blockID, height-1, commit) - assert.Nil(t, err) + assert.NoError(t, err) } else { assert.Panics(t, func() { voteSet.MakeCommit() }) } diff --git a/types/node_info_test.go b/types/node_info_test.go index ff30aa30a..9a5a90d51 100644 --- a/types/node_info_test.go +++ b/types/node_info_test.go @@ -241,7 +241,7 @@ func TestParseAddressString(t *testing.T) { t.Run(tc.name, func(t *testing.T) { addr, port, err := ParseAddressString(tc.addr) if tc.correct { - require.Nil(t, err, tc.addr) + require.NoError(t, err, tc.addr) assert.Contains(t, tc.expected, addr.String()) assert.Contains(t, tc.expected, fmt.Sprint(port)) } else { diff --git a/types/node_key_test.go b/types/node_key_test.go index ae6b68101..0dea771ea 100644 --- a/types/node_key_test.go +++ b/types/node_key_test.go @@ -14,10 +14,10 @@ func TestLoadOrGenNodeKey(t *testing.T) { filePath := filepath.Join(t.TempDir(), "peer_id.json") nodeKey, err := types.LoadOrGenNodeKey(filePath) - require.Nil(t, err) + require.NoError(t, err) nodeKey2, err := types.LoadOrGenNodeKey(filePath) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, nodeKey, nodeKey2) } diff --git a/types/part_set_test.go b/types/part_set_test.go index 2dfe12263..af65ca8db 100644 --- a/types/part_set_test.go +++ b/types/part_set_test.go @@ -48,7 +48,7 @@ func TestBasicPartSet(t *testing.T) { // adding existing part added, err = partSet2.AddPart(partSet2.GetPart(0)) assert.False(t, added) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, partSet.Hash(), partSet2.Hash()) assert.EqualValues(t, nParts, partSet2.Total()) diff --git a/types/protobuf_test.go b/types/protobuf_test.go index a33d031e2..3ab095eee 100644 --- a/types/protobuf_test.go +++ b/types/protobuf_test.go @@ -37,7 +37,7 @@ func TestABCIValidators(t *testing.T) { abciVal := TM2PB.ValidatorUpdate(tmVal) tmVals, err := PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{abciVal}) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, tmValExpected, tmVals[0]) abciVals := TM2PB.ValidatorUpdates(NewValidatorSet(tmVals)) @@ -48,7 +48,7 @@ func TestABCIValidators(t *testing.T) { abciVal = TM2PB.ValidatorUpdate(tmVal) tmVals, err = PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{abciVal}) - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, tmValExpected, tmVals[0]) } diff --git a/types/tx_test.go b/types/tx_test.go index 8fe277da8..e2f12772a 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -92,7 +92,7 @@ func TestValidTxProof(t *testing.T) { require.NoError(t, err) p2, err = TxProofFromProto(pb2) - if assert.Nil(t, err, "%d: %d: %+v", h, i, err) { + if assert.NoError(t, err, "%d: %d: %+v", h, i, err) { assert.Nil(t, p2.Validate(root), "%d: %d", h, i) } }