Browse Source

Clean up temp files more thoroughly after testing. (#7815)

Our test cases spew a lot of files and directories around $TMPDIR.  Make more
thorough use of the testing package's TempDir methods to ensure these are
cleaned up.

In a few cases, this required plumbing test contexts through existing helper
code. In a couple places an explicit path was required, to work around cases
where we do global setup during a TestMain function. Those cases probably
deserve more thorough cleansing (preferably with fire), but for now I have just
worked around it to keep focused on the cleanup.
pull/7820/head
M. J. Fromberger 3 years ago
committed by GitHub
parent
commit
7e09c2ef43
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 149 additions and 213 deletions
  1. +3
    -13
      abci/example/kvstore/kvstore_test.go
  2. +1
    -1
      cmd/tendermint/commands/reindex_event_test.go
  3. +1
    -1
      cmd/tendermint/commands/rollback_test.go
  4. +4
    -4
      config/toml.go
  5. +2
    -4
      config/toml_test.go
  6. +4
    -4
      internal/blocksync/reactor_test.go
  7. +1
    -1
      internal/consensus/byzantine_test.go
  8. +13
    -14
      internal/consensus/common_test.go
  9. +3
    -3
      internal/consensus/mempool_test.go
  10. +1
    -1
      internal/consensus/reactor_test.go
  11. +6
    -6
      internal/consensus/replay_test.go
  12. +9
    -18
      internal/consensus/types/height_vote_set_test.go
  13. +1
    -1
      internal/consensus/wal_generator.go
  14. +2
    -2
      internal/inspect/inspect_test.go
  15. +3
    -9
      internal/libs/autofile/autofile_test.go
  16. +2
    -5
      internal/libs/autofile/group_test.go
  17. +1
    -1
      internal/libs/tempfile/tempfile_test.go
  18. +1
    -1
      internal/mempool/mempool_test.go
  19. +1
    -1
      internal/mempool/reactor_test.go
  20. +1
    -5
      internal/state/indexer/tx/kv/kv_bench_test.go
  21. +1
    -4
      internal/state/indexer/tx/kv/kv_test.go
  22. +1
    -1
      internal/state/state_test.go
  23. +1
    -1
      internal/state/store_test.go
  24. +2
    -4
      internal/statesync/chunks_test.go
  25. +3
    -3
      internal/statesync/syncer_test.go
  26. +12
    -8
      internal/store/store_test.go
  27. +3
    -10
      libs/cli/setup_test.go
  28. +4
    -10
      libs/os/os_test.go
  29. +15
    -21
      light/example_test.go
  30. +6
    -16
      light/light_test.go
  31. +1
    -1
      light/provider/http/http_test.go
  32. +12
    -12
      node/node_test.go
  33. +12
    -12
      privval/file_test.go
  34. +1
    -1
      privval/socket_dialers_test.go
  35. +7
    -4
      privval/socket_listeners_test.go
  36. +2
    -2
      rpc/client/examples_test.go
  37. +2
    -5
      rpc/client/main_test.go
  38. +3
    -2
      rpc/test/helpers.go
  39. +1
    -1
      types/genesis_test.go

+ 3
- 13
abci/example/kvstore/kvstore_test.go View File

@ -3,7 +3,6 @@ package kvstore
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"sort" "sort"
"testing" "testing"
@ -72,10 +71,7 @@ func TestKVStoreKV(t *testing.T) {
} }
func TestPersistentKVStoreKV(t *testing.T) { func TestPersistentKVStoreKV(t *testing.T) {
dir, err := os.MkdirTemp("/tmp", "abci-kvstore-test") // TODO
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
logger := log.NewTestingLogger(t) logger := log.NewTestingLogger(t)
kvstore := NewPersistentKVStoreApplication(logger, dir) kvstore := NewPersistentKVStoreApplication(logger, dir)
@ -90,10 +86,7 @@ func TestPersistentKVStoreKV(t *testing.T) {
} }
func TestPersistentKVStoreInfo(t *testing.T) { func TestPersistentKVStoreInfo(t *testing.T) {
dir, err := os.MkdirTemp("/tmp", "abci-kvstore-test") // TODO
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
logger := log.NewTestingLogger(t) logger := log.NewTestingLogger(t)
kvstore := NewPersistentKVStoreApplication(logger, dir) kvstore := NewPersistentKVStoreApplication(logger, dir)
@ -124,10 +117,7 @@ func TestPersistentKVStoreInfo(t *testing.T) {
// add a validator, remove a validator, update a validator // add a validator, remove a validator, update a validator
func TestValUpdates(t *testing.T) { func TestValUpdates(t *testing.T) {
dir, err := os.MkdirTemp("/tmp", "abci-kvstore-test") // TODO
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
logger := log.NewTestingLogger(t) logger := log.NewTestingLogger(t)
kvstore := NewPersistentKVStoreApplication(logger, dir) kvstore := NewPersistentKVStoreApplication(logger, dir)


+ 1
- 1
cmd/tendermint/commands/reindex_event_test.go View File

@ -110,7 +110,7 @@ func TestLoadEventSink(t *testing.T) {
} }
func TestLoadBlockStore(t *testing.T) { func TestLoadBlockStore(t *testing.T) {
testCfg, err := config.ResetTestRoot(t.Name())
testCfg, err := config.ResetTestRoot(t.TempDir(), t.Name())
require.NoError(t, err) require.NoError(t, err)
testCfg.DBBackend = "goleveldb" testCfg.DBBackend = "goleveldb"
_, _, err = loadStateAndBlockStore(testCfg) _, _, err = loadStateAndBlockStore(testCfg)


+ 1
- 1
cmd/tendermint/commands/rollback_test.go View File

@ -19,7 +19,7 @@ func TestRollbackIntegration(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := rpctest.CreateConfig(t.Name())
cfg, err := rpctest.CreateConfig(t, t.Name())
require.NoError(t, err) require.NoError(t, err)
cfg.BaseConfig.DBBackend = "goleveldb" cfg.BaseConfig.DBBackend = "goleveldb"


+ 4
- 4
config/toml.go View File

@ -504,13 +504,13 @@ namespace = "{{ .Instrumentation.Namespace }}"
/****** these are for test settings ***********/ /****** these are for test settings ***********/
func ResetTestRoot(testName string) (*Config, error) {
return ResetTestRootWithChainID(testName, "")
func ResetTestRoot(dir, testName string) (*Config, error) {
return ResetTestRootWithChainID(dir, testName, "")
} }
func ResetTestRootWithChainID(testName string, chainID string) (*Config, error) {
func ResetTestRootWithChainID(dir, testName string, chainID string) (*Config, error) {
// create a unique, concurrency-safe test directory under os.TempDir() // create a unique, concurrency-safe test directory under os.TempDir()
rootDir, err := os.MkdirTemp("", fmt.Sprintf("%s-%s_", chainID, testName))
rootDir, err := os.MkdirTemp(dir, fmt.Sprintf("%s-%s_", chainID, testName))
if err != nil { if err != nil {
return nil, err return nil, err
} }


+ 2
- 4
config/toml_test.go View File

@ -20,9 +20,7 @@ func ensureFiles(t *testing.T, rootDir string, files ...string) {
func TestEnsureRoot(t *testing.T) { func TestEnsureRoot(t *testing.T) {
// setup temp dir for test // setup temp dir for test
tmpDir, err := os.MkdirTemp("", "config-test")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
tmpDir := t.TempDir()
// create root dir // create root dir
EnsureRoot(tmpDir) EnsureRoot(tmpDir)
@ -42,7 +40,7 @@ func TestEnsureTestRoot(t *testing.T) {
testName := "ensureTestRoot" testName := "ensureTestRoot"
// create root dir // create root dir
cfg, err := ResetTestRoot(testName)
cfg, err := ResetTestRoot(t.TempDir(), testName)
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
rootDir := cfg.RootDir rootDir := cfg.RootDir


+ 4
- 4
internal/blocksync/reactor_test.go View File

@ -203,7 +203,7 @@ func TestReactor_AbruptDisconnect(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("block_sync_reactor_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "block_sync_reactor_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -243,7 +243,7 @@ func TestReactor_SyncTime(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("block_sync_reactor_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "block_sync_reactor_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -271,7 +271,7 @@ func TestReactor_NoBlockResponse(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("block_sync_reactor_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "block_sync_reactor_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -323,7 +323,7 @@ func TestReactor_BadBlockStopsPeer(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("block_sync_reactor_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "block_sync_reactor_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)


+ 1
- 1
internal/consensus/byzantine_test.go View File

@ -60,7 +60,7 @@ func TestByzantinePrevoteEquivocation(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, stateStore.Save(state)) require.NoError(t, stateStore.Save(state))
thisConfig, err := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
thisConfig, err := ResetConfig(t.TempDir(), fmt.Sprintf("%s_%d", testName, i))
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(thisConfig.RootDir) defer os.RemoveAll(thisConfig.RootDir)


+ 13
- 14
internal/consensus/common_test.go View File

@ -50,23 +50,23 @@ type cleanupFunc func()
func configSetup(t *testing.T) *config.Config { func configSetup(t *testing.T) *config.Config {
t.Helper() t.Helper()
cfg, err := ResetConfig("consensus_reactor_test")
cfg, err := ResetConfig(t.TempDir(), "consensus_reactor_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(cfg.RootDir) }) t.Cleanup(func() { os.RemoveAll(cfg.RootDir) })
consensusReplayConfig, err := ResetConfig("consensus_replay_test")
consensusReplayConfig, err := ResetConfig(t.TempDir(), "consensus_replay_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(consensusReplayConfig.RootDir) }) t.Cleanup(func() { os.RemoveAll(consensusReplayConfig.RootDir) })
configStateTest, err := ResetConfig("consensus_state_test")
configStateTest, err := ResetConfig(t.TempDir(), "consensus_state_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(configStateTest.RootDir) }) t.Cleanup(func() { os.RemoveAll(configStateTest.RootDir) })
configMempoolTest, err := ResetConfig("consensus_mempool_test")
configMempoolTest, err := ResetConfig(t.TempDir(), "consensus_mempool_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(configMempoolTest.RootDir) }) t.Cleanup(func() { os.RemoveAll(configMempoolTest.RootDir) })
configByzantineTest, err := ResetConfig("consensus_byzantine_test")
configByzantineTest, err := ResetConfig(t.TempDir(), "consensus_byzantine_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(configByzantineTest.RootDir) }) t.Cleanup(func() { os.RemoveAll(configByzantineTest.RootDir) })
@ -78,8 +78,8 @@ func ensureDir(t *testing.T, dir string, mode os.FileMode) {
require.NoError(t, tmos.EnsureDir(dir, mode)) require.NoError(t, tmos.EnsureDir(dir, mode))
} }
func ResetConfig(name string) (*config.Config, error) {
return config.ResetTestRoot(name)
func ResetConfig(dir, name string) (*config.Config, error) {
return config.ResetTestRoot(dir, name)
} }
//------------------------------------------------------------------------------- //-------------------------------------------------------------------------------
@ -422,7 +422,7 @@ func newState(
) *State { ) *State {
t.Helper() t.Helper()
cfg, err := config.ResetTestRoot("consensus_state_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "consensus_state_test")
require.NoError(t, err) require.NoError(t, err)
return newStateWithConfig(ctx, t, logger, cfg, state, pv, app) return newStateWithConfig(ctx, t, logger, cfg, state, pv, app)
@ -769,7 +769,7 @@ func makeConsensusState(
blockStore := store.NewBlockStore(dbm.NewMemDB()) // each state needs its own db blockStore := store.NewBlockStore(dbm.NewMemDB()) // each state needs its own db
state, err := sm.MakeGenesisState(genDoc) state, err := sm.MakeGenesisState(genDoc)
require.NoError(t, err) require.NoError(t, err)
thisConfig, err := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
thisConfig, err := ResetConfig(t.TempDir(), fmt.Sprintf("%s_%d", testName, i))
require.NoError(t, err) require.NoError(t, err)
configRootDirs = append(configRootDirs, thisConfig.RootDir) configRootDirs = append(configRootDirs, thisConfig.RootDir)
@ -827,7 +827,7 @@ func randConsensusNetWithPeers(
configRootDirs := make([]string, 0, nPeers) configRootDirs := make([]string, 0, nPeers)
for i := 0; i < nPeers; i++ { for i := 0; i < nPeers; i++ {
state, _ := sm.MakeGenesisState(genDoc) state, _ := sm.MakeGenesisState(genDoc)
thisConfig, err := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
thisConfig, err := ResetConfig(t.TempDir(), fmt.Sprintf("%s_%d", testName, i))
require.NoError(t, err) require.NoError(t, err)
configRootDirs = append(configRootDirs, thisConfig.RootDir) configRootDirs = append(configRootDirs, thisConfig.RootDir)
@ -839,10 +839,10 @@ func randConsensusNetWithPeers(
if i < nValidators { if i < nValidators {
privVal = privVals[i] privVal = privVals[i]
} else { } else {
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_")
require.NoError(t, err) require.NoError(t, err)
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_")
require.NoError(t, err) require.NoError(t, err)
privVal, err = privval.GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") privVal, err = privval.GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
@ -946,8 +946,7 @@ func (*mockTicker) SetLogger(log.Logger) {}
func newPersistentKVStore(t *testing.T, logger log.Logger) abci.Application { func newPersistentKVStore(t *testing.T, logger log.Logger) abci.Application {
t.Helper() t.Helper()
dir, err := os.MkdirTemp("", "persistent-kvstore")
require.NoError(t, err)
dir := t.TempDir()
return kvstore.NewPersistentKVStoreApplication(logger, dir) return kvstore.NewPersistentKVStoreApplication(logger, dir)
} }


+ 3
- 3
internal/consensus/mempool_test.go View File

@ -35,7 +35,7 @@ func TestMempoolNoProgressUntilTxsAvailable(t *testing.T) {
baseConfig := configSetup(t) baseConfig := configSetup(t)
config, err := ResetConfig("consensus_mempool_txs_available_test")
config, err := ResetConfig(t.TempDir(), "consensus_mempool_txs_available_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) }) t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
@ -62,7 +62,7 @@ func TestMempoolProgressAfterCreateEmptyBlocksInterval(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
config, err := ResetConfig("consensus_mempool_txs_available_test")
config, err := ResetConfig(t.TempDir(), "consensus_mempool_txs_available_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) }) t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
@ -87,7 +87,7 @@ func TestMempoolProgressInHigherRound(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
config, err := ResetConfig("consensus_mempool_txs_available_test")
config, err := ResetConfig(t.TempDir(), "consensus_mempool_txs_available_test")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) }) t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })


+ 1
- 1
internal/consensus/reactor_test.go View File

@ -391,7 +391,7 @@ func TestReactorWithEvidence(t *testing.T) {
stateStore := sm.NewStore(stateDB) stateStore := sm.NewStore(stateDB)
state, err := sm.MakeGenesisState(genDoc) state, err := sm.MakeGenesisState(genDoc)
require.NoError(t, err) require.NoError(t, err)
thisConfig, err := ResetConfig(fmt.Sprintf("%s_%d", testName, i))
thisConfig, err := ResetConfig(t.TempDir(), fmt.Sprintf("%s_%d", testName, i))
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(thisConfig.RootDir) defer os.RemoveAll(thisConfig.RootDir)


+ 6
- 6
internal/consensus/replay_test.go View File

@ -142,7 +142,7 @@ func TestWALCrash(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
tc := tc tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
consensusReplayConfig, err := ResetConfig(tc.name)
consensusReplayConfig, err := ResetConfig(t.TempDir(), tc.name)
require.NoError(t, err) require.NoError(t, err)
crashWALandCheckLiveness(ctx, t, consensusReplayConfig, tc.initFn, tc.heightToStop) crashWALandCheckLiveness(ctx, t, consensusReplayConfig, tc.initFn, tc.heightToStop)
}) })
@ -709,7 +709,7 @@ func TestMockProxyApp(t *testing.T) {
func tempWALWithData(t *testing.T, data []byte) string { func tempWALWithData(t *testing.T, data []byte) string {
t.Helper() t.Helper()
walFile, err := os.CreateTemp("", "wal")
walFile, err := os.CreateTemp(t.TempDir(), "wal")
require.NoError(t, err, "failed to create temp WAL file") require.NoError(t, err, "failed to create temp WAL file")
_, err = walFile.Write(data) _, err = walFile.Write(data)
@ -743,7 +743,7 @@ func testHandshakeReplay(
logger := log.TestingLogger() logger := log.TestingLogger()
if testValidatorsChange { if testValidatorsChange {
testConfig, err := ResetConfig(fmt.Sprintf("%s_%v_m", t.Name(), mode))
testConfig, err := ResetConfig(t.TempDir(), fmt.Sprintf("%s_%v_m", t.Name(), mode))
require.NoError(t, err) require.NoError(t, err)
defer func() { _ = os.RemoveAll(testConfig.RootDir) }() defer func() { _ = os.RemoveAll(testConfig.RootDir) }()
stateDB = dbm.NewMemDB() stateDB = dbm.NewMemDB()
@ -754,7 +754,7 @@ func testHandshakeReplay(
commits = sim.Commits commits = sim.Commits
store = newMockBlockStore(t, cfg, genesisState.ConsensusParams) store = newMockBlockStore(t, cfg, genesisState.ConsensusParams)
} else { // test single node } else { // test single node
testConfig, err := ResetConfig(fmt.Sprintf("%s_%v_s", t.Name(), mode))
testConfig, err := ResetConfig(t.TempDir(), fmt.Sprintf("%s_%v_s", t.Name(), mode))
require.NoError(t, err) require.NoError(t, err)
defer func() { _ = os.RemoveAll(testConfig.RootDir) }() defer func() { _ = os.RemoveAll(testConfig.RootDir) }()
walBody, err := WALWithNBlocks(ctx, t, logger, numBlocks) walBody, err := WALWithNBlocks(ctx, t, logger, numBlocks)
@ -1004,7 +1004,7 @@ func TestHandshakePanicsIfAppReturnsWrongAppHash(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := ResetConfig("handshake_test_")
cfg, err := ResetConfig(t.TempDir(), "handshake_test_")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(cfg.RootDir) }) t.Cleanup(func() { os.RemoveAll(cfg.RootDir) })
privVal, err := privval.LoadFilePV(cfg.PrivValidator.KeyFile(), cfg.PrivValidator.StateFile()) privVal, err := privval.LoadFilePV(cfg.PrivValidator.KeyFile(), cfg.PrivValidator.StateFile())
@ -1288,7 +1288,7 @@ func TestHandshakeUpdatesValidators(t *testing.T) {
app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)} app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}
clientCreator := abciclient.NewLocalCreator(app) clientCreator := abciclient.NewLocalCreator(app)
cfg, err := ResetConfig("handshake_test_")
cfg, err := ResetConfig(t.TempDir(), "handshake_test_")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(cfg.RootDir) }) t.Cleanup(func() { _ = os.RemoveAll(cfg.RootDir) })


+ 9
- 18
internal/consensus/types/height_vote_set_test.go View File

@ -2,8 +2,6 @@ package types
import ( import (
"context" "context"
"log"
"os"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -16,40 +14,33 @@ import (
"github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/types"
) )
var cfg *config.Config // NOTE: must be reset for each _test.go file
func TestMain(m *testing.M) {
var err error
cfg, err = config.ResetTestRoot("consensus_height_vote_set_test")
func TestPeerCatchupRounds(t *testing.T) {
cfg, err := config.ResetTestRoot(t.TempDir(), "consensus_height_vote_set_test")
if err != nil { if err != nil {
log.Fatal(err)
t.Fatal(err)
} }
code := m.Run()
os.RemoveAll(cfg.RootDir)
os.Exit(code)
}
func TestPeerCatchupRounds(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
valSet, privVals := factory.ValidatorSet(ctx, t, 10, 1) valSet, privVals := factory.ValidatorSet(ctx, t, 10, 1)
hvs := NewHeightVoteSet(cfg.ChainID(), 1, valSet)
chainID := cfg.ChainID()
hvs := NewHeightVoteSet(chainID, 1, valSet)
vote999_0 := makeVoteHR(ctx, t, 1, 0, 999, privVals)
vote999_0 := makeVoteHR(ctx, t, 1, 0, 999, privVals, chainID)
added, err := hvs.AddVote(vote999_0, "peer1") added, err := hvs.AddVote(vote999_0, "peer1")
if !added || err != nil { if !added || err != nil {
t.Error("Expected to successfully add vote from peer", added, err) t.Error("Expected to successfully add vote from peer", added, err)
} }
vote1000_0 := makeVoteHR(ctx, t, 1, 0, 1000, privVals)
vote1000_0 := makeVoteHR(ctx, t, 1, 0, 1000, privVals, chainID)
added, err = hvs.AddVote(vote1000_0, "peer1") added, err = hvs.AddVote(vote1000_0, "peer1")
if !added || err != nil { if !added || err != nil {
t.Error("Expected to successfully add vote from peer", added, err) t.Error("Expected to successfully add vote from peer", added, err)
} }
vote1001_0 := makeVoteHR(ctx, t, 1, 0, 1001, privVals)
vote1001_0 := makeVoteHR(ctx, t, 1, 0, 1001, privVals, chainID)
added, err = hvs.AddVote(vote1001_0, "peer1") added, err = hvs.AddVote(vote1001_0, "peer1")
if err != ErrGotVoteFromUnwantedRound { if err != ErrGotVoteFromUnwantedRound {
t.Errorf("expected GotVoteFromUnwantedRoundError, but got %v", err) t.Errorf("expected GotVoteFromUnwantedRoundError, but got %v", err)
@ -71,6 +62,7 @@ func makeVoteHR(
height int64, height int64,
valIndex, round int32, valIndex, round int32,
privVals []types.PrivValidator, privVals []types.PrivValidator,
chainID string,
) *types.Vote { ) *types.Vote {
t.Helper() t.Helper()
@ -89,7 +81,6 @@ func makeVoteHR(
Type: tmproto.PrecommitType, Type: tmproto.PrecommitType,
BlockID: types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}}, BlockID: types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}},
} }
chainID := cfg.ChainID()
v := vote.ToProto() v := vote.ToProto()
err = privVal.SignVote(ctx, chainID, v) err = privVal.SignVote(ctx, chainID, v)


+ 1
- 1
internal/consensus/wal_generator.go View File

@ -145,7 +145,7 @@ func makeAddrs() (p2pAddr, rpcAddr string) {
// getConfig returns a config for test cases // getConfig returns a config for test cases
func getConfig(t *testing.T) *config.Config { func getConfig(t *testing.T) *config.Config {
c, err := config.ResetTestRoot(t.Name())
c, err := config.ResetTestRoot(t.TempDir(), t.Name())
require.NoError(t, err) require.NoError(t, err)
p2pAddr, rpcAddr := makeAddrs() p2pAddr, rpcAddr := makeAddrs()


+ 2
- 2
internal/inspect/inspect_test.go View File

@ -28,7 +28,7 @@ import (
) )
func TestInspectConstructor(t *testing.T) { func TestInspectConstructor(t *testing.T) {
cfg, err := config.ResetTestRoot("test")
cfg, err := config.ResetTestRoot(t.TempDir(), "test")
require.NoError(t, err) require.NoError(t, err)
testLogger := log.TestingLogger() testLogger := log.TestingLogger()
t.Cleanup(leaktest.Check(t)) t.Cleanup(leaktest.Check(t))
@ -43,7 +43,7 @@ func TestInspectConstructor(t *testing.T) {
} }
func TestInspectRun(t *testing.T) { func TestInspectRun(t *testing.T) {
cfg, err := config.ResetTestRoot("test")
cfg, err := config.ResetTestRoot(t.TempDir(), "test")
require.NoError(t, err) require.NoError(t, err)
testLogger := log.TestingLogger() testLogger := log.TestingLogger()


+ 3
- 9
internal/libs/autofile/autofile_test.go View File

@ -25,11 +25,7 @@ func TestSIGHUP(t *testing.T) {
}) })
// First, create a temporary directory and move into it // First, create a temporary directory and move into it
dir, err := os.MkdirTemp("", "sighup_test")
require.NoError(t, err)
t.Cleanup(func() {
_ = os.RemoveAll(dir)
})
dir := t.TempDir()
require.NoError(t, os.Chdir(dir)) require.NoError(t, os.Chdir(dir))
// Create an AutoFile in the temporary directory // Create an AutoFile in the temporary directory
@ -48,9 +44,7 @@ func TestSIGHUP(t *testing.T) {
require.NoError(t, os.Rename(name, name+"_old")) require.NoError(t, os.Rename(name, name+"_old"))
// Move into a different temporary directory // Move into a different temporary directory
otherDir, err := os.MkdirTemp("", "sighup_test_other")
require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(otherDir) })
otherDir := t.TempDir()
require.NoError(t, os.Chdir(otherDir)) require.NoError(t, os.Chdir(otherDir))
// Send SIGHUP to self. // Send SIGHUP to self.
@ -112,7 +106,7 @@ func TestAutoFileSize(t *testing.T) {
defer cancel() defer cancel()
// First, create an AutoFile writing to a tempfile dir // First, create an AutoFile writing to a tempfile dir
f, err := os.CreateTemp("", "sighup_test")
f, err := os.CreateTemp(t.TempDir(), "sighup_test")
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, f.Close()) require.NoError(t, f.Close())


+ 2
- 5
internal/libs/autofile/group_test.go View File

@ -132,11 +132,8 @@ func TestRotateFile(t *testing.T) {
} }
}() }()
dir, err := os.MkdirTemp("", "rotate_test")
require.NoError(t, err)
defer os.RemoveAll(dir)
err = os.Chdir(dir)
require.NoError(t, err)
dir := t.TempDir()
require.NoError(t, os.Chdir(dir))
require.True(t, filepath.IsAbs(g.Head.Path)) require.True(t, filepath.IsAbs(g.Head.Path))
require.True(t, filepath.IsAbs(g.Dir)) require.True(t, filepath.IsAbs(g.Dir))


+ 1
- 1
internal/libs/tempfile/tempfile_test.go View File

@ -21,7 +21,7 @@ func TestWriteFileAtomic(t *testing.T) {
perm os.FileMode = 0600 perm os.FileMode = 0600
) )
f, err := os.CreateTemp("/tmp", "write-atomic-test-")
f, err := os.CreateTemp(t.TempDir(), "write-atomic-test-")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }


+ 1
- 1
internal/mempool/mempool_test.go View File

@ -82,7 +82,7 @@ func setup(ctx context.Context, t testing.TB, cacheSize int, options ...TxMempoo
cc := abciclient.NewLocalCreator(app) cc := abciclient.NewLocalCreator(app)
logger := log.TestingLogger() logger := log.TestingLogger()
cfg, err := config.ResetTestRoot(strings.ReplaceAll(t.Name(), "/", "|"))
cfg, err := config.ResetTestRoot(t.TempDir(), strings.ReplaceAll(t.Name(), "/", "|"))
require.NoError(t, err) require.NoError(t, err)
cfg.Mempool.CacheSize = cacheSize cfg.Mempool.CacheSize = cacheSize
appConnMem, err := cc(logger) appConnMem, err := cc(logger)


+ 1
- 1
internal/mempool/reactor_test.go View File

@ -41,7 +41,7 @@ type reactorTestSuite struct {
func setupReactors(ctx context.Context, t *testing.T, numNodes int, chBuf uint) *reactorTestSuite { func setupReactors(ctx context.Context, t *testing.T, numNodes int, chBuf uint) *reactorTestSuite {
t.Helper() t.Helper()
cfg, err := config.ResetTestRoot(strings.ReplaceAll(t.Name(), "/", "|"))
cfg, err := config.ResetTestRoot(t.TempDir(), strings.ReplaceAll(t.Name(), "/", "|"))
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(cfg.RootDir) }) t.Cleanup(func() { os.RemoveAll(cfg.RootDir) })


+ 1
- 5
internal/state/indexer/tx/kv/kv_bench_test.go View File

@ -4,7 +4,6 @@ import (
"context" "context"
"crypto/rand" "crypto/rand"
"fmt" "fmt"
"os"
"testing" "testing"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
@ -15,10 +14,7 @@ import (
) )
func BenchmarkTxSearch(b *testing.B) { func BenchmarkTxSearch(b *testing.B) {
dbDir, err := os.MkdirTemp("", "benchmark_tx_search_test")
if err != nil {
b.Errorf("failed to create temporary directory: %s", err)
}
dbDir := b.TempDir()
db, err := dbm.NewGoLevelDB("benchmark_tx_search_test", dbDir) db, err := dbm.NewGoLevelDB("benchmark_tx_search_test", dbDir)
if err != nil { if err != nil {


+ 1
- 4
internal/state/indexer/tx/kv/kv_test.go View File

@ -3,7 +3,6 @@ package kv
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"testing" "testing"
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
@ -333,9 +332,7 @@ func txResultWithEvents(events []abci.Event) *abci.TxResult {
} }
func benchmarkTxIndex(txsCount int64, b *testing.B) { func benchmarkTxIndex(txsCount int64, b *testing.B) {
dir, err := os.MkdirTemp("", "tx_index_db")
require.NoError(b, err)
defer os.RemoveAll(dir)
dir := b.TempDir()
store, err := dbm.NewDB("tx_index", "goleveldb", dir) store, err := dbm.NewDB("tx_index", "goleveldb", dir)
require.NoError(b, err) require.NoError(b, err)


+ 1
- 1
internal/state/state_test.go View File

@ -26,7 +26,7 @@ import (
// setupTestCase does setup common to all test cases. // setupTestCase does setup common to all test cases.
func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, sm.State) { func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, sm.State) {
cfg, err := config.ResetTestRoot("state_")
cfg, err := config.ResetTestRoot(t.TempDir(), "state_")
require.NoError(t, err) require.NoError(t, err)
dbType := dbm.BackendType(cfg.DBBackend) dbType := dbm.BackendType(cfg.DBBackend)


+ 1
- 1
internal/state/store_test.go View File

@ -110,7 +110,7 @@ func TestStoreLoadValidators(t *testing.T) {
func BenchmarkLoadValidators(b *testing.B) { func BenchmarkLoadValidators(b *testing.B) {
const valSetSize = 100 const valSetSize = 100
cfg, err := config.ResetTestRoot("state_")
cfg, err := config.ResetTestRoot(b.TempDir(), "state_")
require.NoError(b, err) require.NoError(b, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)


+ 2
- 4
internal/statesync/chunks_test.go View File

@ -18,7 +18,7 @@ func setupChunkQueue(t *testing.T) (*chunkQueue, func()) {
Hash: []byte{7}, Hash: []byte{7},
Metadata: nil, Metadata: nil,
} }
queue, err := newChunkQueue(snapshot, "")
queue, err := newChunkQueue(snapshot, t.TempDir())
require.NoError(t, err) require.NoError(t, err)
teardown := func() { teardown := func() {
err := queue.Close() err := queue.Close()
@ -35,9 +35,7 @@ func TestNewChunkQueue_TempDir(t *testing.T) {
Hash: []byte{7}, Hash: []byte{7},
Metadata: nil, Metadata: nil,
} }
dir, err := os.MkdirTemp("", "newchunkqueue")
require.NoError(t, err)
defer os.RemoveAll(dir)
dir := t.TempDir()
queue, err := newChunkQueue(snapshot, dir) queue, err := newChunkQueue(snapshot, dir)
require.NoError(t, err) require.NoError(t, err)


+ 3
- 3
internal/statesync/syncer_test.go View File

@ -503,7 +503,7 @@ func TestSyncer_applyChunks_Results(t *testing.T) {
rts := setup(ctx, t, nil, nil, stateProvider, 2) rts := setup(ctx, t, nil, nil, stateProvider, 2)
body := []byte{1, 2, 3} body := []byte{1, 2, 3}
chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 1}, "")
chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 1}, t.TempDir())
require.NoError(t, err) require.NoError(t, err)
fetchStartTime := time.Now() fetchStartTime := time.Now()
@ -562,7 +562,7 @@ func TestSyncer_applyChunks_RefetchChunks(t *testing.T) {
rts := setup(ctx, t, nil, nil, stateProvider, 2) rts := setup(ctx, t, nil, nil, stateProvider, 2)
chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 3}, "")
chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 3}, t.TempDir())
require.NoError(t, err) require.NoError(t, err)
fetchStartTime := time.Now() fetchStartTime := time.Now()
@ -660,7 +660,7 @@ func TestSyncer_applyChunks_RejectSenders(t *testing.T) {
_, err = rts.syncer.AddSnapshot(peerCID, s2) _, err = rts.syncer.AddSnapshot(peerCID, s2)
require.NoError(t, err) require.NoError(t, err)
chunks, err := newChunkQueue(s1, "")
chunks, err := newChunkQueue(s1, t.TempDir())
require.NoError(t, err) require.NoError(t, err)
fetchStartTime := time.Now() fetchStartTime := time.Now()


+ 12
- 8
internal/store/store_test.go View File

@ -46,8 +46,8 @@ func makeTestCommit(height int64, timestamp time.Time) *types.Commit {
commitSigs) commitSigs)
} }
func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFunc, error) {
cfg, err := config.ResetTestRoot("blockchain_reactor_test")
func makeStateAndBlockStore(dir string, logger log.Logger) (sm.State, *BlockStore, cleanupFunc, error) {
cfg, err := config.ResetTestRoot(dir, "blockchain_reactor_test")
if err != nil { if err != nil {
return sm.State{}, nil, nil, err return sm.State{}, nil, nil, err
} }
@ -75,10 +75,13 @@ var (
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
dir, err := os.MkdirTemp("", "store_test")
if err != nil {
stdlog.Fatal(err)
}
var cleanup cleanupFunc var cleanup cleanupFunc
var err error
state, _, cleanup, err = makeStateAndBlockStore(log.NewNopLogger())
state, _, cleanup, err = makeStateAndBlockStore(dir, log.NewNopLogger())
if err != nil { if err != nil {
stdlog.Fatal(err) stdlog.Fatal(err)
} }
@ -97,12 +100,13 @@ func TestMain(m *testing.M) {
seenCommit1 = makeTestCommit(10, tmtime.Now()) seenCommit1 = makeTestCommit(10, tmtime.Now())
code := m.Run() code := m.Run()
cleanup() cleanup()
os.RemoveAll(dir) // best-effort
os.Exit(code) os.Exit(code)
} }
// TODO: This test should be simplified ... // TODO: This test should be simplified ...
func TestBlockStoreSaveLoadBlock(t *testing.T) { func TestBlockStoreSaveLoadBlock(t *testing.T) {
state, bs, cleanup, err := makeStateAndBlockStore(log.NewNopLogger())
state, bs, cleanup, err := makeStateAndBlockStore(t.TempDir(), log.NewNopLogger())
defer cleanup() defer cleanup()
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, bs.Base(), int64(0), "initially the base should be zero") require.Equal(t, bs.Base(), int64(0), "initially the base should be zero")
@ -313,7 +317,7 @@ func TestBlockStoreSaveLoadBlock(t *testing.T) {
} }
func TestLoadBaseMeta(t *testing.T) { func TestLoadBaseMeta(t *testing.T) {
cfg, err := config.ResetTestRoot("blockchain_reactor_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "blockchain_reactor_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -373,7 +377,7 @@ func TestLoadBlockPart(t *testing.T) {
} }
func TestPruneBlocks(t *testing.T) { func TestPruneBlocks(t *testing.T) {
cfg, err := config.ResetTestRoot("blockchain_reactor_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "blockchain_reactor_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -494,7 +498,7 @@ func TestLoadBlockMeta(t *testing.T) {
} }
func TestBlockFetchAtHeight(t *testing.T) { func TestBlockFetchAtHeight(t *testing.T) {
state, bs, cleanup, err := makeStateAndBlockStore(log.NewNopLogger())
state, bs, cleanup, err := makeStateAndBlockStore(t.TempDir(), log.NewNopLogger())
defer cleanup() defer cleanup()
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, bs.Height(), int64(0), "initially the height should be zero") require.Equal(t, bs.Height(), int64(0), "initially the height should be zero")


+ 3
- 10
libs/cli/setup_test.go View File

@ -60,13 +60,6 @@ func TestSetupEnv(t *testing.T) {
} }
} }
func tempDir(t *testing.T) string {
t.Helper()
cdir, err := os.MkdirTemp("", "test-cli")
require.NoError(t, err)
return cdir
}
// writeConfigVals writes a toml file with the given values. // writeConfigVals writes a toml file with the given values.
// It returns an error if writing was impossible. // It returns an error if writing was impossible.
func writeConfigVals(dir string, vals map[string]string) error { func writeConfigVals(dir string, vals map[string]string) error {
@ -86,7 +79,7 @@ func TestSetupConfig(t *testing.T) {
// we pre-create two config files we can refer to in the rest of // we pre-create two config files we can refer to in the rest of
// the test cases. // the test cases.
cval1 := "fubble" cval1 := "fubble"
conf1 := tempDir(t)
conf1 := t.TempDir()
err := writeConfigVals(conf1, map[string]string{"boo": cval1}) err := writeConfigVals(conf1, map[string]string{"boo": cval1})
require.NoError(t, err) require.NoError(t, err)
@ -147,11 +140,11 @@ func TestSetupUnmarshal(t *testing.T) {
// we pre-create two config files we can refer to in the rest of // we pre-create two config files we can refer to in the rest of
// the test cases. // the test cases.
cval1, cval2 := "someone", "else" cval1, cval2 := "someone", "else"
conf1 := tempDir(t)
conf1 := t.TempDir()
err := writeConfigVals(conf1, map[string]string{"name": cval1}) err := writeConfigVals(conf1, map[string]string{"name": cval1})
require.NoError(t, err) require.NoError(t, err)
// even with some ignored fields, should be no problem // even with some ignored fields, should be no problem
conf2 := tempDir(t)
conf2 := t.TempDir()
err = writeConfigVals(conf2, map[string]string{"name": cval2, "foo": "bar"}) err = writeConfigVals(conf2, map[string]string{"name": cval2, "foo": "bar"})
require.NoError(t, err) require.NoError(t, err)


+ 4
- 10
libs/os/os_test.go View File

@ -12,7 +12,7 @@ import (
) )
func TestCopyFile(t *testing.T) { func TestCopyFile(t *testing.T) {
tmpfile, err := os.CreateTemp("", "example")
tmpfile, err := os.CreateTemp(t.TempDir(), "example")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -40,12 +40,10 @@ func TestCopyFile(t *testing.T) {
} }
func TestEnsureDir(t *testing.T) { func TestEnsureDir(t *testing.T) {
tmp, err := os.MkdirTemp("", "ensure-dir")
require.NoError(t, err)
defer os.RemoveAll(tmp)
tmp := t.TempDir()
// Should be possible to create a new directory. // Should be possible to create a new directory.
err = tmos.EnsureDir(filepath.Join(tmp, "dir"), 0755)
err := tmos.EnsureDir(filepath.Join(tmp, "dir"), 0755)
require.NoError(t, err) require.NoError(t, err)
require.DirExists(t, filepath.Join(tmp, "dir")) require.DirExists(t, filepath.Join(tmp, "dir"))
@ -76,11 +74,7 @@ func TestEnsureDir(t *testing.T) {
// the origin is positively a non-directory and that it is ready for copying. // the origin is positively a non-directory and that it is ready for copying.
// See https://github.com/tendermint/tendermint/issues/6427 // See https://github.com/tendermint/tendermint/issues/6427
func TestTrickedTruncation(t *testing.T) { func TestTrickedTruncation(t *testing.T) {
tmpDir, err := os.MkdirTemp(os.TempDir(), "pwn_truncate")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpDir)
tmpDir := t.TempDir()
originalWALPath := filepath.Join(tmpDir, "wal") originalWALPath := filepath.Join(tmpDir, "wal")
originalWALContent := []byte("I AM BECOME DEATH, DESTROYER OF ALL WORLDS!") originalWALContent := []byte("I AM BECOME DEATH, DESTROYER OF ALL WORLDS!")


+ 15
- 21
light/example_test.go View File

@ -2,8 +2,7 @@ package light_test
import ( import (
"context" "context"
stdlog "log"
"os"
"testing"
"time" "time"
dbm "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db"
@ -17,17 +16,17 @@ import (
) )
// Manually getting light blocks and verifying them. // Manually getting light blocks and verifying them.
func ExampleClient() {
func TestExampleClient(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
conf, err := rpctest.CreateConfig("ExampleClient_VerifyLightBlockAtHeight")
conf, err := rpctest.CreateConfig(t, "ExampleClient_VerifyLightBlockAtHeight")
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
logger, err := log.NewDefaultLogger(log.LogFormatPlain, log.LogLevelInfo) logger, err := log.NewDefaultLogger(log.LogFormatPlain, log.LogLevelInfo)
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
// Start a test application // Start a test application
@ -35,21 +34,16 @@ func ExampleClient() {
_, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout) _, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout)
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
defer func() { _ = closer(ctx) }() defer func() { _ = closer(ctx) }()
dbDir, err := os.MkdirTemp("", "light-client-example")
if err != nil {
stdlog.Fatal(err)
}
defer os.RemoveAll(dbDir)
dbDir := t.TempDir()
chainID := conf.ChainID() chainID := conf.ChainID()
primary, err := httpp.New(chainID, conf.RPC.ListenAddress) primary, err := httpp.New(chainID, conf.RPC.ListenAddress)
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
// give Tendermint time to generate some blocks // give Tendermint time to generate some blocks
@ -57,12 +51,12 @@ func ExampleClient() {
block, err := primary.LightBlock(ctx, 2) block, err := primary.LightBlock(ctx, 2)
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
db, err := dbm.NewGoLevelDB("light-client-db", dbDir) db, err := dbm.NewGoLevelDB("light-client-db", dbDir)
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
c, err := light.NewClient(ctx, c, err := light.NewClient(ctx,
@ -78,11 +72,11 @@ func ExampleClient() {
light.Logger(logger), light.Logger(logger),
) )
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
defer func() { defer func() {
if err := c.Cleanup(); err != nil { if err := c.Cleanup(); err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
}() }()
@ -92,19 +86,19 @@ func ExampleClient() {
// veify the block at height 3 // veify the block at height 3
_, err = c.VerifyLightBlockAtHeight(ctx, 3, time.Now()) _, err = c.VerifyLightBlockAtHeight(ctx, 3, time.Now())
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
// retrieve light block at height 3 // retrieve light block at height 3
_, err = c.TrustedLightBlock(3) _, err = c.TrustedLightBlock(3)
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
// update to the latest height // update to the latest height
lb, err := c.Update(ctx, time.Now()) lb, err := c.Update(ctx, time.Now())
if err != nil { if err != nil {
stdlog.Fatal(err)
t.Fatal(err)
} }
logger.Info("verified light block", "light-block", lb) logger.Info("verified light block", "light-block", lb)


+ 6
- 16
light/light_test.go View File

@ -2,7 +2,6 @@ package light_test
import ( import (
"context" "context"
"os"
"testing" "testing"
"time" "time"
@ -28,7 +27,7 @@ func TestClientIntegration_Update(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
conf, err := rpctest.CreateConfig(t.Name())
conf, err := rpctest.CreateConfig(t, t.Name())
require.NoError(t, err) require.NoError(t, err)
logger := log.NewTestingLogger(t) logger := log.NewTestingLogger(t)
@ -42,10 +41,7 @@ func TestClientIntegration_Update(t *testing.T) {
// give Tendermint time to generate some blocks // give Tendermint time to generate some blocks
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)
dbDir, err := os.MkdirTemp("", "light-client-test-update-example")
require.NoError(t, err)
defer os.RemoveAll(dbDir)
dbDir := t.TempDir()
chainID := conf.ChainID() chainID := conf.ChainID()
primary, err := httpp.New(chainID, conf.RPC.ListenAddress) primary, err := httpp.New(chainID, conf.RPC.ListenAddress)
@ -91,7 +87,7 @@ func TestClientIntegration_VerifyLightBlockAtHeight(t *testing.T) {
t.Parallel() t.Parallel()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
conf, err := rpctest.CreateConfig(t.Name())
conf, err := rpctest.CreateConfig(t, t.Name())
require.NoError(t, err) require.NoError(t, err)
logger := log.NewTestingLogger(t) logger := log.NewTestingLogger(t)
@ -103,10 +99,7 @@ func TestClientIntegration_VerifyLightBlockAtHeight(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
defer func() { require.NoError(t, closer(ctx)) }() defer func() { require.NoError(t, closer(ctx)) }()
dbDir, err := os.MkdirTemp("", "light-client-test-verify-example")
require.NoError(t, err)
defer os.RemoveAll(dbDir)
dbDir := t.TempDir()
chainID := conf.ChainID() chainID := conf.ChainID()
primary, err := httpp.New(chainID, conf.RPC.ListenAddress) primary, err := httpp.New(chainID, conf.RPC.ListenAddress)
@ -171,7 +164,7 @@ func waitForBlock(ctx context.Context, p provider.Provider, height int64) (*type
func TestClientStatusRPC(t *testing.T) { func TestClientStatusRPC(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
conf, err := rpctest.CreateConfig(t.Name())
conf, err := rpctest.CreateConfig(t, t.Name())
require.NoError(t, err) require.NoError(t, err)
// Start a test application // Start a test application
@ -181,10 +174,7 @@ func TestClientStatusRPC(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
defer func() { require.NoError(t, closer(ctx)) }() defer func() { require.NoError(t, closer(ctx)) }()
dbDir, err := os.MkdirTemp("", "light-client-test-status-example")
require.NoError(t, err)
t.Cleanup(func() { os.RemoveAll(dbDir) })
dbDir := t.TempDir()
chainID := conf.ChainID() chainID := conf.ChainID()
primary, err := httpp.New(chainID, conf.RPC.ListenAddress) primary, err := httpp.New(chainID, conf.RPC.ListenAddress)


+ 1
- 1
light/provider/http/http_test.go View File

@ -35,7 +35,7 @@ func TestNewProvider(t *testing.T) {
func TestProvider(t *testing.T) { func TestProvider(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := rpctest.CreateConfig(t.Name())
cfg, err := rpctest.CreateConfig(t, t.Name())
require.NoError(t, err) require.NoError(t, err)
// start a tendermint node in the background to test against // start a tendermint node in the background to test against


+ 12
- 12
node/node_test.go View File

@ -39,7 +39,7 @@ import (
) )
func TestNodeStartStop(t *testing.T) { func TestNodeStartStop(t *testing.T) {
cfg, err := config.ResetTestRoot("node_node_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_node_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -104,7 +104,7 @@ func getTestNode(ctx context.Context, t *testing.T, conf *config.Config, logger
} }
func TestNodeDelayedStart(t *testing.T) { func TestNodeDelayedStart(t *testing.T) {
cfg, err := config.ResetTestRoot("node_delayed_start_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_delayed_start_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -126,7 +126,7 @@ func TestNodeDelayedStart(t *testing.T) {
} }
func TestNodeSetAppVersion(t *testing.T) { func TestNodeSetAppVersion(t *testing.T) {
cfg, err := config.ResetTestRoot("node_app_version_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_app_version_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -159,7 +159,7 @@ func TestNodeSetPrivValTCP(t *testing.T) {
logger := log.NewNopLogger() logger := log.NewNopLogger()
cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_priv_val_tcp_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
cfg.PrivValidator.ListenAddr = addr cfg.PrivValidator.ListenAddr = addr
@ -196,7 +196,7 @@ func TestPrivValidatorListenAddrNoProtocol(t *testing.T) {
addrNoPrefix := testFreeAddr(t) addrNoPrefix := testFreeAddr(t)
cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_priv_val_tcp_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
cfg.PrivValidator.ListenAddr = addrNoPrefix cfg.PrivValidator.ListenAddr = addrNoPrefix
@ -220,7 +220,7 @@ func TestNodeSetPrivValIPC(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_priv_val_tcp_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
cfg.PrivValidator.ListenAddr = "unix://" + tmpfile cfg.PrivValidator.ListenAddr = "unix://" + tmpfile
@ -267,7 +267,7 @@ func TestCreateProposalBlock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("node_create_proposal")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_create_proposal")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -364,7 +364,7 @@ func TestMaxTxsProposalBlockSize(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("node_create_proposal")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_create_proposal")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -432,7 +432,7 @@ func TestMaxProposalBlockSize(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
cfg, err := config.ResetTestRoot("node_create_proposal")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_create_proposal")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -547,7 +547,7 @@ func TestMaxProposalBlockSize(t *testing.T) {
} }
func TestNodeNewSeedNode(t *testing.T) { func TestNodeNewSeedNode(t *testing.T) {
cfg, err := config.ResetTestRoot("node_new_node_custom_reactors_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_new_node_custom_reactors_test")
require.NoError(t, err) require.NoError(t, err)
cfg.Mode = config.ModeSeed cfg.Mode = config.ModeSeed
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -585,7 +585,7 @@ func TestNodeNewSeedNode(t *testing.T) {
} }
func TestNodeSetEventSink(t *testing.T) { func TestNodeSetEventSink(t *testing.T) {
cfg, err := config.ResetTestRoot("node_app_version_test")
cfg, err := config.ResetTestRoot(t.TempDir(), "node_app_version_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir) defer os.RemoveAll(cfg.RootDir)
@ -725,7 +725,7 @@ func loadStatefromGenesis(ctx context.Context, t *testing.T) sm.State {
stateDB := dbm.NewMemDB() stateDB := dbm.NewMemDB()
stateStore := sm.NewStore(stateDB) stateStore := sm.NewStore(stateDB)
cfg, err := config.ResetTestRoot("load_state_from_genesis")
cfg, err := config.ResetTestRoot(t.TempDir(), "load_state_from_genesis")
require.NoError(t, err) require.NoError(t, err)
loadedState, err := stateStore.Load() loadedState, err := stateStore.Load()


+ 12
- 12
privval/file_test.go View File

@ -21,9 +21,9 @@ import (
) )
func TestGenLoadValidator(t *testing.T) { func TestGenLoadValidator(t *testing.T) {
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_")
require.NoError(t, err) require.NoError(t, err)
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_")
require.NoError(t, err) require.NoError(t, err)
privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
@ -44,9 +44,9 @@ func TestResetValidator(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_")
require.NoError(t, err) require.NoError(t, err)
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_")
require.NoError(t, err) require.NoError(t, err)
privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
@ -74,9 +74,9 @@ func TestResetValidator(t *testing.T) {
} }
func TestLoadOrGenValidator(t *testing.T) { func TestLoadOrGenValidator(t *testing.T) {
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_")
require.NoError(t, err) require.NoError(t, err)
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_")
require.NoError(t, err) require.NoError(t, err)
tempKeyFilePath := tempKeyFile.Name() tempKeyFilePath := tempKeyFile.Name()
@ -160,9 +160,9 @@ func TestSignVote(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_")
require.NoError(t, err) require.NoError(t, err)
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_")
require.NoError(t, err) require.NoError(t, err)
privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
@ -215,9 +215,9 @@ func TestSignProposal(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_")
require.NoError(t, err) require.NoError(t, err)
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_")
require.NoError(t, err) require.NoError(t, err)
privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
@ -263,9 +263,9 @@ func TestDifferByTimestamp(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempKeyFile, err := os.CreateTemp("", "priv_validator_key_")
tempKeyFile, err := os.CreateTemp(t.TempDir(), "priv_validator_key_")
require.NoError(t, err) require.NoError(t, err)
tempStateFile, err := os.CreateTemp("", "priv_validator_state_")
tempStateFile, err := os.CreateTemp(t.TempDir(), "priv_validator_state_")
require.NoError(t, err) require.NoError(t, err)
privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "") privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")


+ 1
- 1
privval/socket_dialers_test.go View File

@ -23,7 +23,7 @@ func getFreeLocalhostAddrPort(t *testing.T) string {
func getDialerTestCases(t *testing.T) []dialerTestCase { func getDialerTestCases(t *testing.T) []dialerTestCase {
tcpAddr := getFreeLocalhostAddrPort(t) tcpAddr := getFreeLocalhostAddrPort(t)
unixFilePath, err := testUnixAddr()
unixFilePath, err := testUnixAddr(t)
require.NoError(t, err) require.NoError(t, err)
unixAddr := fmt.Sprintf("unix://%s", unixFilePath) unixAddr := fmt.Sprintf("unix://%s", unixFilePath)


+ 7
- 4
privval/socket_listeners_test.go View File

@ -28,14 +28,17 @@ type listenerTestCase struct {
// testUnixAddr will attempt to obtain a platform-independent temporary file // testUnixAddr will attempt to obtain a platform-independent temporary file
// name for a Unix socket // name for a Unix socket
func testUnixAddr() (string, error) {
f, err := os.CreateTemp("", "tendermint-privval-test-*")
func testUnixAddr(t *testing.T) (string, error) {
// N.B. We can't use t.TempDir here because socket filenames have a
// restrictive length limit (~100 bytes) for silly historical reasons.
f, err := os.CreateTemp("", "tendermint-privval-test-*.sock")
if err != nil { if err != nil {
return "", err return "", err
} }
addr := f.Name() addr := f.Name()
f.Close() f.Close()
os.Remove(addr)
os.Remove(addr) // remove so the test can bind it
t.Cleanup(func() { os.Remove(addr) }) // clean up after the test
return addr, nil return addr, nil
} }
@ -56,7 +59,7 @@ func tcpListenerTestCase(t *testing.T, timeoutAccept, timeoutReadWrite time.Dura
} }
func unixListenerTestCase(t *testing.T, timeoutAccept, timeoutReadWrite time.Duration) listenerTestCase { func unixListenerTestCase(t *testing.T, timeoutAccept, timeoutReadWrite time.Duration) listenerTestCase {
addr, err := testUnixAddr()
addr, err := testUnixAddr(t)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }


+ 2
- 2
rpc/client/examples_test.go View File

@ -22,7 +22,7 @@ func TestHTTPSimple(t *testing.T) {
// Start a tendermint node (and kvstore) in the background to test against // Start a tendermint node (and kvstore) in the background to test against
app := kvstore.NewApplication() app := kvstore.NewApplication()
conf, err := rpctest.CreateConfig("ExampleHTTP_simple")
conf, err := rpctest.CreateConfig(t, "ExampleHTTP_simple")
require.NoError(t, err) require.NoError(t, err)
_, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout) _, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout)
@ -72,7 +72,7 @@ func TestHTTPBatching(t *testing.T) {
// Start a tendermint node (and kvstore) in the background to test against // Start a tendermint node (and kvstore) in the background to test against
app := kvstore.NewApplication() app := kvstore.NewApplication()
conf, err := rpctest.CreateConfig("ExampleHTTP_batching")
conf, err := rpctest.CreateConfig(t, "ExampleHTTP_batching")
require.NoError(t, err) require.NoError(t, err)
_, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout) _, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout)


+ 2
- 5
rpc/client/main_test.go View File

@ -2,7 +2,6 @@ package client_test
import ( import (
"context" "context"
"fmt"
"os" "os"
"testing" "testing"
@ -20,13 +19,11 @@ func NodeSuite(t *testing.T, logger log.Logger) (service.Service, *config.Config
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
conf, err := rpctest.CreateConfig(t.Name())
conf, err := rpctest.CreateConfig(t, t.Name())
require.NoError(t, err) require.NoError(t, err)
// start a tendermint node in the background to test against // start a tendermint node in the background to test against
dir, err := os.MkdirTemp("/tmp", fmt.Sprint("rpc-client-test-", t.Name()))
require.NoError(t, err)
dir := t.TempDir()
app := kvstore.NewPersistentKVStoreApplication(logger, dir) app := kvstore.NewPersistentKVStoreApplication(logger, dir)
node, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout) node, closer, err := rpctest.StartTendermint(ctx, conf, app, rpctest.SuppressStdout)


+ 3
- 2
rpc/test/helpers.go View File

@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"os" "os"
"testing"
"time" "time"
abciclient "github.com/tendermint/tendermint/abci/client" abciclient "github.com/tendermint/tendermint/abci/client"
@ -57,8 +58,8 @@ func makeAddrs() (p2pAddr, rpcAddr string) {
return fmt.Sprintf(addrTemplate, randPort()), fmt.Sprintf(addrTemplate, randPort()) return fmt.Sprintf(addrTemplate, randPort()), fmt.Sprintf(addrTemplate, randPort())
} }
func CreateConfig(testName string) (*config.Config, error) {
c, err := config.ResetTestRoot(testName)
func CreateConfig(t *testing.T, testName string) (*config.Config, error) {
c, err := config.ResetTestRoot(t.TempDir(), testName)
if err != nil { if err != nil {
return nil, err return nil, err
} }


+ 1
- 1
types/genesis_test.go View File

@ -126,7 +126,7 @@ func TestBasicGenesisDoc(t *testing.T) {
} }
func TestGenesisSaveAs(t *testing.T) { func TestGenesisSaveAs(t *testing.T) {
tmpfile, err := os.CreateTemp("", "genesis")
tmpfile, err := os.CreateTemp(t.TempDir(), "genesis")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpfile.Name()) defer os.Remove(tmpfile.Name())


Loading…
Cancel
Save