From 9d53f9bc6f78752c61d78b2e0bd127f10b55a691 Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Wed, 8 Jan 2025 19:07:48 +0800 Subject: [PATCH] all: use T.TempDir to create temporary test directories (#24633) --- accounts/abi/bind/backends/simulated.go | 8 +--- accounts/abi/bind/bind_test.go | 8 +--- accounts/keystore/account_cache_test.go | 1 - accounts/keystore/keystore_test.go | 39 ++++++------------- accounts/keystore/plain_test.go | 16 ++------ cmd/XDC/accountcmd_test.go | 8 ++-- cmd/XDC/consolecmd_test.go | 13 ++----- cmd/XDC/dao_test.go | 3 +- cmd/XDC/run_test.go | 17 +------- cmd/ethkey/message_test.go | 7 +--- cmd/utils/flags_test.go | 15 ++----- .../XDPoS/engines/engine_v2/forensics_test.go | 8 +--- .../XDPoS/engines/engine_v2/snapshot_test.go | 6 +-- consensus/ethash/algorithm_test.go | 2 + consensus/ethash/ethash_test.go | 2 + consensus/tests/engine_v2_tests/helper.go | 8 +--- console/console_test.go | 5 +-- core/bench_test.go | 18 ++------- eth/filters/filter_test.go | 16 ++------ internal/guide/guide_test.go | 7 +--- internal/jsre/jsre_test.go | 18 +++------ node/config_test.go | 17 +++----- node/node_test.go | 7 +--- node/service_test.go | 6 +-- p2p/discover/database_test.go | 7 +--- p2p/discv5/database_test.go | 7 +--- trie/trie_test.go | 11 ++---- 27 files changed, 73 insertions(+), 207 deletions(-) diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 7d8e26a33f0c6..092fa6e13be8d 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -86,13 +86,9 @@ func SimulateWalletAddressAndSignFn() (common.Address, func(account accounts.Acc veryLightScryptN := 2 veryLightScryptP := 1 dir, _ := os.MkdirTemp("", "eth-SimulateWalletAddressAndSignFn-test") - - new := func(kd string) *keystore.KeyStore { - return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP) - } - defer os.RemoveAll(dir) - ks := new(dir) + + ks := keystore.NewKeyStore(dir, veryLightScryptN, veryLightScryptP) pass := "" // not used but required by API a1, err := ks.NewAccount(pass) if err != nil { diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index 8393ada957d07..a2ce6b8f4d6ba 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -1919,14 +1919,10 @@ func TestGolangBindings(t *testing.T) { } t.Log("Using config", params.TestXDPoSMockChainConfig) // Create a temporary workspace for the test suite - ws, err := os.MkdirTemp("", "binding-test") - if err != nil { - t.Fatalf("failed to create temporary workspace: %v", err) - } - // defer os.RemoveAll(ws) + ws := t.TempDir() pkg := filepath.Join(ws, "bindtest") - if err = os.MkdirAll(pkg, 0700); err != nil { + if err := os.MkdirAll(pkg, 0700); err != nil { t.Fatalf("failed to create package: %v", err) } // Generate the test suite for all the contracts diff --git a/accounts/keystore/account_cache_test.go b/accounts/keystore/account_cache_test.go index 92b26f71bc3ab..6416aa0435156 100644 --- a/accounts/keystore/account_cache_test.go +++ b/accounts/keystore/account_cache_test.go @@ -55,7 +55,6 @@ func TestWatchNewFile(t *testing.T) { t.Parallel() dir, ks := tmpKeyStore(t, false) - defer os.RemoveAll(dir) // Ensure the watcher is started before adding any files. ks.Accounts() diff --git a/accounts/keystore/keystore_test.go b/accounts/keystore/keystore_test.go index 75af63ff77012..82d576e521742 100644 --- a/accounts/keystore/keystore_test.go +++ b/accounts/keystore/keystore_test.go @@ -37,7 +37,6 @@ var testSigData = make([]byte, 32) func TestKeyStore(t *testing.T) { dir, ks := tmpKeyStore(t, true) - defer os.RemoveAll(dir) a, err := ks.NewAccount("foo") if err != nil { @@ -71,8 +70,7 @@ func TestKeyStore(t *testing.T) { } func TestSign(t *testing.T) { - dir, ks := tmpKeyStore(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, true) pass := "" // not used but required by API a1, err := ks.NewAccount(pass) @@ -88,8 +86,7 @@ func TestSign(t *testing.T) { } func TestSignWithPassphrase(t *testing.T) { - dir, ks := tmpKeyStore(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, true) pass := "passwd" acc, err := ks.NewAccount(pass) @@ -116,8 +113,7 @@ func TestSignWithPassphrase(t *testing.T) { } func TestTimedUnlock(t *testing.T) { - dir, ks := tmpKeyStore(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, true) pass := "foo" a1, err := ks.NewAccount(pass) @@ -151,8 +147,7 @@ func TestTimedUnlock(t *testing.T) { } func TestOverrideUnlock(t *testing.T) { - dir, ks := tmpKeyStore(t, false) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, false) pass := "foo" a1, err := ks.NewAccount(pass) @@ -192,8 +187,7 @@ func TestOverrideUnlock(t *testing.T) { // This test should fail under -race if signing races the expiration goroutine. func TestSignRace(t *testing.T) { - dir, ks := tmpKeyStore(t, false) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, false) // Create a test account. a1, err := ks.NewAccount("") @@ -221,8 +215,7 @@ func TestSignRace(t *testing.T) { // addition and removal of wallet event subscriptions. func TestWalletNotifierLifecycle(t *testing.T) { // Create a temporary kesytore to test with - dir, ks := tmpKeyStore(t, false) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, false) // Ensure that the notification updater is not running yet time.Sleep(250 * time.Millisecond) @@ -282,8 +275,7 @@ type walletEvent struct { // Tests that wallet notifications and correctly fired when accounts are added // or deleted from the keystore. func TestWalletNotifications(t *testing.T) { - dir, ks := tmpKeyStore(t, false) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, false) // Subscribe to the wallet feed and collect events. var ( @@ -344,8 +336,7 @@ func TestWalletNotifications(t *testing.T) { // TestImportECDSA tests the import functionality of a keystore. func TestImportECDSA(t *testing.T) { - dir, ks := tmpKeyStore(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, true) key, err := crypto.GenerateKey() if err != nil { t.Fatalf("failed to generate key: %v", key) @@ -363,8 +354,7 @@ func TestImportECDSA(t *testing.T) { // TestImportExport tests the import and export functionality of a keystore. func TestImportExport(t *testing.T) { - dir, ks := tmpKeyStore(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, true) acc, err := ks.NewAccount("old") if err != nil { t.Fatalf("failed to create account: %v", acc) @@ -394,8 +384,7 @@ func TestImportExport(t *testing.T) { // TestImportRace tests the keystore on races. // This test should fail under -race if importing races. func TestImportRace(t *testing.T) { - dir, ks := tmpKeyStore(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStore(t, true) acc, err := ks.NewAccount("old") if err != nil { t.Fatalf("failed to create account: %v", acc) @@ -404,8 +393,7 @@ func TestImportRace(t *testing.T) { if err != nil { t.Fatalf("failed to export account: %v", acc) } - dir2, ks2 := tmpKeyStore(t, true) - defer os.RemoveAll(dir2) + _, ks2 := tmpKeyStore(t, true) var atom uint32 var wg sync.WaitGroup wg.Add(2) @@ -461,10 +449,7 @@ func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) { } func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) { - d, err := os.MkdirTemp("", "eth-keystore-test") - if err != nil { - t.Fatal(err) - } + d := t.TempDir() newKs := NewPlaintextKeyStore if encrypted { newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) } diff --git a/accounts/keystore/plain_test.go b/accounts/keystore/plain_test.go index 180851e399b13..1f7369519afa7 100644 --- a/accounts/keystore/plain_test.go +++ b/accounts/keystore/plain_test.go @@ -20,7 +20,6 @@ import ( "crypto/rand" "encoding/hex" "fmt" - "os" "path/filepath" "reflect" "strings" @@ -31,10 +30,7 @@ import ( ) func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) { - d, err := os.MkdirTemp("", "geth-keystore-test") - if err != nil { - t.Fatal(err) - } + d := t.TempDir() if encrypted { ks = &keyStorePassphrase{d, veryLightScryptN, veryLightScryptP, true} } else { @@ -44,8 +40,7 @@ func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) { } func TestKeyStorePlain(t *testing.T) { - dir, ks := tmpKeyStoreIface(t, false) - defer os.RemoveAll(dir) + _, ks := tmpKeyStoreIface(t, false) pass := "" // not used but required by API k1, account, err := storeNewKey(ks, rand.Reader, pass) @@ -65,8 +60,7 @@ func TestKeyStorePlain(t *testing.T) { } func TestKeyStorePassphrase(t *testing.T) { - dir, ks := tmpKeyStoreIface(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStoreIface(t, true) pass := "foo" k1, account, err := storeNewKey(ks, rand.Reader, pass) @@ -86,8 +80,7 @@ func TestKeyStorePassphrase(t *testing.T) { } func TestKeyStorePassphraseDecryptionFail(t *testing.T) { - dir, ks := tmpKeyStoreIface(t, true) - defer os.RemoveAll(dir) + _, ks := tmpKeyStoreIface(t, true) pass := "foo" k1, account, err := storeNewKey(ks, rand.Reader, pass) @@ -101,7 +94,6 @@ func TestKeyStorePassphraseDecryptionFail(t *testing.T) { func TestImportPreSaleKey(t *testing.T) { dir, ks := tmpKeyStoreIface(t, true) - defer os.RemoveAll(dir) // file content of a presale key file generated with: // python pyethsaletool.py genwallet diff --git a/cmd/XDC/accountcmd_test.go b/cmd/XDC/accountcmd_test.go index 2afb457699235..5c102e8673031 100644 --- a/cmd/XDC/accountcmd_test.go +++ b/cmd/XDC/accountcmd_test.go @@ -33,7 +33,7 @@ import ( // are copied into a temporary keystore directory. func tmpDatadirWithKeystore(t *testing.T) string { - datadir := tmpdir(t) + datadir := t.TempDir() keystore := filepath.Join(datadir, "keystore") source := filepath.Join("..", "..", "accounts", "keystore", "testdata", "keystore") if err := cp.CopyAll(keystore, source); err != nil { @@ -43,8 +43,7 @@ func tmpDatadirWithKeystore(t *testing.T) string { } func TestAccountListEmpty(t *testing.T) { - datadir := tmpdir(t) - defer os.RemoveAll(datadir) + datadir := t.TempDir() XDC := runXDC(t, "account", "list", "--datadir", datadir) XDC.ExpectExit() } @@ -144,8 +143,7 @@ Repeat passphrase: {{.InputLine "foobar2"}} } func TestWalletImport(t *testing.T) { - datadir := tmpdir(t) - defer os.RemoveAll(datadir) + datadir := t.TempDir() XDC := runXDC(t, "wallet", "import", "--datadir", datadir, "--lightkdf", "testdata/guswallet.json") defer XDC.ExpectExit() XDC.Expect(` diff --git a/cmd/XDC/consolecmd_test.go b/cmd/XDC/consolecmd_test.go index 23988bc2c2836..8698d4e96cacf 100644 --- a/cmd/XDC/consolecmd_test.go +++ b/cmd/XDC/consolecmd_test.go @@ -19,7 +19,6 @@ package main import ( "crypto/rand" "math/big" - "os" "path/filepath" "runtime" "strconv" @@ -39,8 +38,7 @@ const ( // then terminated by closing the input stream. func TestConsoleWelcome(t *testing.T) { coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" - datadir := tmpdir(t) - defer os.RemoveAll(datadir) + datadir := t.TempDir() // Start a XDC console, make sure it's cleaned up and terminate the console XDC := runXDC(t, @@ -77,8 +75,7 @@ at block: 0 ({{niltime}}) func TestIPCAttachWelcome(t *testing.T) { // Configure the instance for IPC attachement coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" - datadir := tmpdir(t) - defer os.RemoveAll(datadir) + datadir := t.TempDir() var ipc string if runtime.GOOS == "windows" { ipc = `\\.\pipe\XDC` + strconv.Itoa(trulyRandInt(100000, 999999)) @@ -100,8 +97,7 @@ func TestIPCAttachWelcome(t *testing.T) { func TestHTTPAttachWelcome(t *testing.T) { coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" port := strconv.Itoa(trulyRandInt(1024, 65536)) // Yeah, sometimes this will fail, sorry :P - datadir := tmpdir(t) - defer os.RemoveAll(datadir) + datadir := t.TempDir() XDC := runXDC(t, "--datadir", datadir, "--XDCx-datadir", datadir+"/XDCx/"+time.Now().String(), "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", @@ -117,8 +113,7 @@ func TestHTTPAttachWelcome(t *testing.T) { func TestWSAttachWelcome(t *testing.T) { coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" port := strconv.Itoa(trulyRandInt(1024, 65536)) // Yeah, sometimes this will fail, sorry :P - datadir := tmpdir(t) - defer os.RemoveAll(datadir) + datadir := t.TempDir() XDC := runXDC(t, "--datadir", datadir, "--XDCx-datadir", datadir+"/XDCx/"+time.Now().String(), "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", diff --git a/cmd/XDC/dao_test.go b/cmd/XDC/dao_test.go index 5444a4b13761e..7b5a4efe0daa2 100644 --- a/cmd/XDC/dao_test.go +++ b/cmd/XDC/dao_test.go @@ -102,8 +102,7 @@ func TestDAOForkBlockNewChain(t *testing.T) { func testDAOForkBlockNewChain(t *testing.T, test int, genesis string, expectBlock *big.Int, expectVote bool) { // Create a temporary data directory to use and inspect later - datadir := tmpdir(t) - defer os.RemoveAll(datadir) + datadir := t.TempDir() // Start a XDC instance with the requested flags set and immediately terminate if genesis != "" { diff --git a/cmd/XDC/run_test.go b/cmd/XDC/run_test.go index 98f6092fed320..10f3f85c7ab2f 100644 --- a/cmd/XDC/run_test.go +++ b/cmd/XDC/run_test.go @@ -25,14 +25,6 @@ import ( "github.com/docker/docker/pkg/reexec" ) -func tmpdir(t *testing.T) string { - dir, err := os.MkdirTemp("", "XDC-test") - if err != nil { - t.Fatal(err) - } - return dir -} - type testXDC struct { *cmdtest.TestCmd @@ -78,15 +70,10 @@ func runXDC(t *testing.T, args ...string) *testXDC { } } if tt.Datadir == "" { - tt.Datadir = tmpdir(t) + // The temporary datadir will be removed automatically if something fails below. + tt.Datadir = t.TempDir() tt.Cleanup = func() { os.RemoveAll(tt.Datadir) } args = append([]string{"--datadir", tt.Datadir}, args...) - // Remove the temporary datadir if something fails below. - defer func() { - if t.Failed() { - tt.Cleanup() - } - }() } // Boot "XDC". This actually runs the test binary but the TestMain diff --git a/cmd/ethkey/message_test.go b/cmd/ethkey/message_test.go index 28a74de98a09f..c06cf1ffad8b7 100644 --- a/cmd/ethkey/message_test.go +++ b/cmd/ethkey/message_test.go @@ -17,17 +17,12 @@ package main import ( - "os" "path/filepath" "testing" ) func TestMessageSignVerify(t *testing.T) { - tmpdir, err := os.MkdirTemp("", "ethkey-test") - if err != nil { - t.Fatal("Can't create temporary directory:", err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() keyfile := filepath.Join(tmpdir, "the-keyfile") message := "test message" diff --git a/cmd/utils/flags_test.go b/cmd/utils/flags_test.go index 728cbb7070143..52712f0361326 100644 --- a/cmd/utils/flags_test.go +++ b/cmd/utils/flags_test.go @@ -73,13 +73,10 @@ func TestWalkMatch(t *testing.T) { root string pattern string } - dir, err := os.Getwd() - if err != nil { - log.Fatal(err) - } - test1Dir, _ := os.MkdirTemp(dir, "test1") - test2Dir, _ := os.MkdirTemp(dir, "test2") - err = os.WriteFile(filepath.Join(test1Dir, "test1.ldb"), []byte("hello"), os.ModePerm) + test1Dir := t.TempDir() + test2Dir := t.TempDir() + + err := os.WriteFile(filepath.Join(test1Dir, "test1.ldb"), []byte("hello"), os.ModePerm) if err != nil { log.Fatal(err) } @@ -87,10 +84,6 @@ func TestWalkMatch(t *testing.T) { if err != nil { log.Fatal(err) } - defer func() { - os.RemoveAll(test1Dir) - os.RemoveAll(test2Dir) - }() tests := []struct { name string diff --git a/consensus/XDPoS/engines/engine_v2/forensics_test.go b/consensus/XDPoS/engines/engine_v2/forensics_test.go index 3b6dc1b252d22..3cd6e25984de3 100644 --- a/consensus/XDPoS/engines/engine_v2/forensics_test.go +++ b/consensus/XDPoS/engines/engine_v2/forensics_test.go @@ -48,13 +48,9 @@ func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account acco veryLightScryptN := 2 veryLightScryptP := 1 dir, _ := os.MkdirTemp("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5))) - - new := func(kd string) *keystore.KeyStore { - return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP) - } - defer os.RemoveAll(dir) - ks := new(dir) + + ks := keystore.NewKeyStore(dir, veryLightScryptN, veryLightScryptP) pass := "" // not used but required by API a1, err := ks.ImportECDSA(pk, pass) if err != nil { diff --git a/consensus/XDPoS/engines/engine_v2/snapshot_test.go b/consensus/XDPoS/engines/engine_v2/snapshot_test.go index f70dcfb9f2b2b..a76c7697e1dcc 100644 --- a/consensus/XDPoS/engines/engine_v2/snapshot_test.go +++ b/consensus/XDPoS/engines/engine_v2/snapshot_test.go @@ -2,7 +2,6 @@ package engine_v2 import ( "fmt" - "os" "testing" "github.com/XinFinOrg/XDPoSChain/common" @@ -24,10 +23,7 @@ func TestGetMasterNodes(t *testing.T) { func TestStoreLoadSnapshot(t *testing.T) { snap := newSnapshot(1, common.Hash{0x1}, nil) - dir, err := os.MkdirTemp("", "snapshot-test") - if err != nil { - panic(fmt.Sprintf("can't create temporary directory: %v", err)) - } + dir := t.TempDir() db, err := leveldb.New(dir, 256, 0, "") if err != nil { panic(fmt.Sprintf("can't create temporary database: %v", err)) diff --git a/consensus/ethash/algorithm_test.go b/consensus/ethash/algorithm_test.go index 6a9d8809ad682..40524a81e4237 100644 --- a/consensus/ethash/algorithm_test.go +++ b/consensus/ethash/algorithm_test.go @@ -687,6 +687,8 @@ func TestHashimoto(t *testing.T) { // Tests that caches generated on disk may be done concurrently. func TestConcurrentDiskCacheGeneration(t *testing.T) { // Create a temp folder to generate the caches into + // TODO: t.TempDir fails to remove the directory on Windows + // \AppData\Local\Temp\1\TestConcurrentDiskCacheGeneration2382060137\001\cache-R23-1dca8a85e74aa763: Access is denied. cachedir, err := os.MkdirTemp("", "") if err != nil { t.Fatalf("Failed to create temporary cache dir: %v", err) diff --git a/consensus/ethash/ethash_test.go b/consensus/ethash/ethash_test.go index 5b13473cf30d3..c6d319ba7c72b 100644 --- a/consensus/ethash/ethash_test.go +++ b/consensus/ethash/ethash_test.go @@ -45,6 +45,8 @@ func TestTestMode(t *testing.T) { // This test checks that cache lru logic doesn't crash under load. // It reproduces https://github.com/XinFinOrg/XDPoSChain/issues/14943 func TestCacheFileEvict(t *testing.T) { + // TODO: t.TempDir fails to remove the directory on Windows + // \AppData\Local\Temp\1\TestCacheFileEvict2179435125\001\cache-R23-0000000000000000: Access is denied. tmpdir, err := os.MkdirTemp("", "ethash-test") if err != nil { t.Fatal(err) diff --git a/consensus/tests/engine_v2_tests/helper.go b/consensus/tests/engine_v2_tests/helper.go index c13b289b34c83..01a607b0331f9 100644 --- a/consensus/tests/engine_v2_tests/helper.go +++ b/consensus/tests/engine_v2_tests/helper.go @@ -77,13 +77,9 @@ func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account acco veryLightScryptN := 2 veryLightScryptP := 1 dir, _ := os.MkdirTemp("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5))) - - new := func(kd string) *keystore.KeyStore { - return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP) - } - defer os.RemoveAll(dir) - ks := new(dir) + + ks := keystore.NewKeyStore(dir, veryLightScryptN, veryLightScryptP) pass := "" // not used but required by API a1, err := ks.ImportECDSA(pk, pass) if err != nil { diff --git a/console/console_test.go b/console/console_test.go index 0d5c94a754972..2f5cfd5c54a18 100644 --- a/console/console_test.go +++ b/console/console_test.go @@ -87,10 +87,7 @@ type tester struct { // Please ensure you call Close() on the returned tester to avoid leaks. func newTester(t *testing.T, confOverride func(*ethconfig.Config)) *tester { // Create a temporary storage for the node keys and initialize it - workspace, err := os.MkdirTemp("", "console-tester-") - if err != nil { - t.Fatalf("failed to create temporary keystore: %v", err) - } + workspace := t.TempDir() // Create a networkless protocol stack and start an Ethereum service within stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance}) diff --git a/core/bench_test.go b/core/bench_test.go index 0d797dbea5a4f..e65e38ec0dea7 100644 --- a/core/bench_test.go +++ b/core/bench_test.go @@ -148,14 +148,11 @@ func genUncles(i int, gen *BlockGen) { func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) { // Create the database in memory or in a temporary directory. var db ethdb.Database + var err error if !disk { db = rawdb.NewMemoryDatabase() } else { - dir, err := os.MkdirTemp("", "eth-core-bench") - if err != nil { - b.Fatalf("cannot create temporary directory: %v", err) - } - defer os.RemoveAll(dir) + dir := b.TempDir() db, err = rawdb.NewLevelDBDatabase(dir, 128, 128, "") if err != nil { b.Fatalf("cannot create temporary database: %v", err) @@ -250,10 +247,7 @@ func makeChainForBench(db ethdb.Database, full bool, count uint64) { func benchWriteChain(b *testing.B, full bool, count uint64) { for i := 0; i < b.N; i++ { - dir, err := os.MkdirTemp("", "eth-chain-bench") - if err != nil { - b.Fatalf("cannot create temporary directory: %v", err) - } + dir := b.TempDir() db, err := rawdb.NewLevelDBDatabase(dir, 128, 1024, "") if err != nil { b.Fatalf("error opening database at %v: %v", dir, err) @@ -265,11 +259,7 @@ func benchWriteChain(b *testing.B, full bool, count uint64) { } func benchReadChain(b *testing.B, full bool, count uint64) { - dir, err := os.MkdirTemp("", "eth-chain-bench") - if err != nil { - b.Fatalf("cannot create temporary directory: %v", err) - } - defer os.RemoveAll(dir) + dir := b.TempDir() db, err := rawdb.NewLevelDBDatabase(dir, 128, 1024, "") if err != nil { diff --git a/eth/filters/filter_test.go b/eth/filters/filter_test.go index 489917d17c2be..09c9f35f8ce87 100644 --- a/eth/filters/filter_test.go +++ b/eth/filters/filter_test.go @@ -19,14 +19,12 @@ package filters import ( "context" "math/big" - "os" "testing" - "github.com/XinFinOrg/XDPoSChain/core/rawdb" - "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/consensus/ethash" "github.com/XinFinOrg/XDPoSChain/core" + "github.com/XinFinOrg/XDPoSChain/core/rawdb" "github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/params" @@ -42,11 +40,7 @@ func makeReceipt(addr common.Address) *types.Receipt { } func BenchmarkFilters(b *testing.B) { - dir, err := os.MkdirTemp("", "filtertest") - if err != nil { - b.Fatal(err) - } - defer os.RemoveAll(dir) + dir := b.TempDir() var ( db, _ = rawdb.NewLevelDBDatabase(dir, 0, 0, "") @@ -98,11 +92,7 @@ func BenchmarkFilters(b *testing.B) { } func TestFilters(t *testing.T) { - dir, err := os.MkdirTemp("", "filtertest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() var ( db, _ = rawdb.NewLevelDBDatabase(dir, 0, 0, "") diff --git a/internal/guide/guide_test.go b/internal/guide/guide_test.go index 64b9e162fae29..1b608e90cb14c 100644 --- a/internal/guide/guide_test.go +++ b/internal/guide/guide_test.go @@ -24,7 +24,6 @@ package guide import ( "math/big" - "os" "path/filepath" "testing" "time" @@ -37,11 +36,7 @@ import ( // Tests that the account management snippets work correctly. func TestAccountManagement(t *testing.T) { // Create a temporary folder to work with - workdir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatalf("Failed to create temporary work dir: %v", err) - } - defer os.RemoveAll(workdir) + workdir := t.TempDir() // Create an encrypted keystore with standard crypto parameters ks := keystore.NewKeyStore(filepath.Join(workdir, "keystore"), keystore.StandardScryptN, keystore.StandardScryptP) diff --git a/internal/jsre/jsre_test.go b/internal/jsre/jsre_test.go index 9b58fb04903b6..4de1275e6cbe1 100644 --- a/internal/jsre/jsre_test.go +++ b/internal/jsre/jsre_test.go @@ -39,23 +39,19 @@ func (no *testNativeObjectBinding) TestMethod(call goja.FunctionCall) goja.Value return no.vm.ToValue(&msg{m}) } -func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) { - dir, err := os.MkdirTemp("", "jsre-test") - if err != nil { - t.Fatal("cannot create temporary directory:", err) - } +func newWithTestJS(t *testing.T, testjs string) *JSRE { + dir := t.TempDir() if testjs != "" { if err := os.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil { t.Fatal("cannot create test.js:", err) } } jsre := New(dir, os.Stdout) - return jsre, dir + return jsre } func TestExec(t *testing.T) { - jsre, dir := newWithTestJS(t, `msg = "testMsg"`) - defer os.RemoveAll(dir) + jsre := newWithTestJS(t, `msg = "testMsg"`) err := jsre.Exec("test.js") if err != nil { @@ -77,8 +73,7 @@ func TestExec(t *testing.T) { } func TestNatto(t *testing.T) { - jsre, dir := newWithTestJS(t, `setTimeout(function(){msg = "testMsg"}, 1);`) - defer os.RemoveAll(dir) + jsre := newWithTestJS(t, `setTimeout(function(){msg = "testMsg"}, 1);`) err := jsre.Exec("test.js") if err != nil { @@ -113,8 +108,7 @@ func TestBind(t *testing.T) { } func TestLoadScript(t *testing.T) { - jsre, dir := newWithTestJS(t, `msg = "testMsg"`) - defer os.RemoveAll(dir) + jsre := newWithTestJS(t, `msg = "testMsg"`) _, err := jsre.Run(`loadScript("test.js")`) if err != nil { diff --git a/node/config_test.go b/node/config_test.go index 321a7bad6e639..8b3de74b9d74e 100644 --- a/node/config_test.go +++ b/node/config_test.go @@ -31,11 +31,7 @@ import ( // ones or automatically generated temporary ones. func TestDatadirCreation(t *testing.T) { // Create a temporary data dir and check that it can be used by a node - dir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatalf("failed to create manual data dir: %v", err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() node, err := New(&Config{DataDir: dir}) if err != nil { @@ -61,7 +57,10 @@ func TestDatadirCreation(t *testing.T) { if err != nil { t.Fatalf("failed to create temporary file: %v", err) } - defer os.Remove(file.Name()) + defer func() { + file.Close() + os.Remove(file.Name()) + }() dir = filepath.Join(file.Name(), "invalid/path") node, err = New(&Config{DataDir: dir}) @@ -108,11 +107,7 @@ func TestIPCPathResolution(t *testing.T) { // ephemeral. func TestNodeKeyPersistency(t *testing.T) { // Create a temporary folder and make sure no key is present - dir, err := os.MkdirTemp("", "node-test") - if err != nil { - t.Fatalf("failed to create temporary data directory: %v", err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() keyfile := filepath.Join(dir, "unit-test", datadirPrivateKey) diff --git a/node/node_test.go b/node/node_test.go index b733ea517492a..6e6ea3be79d03 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -19,7 +19,6 @@ package node import ( "errors" "net/http" - "os" "reflect" "testing" "time" @@ -80,11 +79,7 @@ func TestNodeLifeCycle(t *testing.T) { // Tests that if the data dir is already in use, an appropriate error is returned. func TestNodeUsedDataDir(t *testing.T) { // Create a temporary folder to use as the data directory - dir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatalf("failed to create temporary data directory: %v", err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() // Create a new node based on the data directory original, err := New(&Config{DataDir: dir}) diff --git a/node/service_test.go b/node/service_test.go index 1c275e2ecbeb6..bf968c7320422 100644 --- a/node/service_test.go +++ b/node/service_test.go @@ -28,11 +28,7 @@ import ( // the configured service context. func TestContextDatabases(t *testing.T) { // Create a temporary folder and ensure no database is contained within - dir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatalf("failed to create temporary data directory: %v", err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() if _, err := os.Stat(filepath.Join(dir, "database")); err == nil { t.Fatalf("non-created database already exists") diff --git a/p2p/discover/database_test.go b/p2p/discover/database_test.go index d881c653377e8..f1ea25139c8fe 100644 --- a/p2p/discover/database_test.go +++ b/p2p/discover/database_test.go @@ -19,7 +19,6 @@ package discover import ( "bytes" "net" - "os" "path/filepath" "reflect" "testing" @@ -254,11 +253,7 @@ func TestNodeDBSeedQuery(t *testing.T) { } func TestNodeDBPersistency(t *testing.T) { - root, err := os.MkdirTemp("", "nodedb-") - if err != nil { - t.Fatalf("failed to create temporary data folder: %v", err) - } - defer os.RemoveAll(root) + root := t.TempDir() var ( testKey = []byte("somekey") diff --git a/p2p/discv5/database_test.go b/p2p/discv5/database_test.go index 73ee613a34fef..9f9c2ee3a0034 100644 --- a/p2p/discv5/database_test.go +++ b/p2p/discv5/database_test.go @@ -19,7 +19,6 @@ package discv5 import ( "bytes" "net" - "os" "path/filepath" "reflect" "testing" @@ -254,11 +253,7 @@ func TestNodeDBSeedQuery(t *testing.T) { } func TestNodeDBPersistency(t *testing.T) { - root, err := os.MkdirTemp("", "nodedb-") - if err != nil { - t.Fatalf("failed to create temporary data folder: %v", err) - } - defer os.RemoveAll(root) + root := t.TempDir() var ( testKey = []byte("somekey") diff --git a/trie/trie_test.go b/trie/trie_test.go index b8ed49364535a..76f98acd1fab9 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -496,7 +496,7 @@ const benchElemCount = 20000 func benchGet(b *testing.B, commit bool) { trie := new(Trie) if commit { - _, tmpdb := tempDB() + tmpdb := tempDB(b) trie, _ = New(common.Hash{}, tmpdb) } k := make([]byte, 32) @@ -837,16 +837,13 @@ func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [] b.StopTimer() } -func tempDB() (string, *Database) { - dir, err := os.MkdirTemp("", "trie-bench") - if err != nil { - panic(fmt.Sprintf("can't create temporary directory: %v", err)) - } +func tempDB(tb testing.TB) *Database { + dir := tb.TempDir() diskdb, err := leveldb.New(dir, 256, 0, "") if err != nil { panic(fmt.Sprintf("can't create temporary database: %v", err)) } - return dir, NewDatabase(diskdb) + return NewDatabase(diskdb) } func getString(trie *Trie, k string) []byte {