all: use T.TempDir to create temporary test directories (#24633)

This commit is contained in:
Daniel Liu 2025-01-14 10:56:13 +08:00
parent 8b9138521e
commit 5b10b2441c
27 changed files with 73 additions and 206 deletions

View file

@ -86,13 +86,9 @@ func SimulateWalletAddressAndSignFn() (common.Address, func(account accounts.Acc
veryLightScryptN := 2 veryLightScryptN := 2
veryLightScryptP := 1 veryLightScryptP := 1
dir, _ := os.MkdirTemp("", "eth-SimulateWalletAddressAndSignFn-test") dir, _ := os.MkdirTemp("", "eth-SimulateWalletAddressAndSignFn-test")
new := func(kd string) *keystore.KeyStore {
return keystore.NewKeyStore(kd, veryLightScryptN, veryLightScryptP)
}
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
ks := new(dir)
ks := keystore.NewKeyStore(dir, veryLightScryptN, veryLightScryptP)
pass := "" // not used but required by API pass := "" // not used but required by API
a1, err := ks.NewAccount(pass) a1, err := ks.NewAccount(pass)
if err != nil { if err != nil {

View file

@ -1919,14 +1919,10 @@ func TestGolangBindings(t *testing.T) {
} }
t.Log("Using config", params.TestXDPoSMockChainConfig) t.Log("Using config", params.TestXDPoSMockChainConfig)
// Create a temporary workspace for the test suite // Create a temporary workspace for the test suite
ws, err := os.MkdirTemp("", "binding-test") ws := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary workspace: %v", err)
}
// defer os.RemoveAll(ws)
pkg := filepath.Join(ws, "bindtest") 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) t.Fatalf("failed to create package: %v", err)
} }
// Generate the test suite for all the contracts // Generate the test suite for all the contracts

View file

@ -55,7 +55,6 @@ func TestWatchNewFile(t *testing.T) {
t.Parallel() t.Parallel()
dir, ks := tmpKeyStore(t, false) dir, ks := tmpKeyStore(t, false)
defer os.RemoveAll(dir)
// Ensure the watcher is started before adding any files. // Ensure the watcher is started before adding any files.
ks.Accounts() ks.Accounts()

View file

@ -37,7 +37,6 @@ var testSigData = make([]byte, 32)
func TestKeyStore(t *testing.T) { func TestKeyStore(t *testing.T) {
dir, ks := tmpKeyStore(t, true) dir, ks := tmpKeyStore(t, true)
defer os.RemoveAll(dir)
a, err := ks.NewAccount("foo") a, err := ks.NewAccount("foo")
if err != nil { if err != nil {
@ -71,8 +70,7 @@ func TestKeyStore(t *testing.T) {
} }
func TestSign(t *testing.T) { func TestSign(t *testing.T) {
dir, ks := tmpKeyStore(t, true) _, ks := tmpKeyStore(t, true)
defer os.RemoveAll(dir)
pass := "" // not used but required by API pass := "" // not used but required by API
a1, err := ks.NewAccount(pass) a1, err := ks.NewAccount(pass)
@ -88,8 +86,7 @@ func TestSign(t *testing.T) {
} }
func TestSignWithPassphrase(t *testing.T) { func TestSignWithPassphrase(t *testing.T) {
dir, ks := tmpKeyStore(t, true) _, ks := tmpKeyStore(t, true)
defer os.RemoveAll(dir)
pass := "passwd" pass := "passwd"
acc, err := ks.NewAccount(pass) acc, err := ks.NewAccount(pass)
@ -116,8 +113,7 @@ func TestSignWithPassphrase(t *testing.T) {
} }
func TestTimedUnlock(t *testing.T) { func TestTimedUnlock(t *testing.T) {
dir, ks := tmpKeyStore(t, true) _, ks := tmpKeyStore(t, true)
defer os.RemoveAll(dir)
pass := "foo" pass := "foo"
a1, err := ks.NewAccount(pass) a1, err := ks.NewAccount(pass)
@ -151,8 +147,7 @@ func TestTimedUnlock(t *testing.T) {
} }
func TestOverrideUnlock(t *testing.T) { func TestOverrideUnlock(t *testing.T) {
dir, ks := tmpKeyStore(t, false) _, ks := tmpKeyStore(t, false)
defer os.RemoveAll(dir)
pass := "foo" pass := "foo"
a1, err := ks.NewAccount(pass) 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. // This test should fail under -race if signing races the expiration goroutine.
func TestSignRace(t *testing.T) { func TestSignRace(t *testing.T) {
dir, ks := tmpKeyStore(t, false) _, ks := tmpKeyStore(t, false)
defer os.RemoveAll(dir)
// Create a test account. // Create a test account.
a1, err := ks.NewAccount("") a1, err := ks.NewAccount("")
@ -221,8 +215,7 @@ func TestSignRace(t *testing.T) {
// addition and removal of wallet event subscriptions. // addition and removal of wallet event subscriptions.
func TestWalletNotifierLifecycle(t *testing.T) { func TestWalletNotifierLifecycle(t *testing.T) {
// Create a temporary kesytore to test with // Create a temporary kesytore to test with
dir, ks := tmpKeyStore(t, false) _, ks := tmpKeyStore(t, false)
defer os.RemoveAll(dir)
// Ensure that the notification updater is not running yet // Ensure that the notification updater is not running yet
time.Sleep(250 * time.Millisecond) time.Sleep(250 * time.Millisecond)
@ -282,8 +275,7 @@ type walletEvent struct {
// Tests that wallet notifications and correctly fired when accounts are added // Tests that wallet notifications and correctly fired when accounts are added
// or deleted from the keystore. // or deleted from the keystore.
func TestWalletNotifications(t *testing.T) { func TestWalletNotifications(t *testing.T) {
dir, ks := tmpKeyStore(t, false) _, ks := tmpKeyStore(t, false)
defer os.RemoveAll(dir)
// Subscribe to the wallet feed and collect events. // Subscribe to the wallet feed and collect events.
var ( var (
@ -344,8 +336,7 @@ func TestWalletNotifications(t *testing.T) {
// TestImportECDSA tests the import functionality of a keystore. // TestImportECDSA tests the import functionality of a keystore.
func TestImportECDSA(t *testing.T) { func TestImportECDSA(t *testing.T) {
dir, ks := tmpKeyStore(t, true) _, ks := tmpKeyStore(t, true)
defer os.RemoveAll(dir)
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
t.Fatalf("failed to generate key: %v", key) 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. // TestImportExport tests the import and export functionality of a keystore.
func TestImportExport(t *testing.T) { func TestImportExport(t *testing.T) {
dir, ks := tmpKeyStore(t, true) _, ks := tmpKeyStore(t, true)
defer os.RemoveAll(dir)
acc, err := ks.NewAccount("old") acc, err := ks.NewAccount("old")
if err != nil { if err != nil {
t.Fatalf("failed to create account: %v", acc) t.Fatalf("failed to create account: %v", acc)
@ -394,8 +384,7 @@ func TestImportExport(t *testing.T) {
// TestImportRace tests the keystore on races. // TestImportRace tests the keystore on races.
// This test should fail under -race if importing races. // This test should fail under -race if importing races.
func TestImportRace(t *testing.T) { func TestImportRace(t *testing.T) {
dir, ks := tmpKeyStore(t, true) _, ks := tmpKeyStore(t, true)
defer os.RemoveAll(dir)
acc, err := ks.NewAccount("old") acc, err := ks.NewAccount("old")
if err != nil { if err != nil {
t.Fatalf("failed to create account: %v", acc) t.Fatalf("failed to create account: %v", acc)
@ -404,8 +393,7 @@ func TestImportRace(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to export account: %v", acc) t.Fatalf("failed to export account: %v", acc)
} }
dir2, ks2 := tmpKeyStore(t, true) _, ks2 := tmpKeyStore(t, true)
defer os.RemoveAll(dir2)
var atom uint32 var atom uint32
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(2) 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) { func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
d, err := os.MkdirTemp("", "eth-keystore-test") d := t.TempDir()
if err != nil {
t.Fatal(err)
}
newKs := NewPlaintextKeyStore newKs := NewPlaintextKeyStore
if encrypted { if encrypted {
newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) } newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }

View file

@ -20,7 +20,6 @@ import (
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings" "strings"
@ -31,10 +30,7 @@ import (
) )
func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) { func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) {
d, err := os.MkdirTemp("", "geth-keystore-test") d := t.TempDir()
if err != nil {
t.Fatal(err)
}
if encrypted { if encrypted {
ks = &keyStorePassphrase{d, veryLightScryptN, veryLightScryptP, true} ks = &keyStorePassphrase{d, veryLightScryptN, veryLightScryptP, true}
} else { } else {
@ -44,8 +40,7 @@ func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) {
} }
func TestKeyStorePlain(t *testing.T) { func TestKeyStorePlain(t *testing.T) {
dir, ks := tmpKeyStoreIface(t, false) _, ks := tmpKeyStoreIface(t, false)
defer os.RemoveAll(dir)
pass := "" // not used but required by API pass := "" // not used but required by API
k1, account, err := storeNewKey(ks, rand.Reader, pass) k1, account, err := storeNewKey(ks, rand.Reader, pass)
@ -65,8 +60,7 @@ func TestKeyStorePlain(t *testing.T) {
} }
func TestKeyStorePassphrase(t *testing.T) { func TestKeyStorePassphrase(t *testing.T) {
dir, ks := tmpKeyStoreIface(t, true) _, ks := tmpKeyStoreIface(t, true)
defer os.RemoveAll(dir)
pass := "foo" pass := "foo"
k1, account, err := storeNewKey(ks, rand.Reader, pass) k1, account, err := storeNewKey(ks, rand.Reader, pass)
@ -86,8 +80,7 @@ func TestKeyStorePassphrase(t *testing.T) {
} }
func TestKeyStorePassphraseDecryptionFail(t *testing.T) { func TestKeyStorePassphraseDecryptionFail(t *testing.T) {
dir, ks := tmpKeyStoreIface(t, true) _, ks := tmpKeyStoreIface(t, true)
defer os.RemoveAll(dir)
pass := "foo" pass := "foo"
k1, account, err := storeNewKey(ks, rand.Reader, pass) k1, account, err := storeNewKey(ks, rand.Reader, pass)
@ -101,7 +94,6 @@ func TestKeyStorePassphraseDecryptionFail(t *testing.T) {
func TestImportPreSaleKey(t *testing.T) { func TestImportPreSaleKey(t *testing.T) {
dir, ks := tmpKeyStoreIface(t, true) dir, ks := tmpKeyStoreIface(t, true)
defer os.RemoveAll(dir)
// file content of a presale key file generated with: // file content of a presale key file generated with:
// python pyethsaletool.py genwallet // python pyethsaletool.py genwallet

View file

@ -33,7 +33,7 @@ import (
// are copied into a temporary keystore directory. // are copied into a temporary keystore directory.
func tmpDatadirWithKeystore(t *testing.T) string { func tmpDatadirWithKeystore(t *testing.T) string {
datadir := tmpdir(t) datadir := t.TempDir()
keystore := filepath.Join(datadir, "keystore") keystore := filepath.Join(datadir, "keystore")
source := filepath.Join("..", "..", "accounts", "keystore", "testdata", "keystore") source := filepath.Join("..", "..", "accounts", "keystore", "testdata", "keystore")
if err := cp.CopyAll(keystore, source); err != nil { if err := cp.CopyAll(keystore, source); err != nil {
@ -43,8 +43,7 @@ func tmpDatadirWithKeystore(t *testing.T) string {
} }
func TestAccountListEmpty(t *testing.T) { func TestAccountListEmpty(t *testing.T) {
datadir := tmpdir(t) datadir := t.TempDir()
defer os.RemoveAll(datadir)
XDC := runXDC(t, "account", "list", "--datadir", datadir) XDC := runXDC(t, "account", "list", "--datadir", datadir)
XDC.ExpectExit() XDC.ExpectExit()
} }
@ -144,8 +143,7 @@ Repeat passphrase: {{.InputLine "foobar2"}}
} }
func TestWalletImport(t *testing.T) { func TestWalletImport(t *testing.T) {
datadir := tmpdir(t) datadir := t.TempDir()
defer os.RemoveAll(datadir)
XDC := runXDC(t, "wallet", "import", "--datadir", datadir, "--lightkdf", "testdata/guswallet.json") XDC := runXDC(t, "wallet", "import", "--datadir", datadir, "--lightkdf", "testdata/guswallet.json")
defer XDC.ExpectExit() defer XDC.ExpectExit()
XDC.Expect(` XDC.Expect(`

View file

@ -19,7 +19,6 @@ package main
import ( import (
"crypto/rand" "crypto/rand"
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strconv" "strconv"
@ -39,8 +38,7 @@ const (
// then terminated by closing the input stream. // then terminated by closing the input stream.
func TestConsoleWelcome(t *testing.T) { func TestConsoleWelcome(t *testing.T) {
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
datadir := tmpdir(t) datadir := t.TempDir()
defer os.RemoveAll(datadir)
// Start a XDC console, make sure it's cleaned up and terminate the console // Start a XDC console, make sure it's cleaned up and terminate the console
XDC := runXDC(t, XDC := runXDC(t,
@ -77,8 +75,7 @@ at block: 0 ({{niltime}})
func TestIPCAttachWelcome(t *testing.T) { func TestIPCAttachWelcome(t *testing.T) {
// Configure the instance for IPC attachement // Configure the instance for IPC attachement
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
datadir := tmpdir(t) datadir := t.TempDir()
defer os.RemoveAll(datadir)
var ipc string var ipc string
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
ipc = `\\.\pipe\XDC` + strconv.Itoa(trulyRandInt(100000, 999999)) ipc = `\\.\pipe\XDC` + strconv.Itoa(trulyRandInt(100000, 999999))
@ -100,8 +97,7 @@ func TestIPCAttachWelcome(t *testing.T) {
func TestHTTPAttachWelcome(t *testing.T) { func TestHTTPAttachWelcome(t *testing.T) {
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
port := strconv.Itoa(trulyRandInt(1024, 65536)) // Yeah, sometimes this will fail, sorry :P port := strconv.Itoa(trulyRandInt(1024, 65536)) // Yeah, sometimes this will fail, sorry :P
datadir := tmpdir(t) datadir := t.TempDir()
defer os.RemoveAll(datadir)
XDC := runXDC(t, XDC := runXDC(t,
"--datadir", datadir, "--XDCx-datadir", datadir+"/XDCx", "--datadir", datadir, "--XDCx-datadir", datadir+"/XDCx",
"--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none",
@ -117,8 +113,7 @@ func TestHTTPAttachWelcome(t *testing.T) {
func TestWSAttachWelcome(t *testing.T) { func TestWSAttachWelcome(t *testing.T) {
coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" coinbase := "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
port := strconv.Itoa(trulyRandInt(1024, 65536)) // Yeah, sometimes this will fail, sorry :P port := strconv.Itoa(trulyRandInt(1024, 65536)) // Yeah, sometimes this will fail, sorry :P
datadir := tmpdir(t) datadir := t.TempDir()
defer os.RemoveAll(datadir)
XDC := runXDC(t, XDC := runXDC(t,
"--datadir", datadir, "--XDCx-datadir", datadir+"/XDCx", "--datadir", datadir, "--XDCx-datadir", datadir+"/XDCx",
"--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none",

View file

@ -100,8 +100,7 @@ func TestDAOForkBlockNewChain(t *testing.T) {
func testDAOForkBlockNewChain(t *testing.T, test int, genesis string, expectBlock *big.Int, expectVote bool) { func testDAOForkBlockNewChain(t *testing.T, test int, genesis string, expectBlock *big.Int, expectVote bool) {
// Create a temporary data directory to use and inspect later // Create a temporary data directory to use and inspect later
datadir := tmpdir(t) datadir := t.TempDir()
defer os.RemoveAll(datadir)
// Start a XDC instance with the requested flags set and immediately terminate // Start a XDC instance with the requested flags set and immediately terminate
if genesis != "" { if genesis != "" {

View file

@ -25,14 +25,6 @@ import (
"github.com/docker/docker/pkg/reexec" "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 { type testXDC struct {
*cmdtest.TestCmd *cmdtest.TestCmd
@ -78,15 +70,10 @@ func runXDC(t *testing.T, args ...string) *testXDC {
} }
} }
if tt.Datadir == "" { 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) } tt.Cleanup = func() { os.RemoveAll(tt.Datadir) }
args = append([]string{"--datadir", tt.Datadir}, args...) 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 // Boot "XDC". This actually runs the test binary but the TestMain

View file

@ -17,17 +17,12 @@
package main package main
import ( import (
"os"
"path/filepath" "path/filepath"
"testing" "testing"
) )
func TestMessageSignVerify(t *testing.T) { func TestMessageSignVerify(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "ethkey-test") tmpdir := t.TempDir()
if err != nil {
t.Fatal("Can't create temporary directory:", err)
}
defer os.RemoveAll(tmpdir)
keyfile := filepath.Join(tmpdir, "the-keyfile") keyfile := filepath.Join(tmpdir, "the-keyfile")
message := "test message" message := "test message"

View file

@ -73,13 +73,10 @@ func TestWalkMatch(t *testing.T) {
root string root string
pattern string pattern string
} }
dir, err := os.Getwd() test1Dir := t.TempDir()
if err != nil { test2Dir := t.TempDir()
log.Fatal(err)
} err := os.WriteFile(filepath.Join(test1Dir, "test1.ldb"), []byte("hello"), os.ModePerm)
test1Dir, _ := os.MkdirTemp(dir, "test1")
test2Dir, _ := os.MkdirTemp(dir, "test2")
err = os.WriteFile(filepath.Join(test1Dir, "test1.ldb"), []byte("hello"), os.ModePerm)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -87,10 +84,6 @@ func TestWalkMatch(t *testing.T) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer func() {
os.RemoveAll(test1Dir)
os.RemoveAll(test2Dir)
}()
tests := []struct { tests := []struct {
name string name string

View file

@ -48,13 +48,9 @@ func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account acco
veryLightScryptN := 2 veryLightScryptN := 2
veryLightScryptP := 1 veryLightScryptP := 1
dir, _ := os.MkdirTemp("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5))) 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) defer os.RemoveAll(dir)
ks := new(dir)
ks := keystore.NewKeyStore(dir, veryLightScryptN, veryLightScryptP)
pass := "" // not used but required by API pass := "" // not used but required by API
a1, err := ks.ImportECDSA(pk, pass) a1, err := ks.ImportECDSA(pk, pass)
if err != nil { if err != nil {

View file

@ -2,7 +2,6 @@ package engine_v2
import ( import (
"fmt" "fmt"
"os"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
@ -24,10 +23,7 @@ func TestGetMasterNodes(t *testing.T) {
func TestStoreLoadSnapshot(t *testing.T) { func TestStoreLoadSnapshot(t *testing.T) {
snap := newSnapshot(1, common.Hash{0x1}, nil) snap := newSnapshot(1, common.Hash{0x1}, nil)
dir, err := os.MkdirTemp("", "snapshot-test") dir := t.TempDir()
if err != nil {
panic(fmt.Sprintf("can't create temporary directory: %v", err))
}
db, err := leveldb.New(dir, 256, 0, "", false) db, err := leveldb.New(dir, 256, 0, "", false)
if err != nil { if err != nil {
panic(fmt.Sprintf("can't create temporary database: %v", err)) panic(fmt.Sprintf("can't create temporary database: %v", err))

View file

@ -687,6 +687,8 @@ func TestHashimoto(t *testing.T) {
// Tests that caches generated on disk may be done concurrently. // Tests that caches generated on disk may be done concurrently.
func TestConcurrentDiskCacheGeneration(t *testing.T) { func TestConcurrentDiskCacheGeneration(t *testing.T) {
// Create a temp folder to generate the caches into // 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("", "") cachedir, err := os.MkdirTemp("", "")
if err != nil { if err != nil {
t.Fatalf("Failed to create temporary cache dir: %v", err) t.Fatalf("Failed to create temporary cache dir: %v", err)

View file

@ -45,6 +45,8 @@ func TestTestMode(t *testing.T) {
// This test checks that cache lru logic doesn't crash under load. // This test checks that cache lru logic doesn't crash under load.
// It reproduces https://github.com/XinFinOrg/XDPoSChain/issues/14943 // It reproduces https://github.com/XinFinOrg/XDPoSChain/issues/14943
func TestCacheFileEvict(t *testing.T) { 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") tmpdir, err := os.MkdirTemp("", "ethash-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -77,13 +77,9 @@ func getSignerAndSignFn(pk *ecdsa.PrivateKey) (common.Address, func(account acco
veryLightScryptN := 2 veryLightScryptN := 2
veryLightScryptP := 1 veryLightScryptP := 1
dir, _ := os.MkdirTemp("", fmt.Sprintf("eth-getSignerAndSignFn-test-%v", RandStringBytes(5))) 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) defer os.RemoveAll(dir)
ks := new(dir)
ks := keystore.NewKeyStore(dir, veryLightScryptN, veryLightScryptP)
pass := "" // not used but required by API pass := "" // not used but required by API
a1, err := ks.ImportECDSA(pk, pass) a1, err := ks.ImportECDSA(pk, pass)
if err != nil { if err != nil {

View file

@ -87,10 +87,7 @@ type tester struct {
// Please ensure you call Close() on the returned tester to avoid leaks. // Please ensure you call Close() on the returned tester to avoid leaks.
func newTester(t *testing.T, confOverride func(*ethconfig.Config)) *tester { func newTester(t *testing.T, confOverride func(*ethconfig.Config)) *tester {
// Create a temporary storage for the node keys and initialize it // Create a temporary storage for the node keys and initialize it
workspace, err := os.MkdirTemp("", "console-tester-") workspace := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary keystore: %v", err)
}
// Create a networkless protocol stack and start an Ethereum service within // Create a networkless protocol stack and start an Ethereum service within
stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance}) stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance})

View file

@ -148,14 +148,11 @@ func genUncles(i int, gen *BlockGen) {
func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) { func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
// Create the database in memory or in a temporary directory. // Create the database in memory or in a temporary directory.
var db ethdb.Database var db ethdb.Database
var err error
if !disk { if !disk {
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
} else { } else {
dir, err := os.MkdirTemp("", "eth-core-bench") dir := b.TempDir()
if err != nil {
b.Fatalf("cannot create temporary directory: %v", err)
}
defer os.RemoveAll(dir)
db, err = rawdb.NewLevelDBDatabase(dir, 128, 128, "", false) db, err = rawdb.NewLevelDBDatabase(dir, 128, 128, "", false)
if err != nil { if err != nil {
b.Fatalf("cannot create temporary database: %v", err) 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) { func benchWriteChain(b *testing.B, full bool, count uint64) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
dir, err := os.MkdirTemp("", "eth-chain-bench") dir := b.TempDir()
if err != nil {
b.Fatalf("cannot create temporary directory: %v", err)
}
db, err := rawdb.NewLevelDBDatabase(dir, 128, 1024, "", false) db, err := rawdb.NewLevelDBDatabase(dir, 128, 1024, "", false)
if err != nil { if err != nil {
b.Fatalf("error opening database at %v: %v", dir, err) 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) { func benchReadChain(b *testing.B, full bool, count uint64) {
dir, err := os.MkdirTemp("", "eth-chain-bench") dir := b.TempDir()
if err != nil {
b.Fatalf("cannot create temporary directory: %v", err)
}
defer os.RemoveAll(dir)
db, err := rawdb.NewLevelDBDatabase(dir, 128, 1024, "", false) db, err := rawdb.NewLevelDBDatabase(dir, 128, 1024, "", false)
if err != nil { if err != nil {

View file

@ -19,13 +19,12 @@ package filters
import ( import (
"context" "context"
"math/big" "math/big"
"os"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/consensus/ethash" "github.com/XinFinOrg/XDPoSChain/consensus/ethash"
"github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/XinFinOrg/XDPoSChain/crypto" "github.com/XinFinOrg/XDPoSChain/crypto"
"github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/params"
@ -41,11 +40,7 @@ func makeReceipt(addr common.Address) *types.Receipt {
} }
func BenchmarkFilters(b *testing.B) { func BenchmarkFilters(b *testing.B) {
dir, err := os.MkdirTemp("", "filtertest") dir := b.TempDir()
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(dir)
var ( var (
db, _ = rawdb.NewLevelDBDatabase(dir, 0, 0, "", false) db, _ = rawdb.NewLevelDBDatabase(dir, 0, 0, "", false)
@ -95,11 +90,7 @@ func BenchmarkFilters(b *testing.B) {
} }
func TestFilters(t *testing.T) { func TestFilters(t *testing.T) {
dir, err := os.MkdirTemp("", "filtertest") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
var ( var (
db, _ = rawdb.NewLevelDBDatabase(dir, 0, 0, "", false) db, _ = rawdb.NewLevelDBDatabase(dir, 0, 0, "", false)

View file

@ -24,7 +24,6 @@ package guide
import ( import (
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -37,11 +36,7 @@ import (
// Tests that the account management snippets work correctly. // Tests that the account management snippets work correctly.
func TestAccountManagement(t *testing.T) { func TestAccountManagement(t *testing.T) {
// Create a temporary folder to work with // Create a temporary folder to work with
workdir, err := os.MkdirTemp("", "") workdir := t.TempDir()
if err != nil {
t.Fatalf("Failed to create temporary work dir: %v", err)
}
defer os.RemoveAll(workdir)
// Create an encrypted keystore with standard crypto parameters // Create an encrypted keystore with standard crypto parameters
ks := keystore.NewKeyStore(filepath.Join(workdir, "keystore"), keystore.StandardScryptN, keystore.StandardScryptP) ks := keystore.NewKeyStore(filepath.Join(workdir, "keystore"), keystore.StandardScryptN, keystore.StandardScryptP)

View file

@ -39,23 +39,19 @@ func (no *testNativeObjectBinding) TestMethod(call goja.FunctionCall) goja.Value
return no.vm.ToValue(&msg{m}) return no.vm.ToValue(&msg{m})
} }
func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) { func newWithTestJS(t *testing.T, testjs string) *JSRE {
dir, err := os.MkdirTemp("", "jsre-test") dir := t.TempDir()
if err != nil {
t.Fatal("cannot create temporary directory:", err)
}
if testjs != "" { if testjs != "" {
if err := os.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil { if err := os.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil {
t.Fatal("cannot create test.js:", err) t.Fatal("cannot create test.js:", err)
} }
} }
jsre := New(dir, os.Stdout) jsre := New(dir, os.Stdout)
return jsre, dir return jsre
} }
func TestExec(t *testing.T) { func TestExec(t *testing.T) {
jsre, dir := newWithTestJS(t, `msg = "testMsg"`) jsre := newWithTestJS(t, `msg = "testMsg"`)
defer os.RemoveAll(dir)
err := jsre.Exec("test.js") err := jsre.Exec("test.js")
if err != nil { if err != nil {
@ -77,8 +73,7 @@ func TestExec(t *testing.T) {
} }
func TestNatto(t *testing.T) { func TestNatto(t *testing.T) {
jsre, dir := newWithTestJS(t, `setTimeout(function(){msg = "testMsg"}, 1);`) jsre := newWithTestJS(t, `setTimeout(function(){msg = "testMsg"}, 1);`)
defer os.RemoveAll(dir)
err := jsre.Exec("test.js") err := jsre.Exec("test.js")
if err != nil { if err != nil {
@ -113,8 +108,7 @@ func TestBind(t *testing.T) {
} }
func TestLoadScript(t *testing.T) { func TestLoadScript(t *testing.T) {
jsre, dir := newWithTestJS(t, `msg = "testMsg"`) jsre := newWithTestJS(t, `msg = "testMsg"`)
defer os.RemoveAll(dir)
_, err := jsre.Run(`loadScript("test.js")`) _, err := jsre.Run(`loadScript("test.js")`)
if err != nil { if err != nil {

View file

@ -31,11 +31,7 @@ import (
// ones or automatically generated temporary ones. // ones or automatically generated temporary ones.
func TestDatadirCreation(t *testing.T) { func TestDatadirCreation(t *testing.T) {
// Create a temporary data dir and check that it can be used by a node // Create a temporary data dir and check that it can be used by a node
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
if err != nil {
t.Fatalf("failed to create manual data dir: %v", err)
}
defer os.RemoveAll(dir)
node, err := New(&Config{DataDir: dir}) node, err := New(&Config{DataDir: dir})
if err != nil { if err != nil {
@ -61,7 +57,10 @@ func TestDatadirCreation(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to create temporary file: %v", err) 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") dir = filepath.Join(file.Name(), "invalid/path")
node, err = New(&Config{DataDir: dir}) node, err = New(&Config{DataDir: dir})
@ -108,11 +107,7 @@ func TestIPCPathResolution(t *testing.T) {
// ephemeral. // ephemeral.
func TestNodeKeyPersistency(t *testing.T) { func TestNodeKeyPersistency(t *testing.T) {
// Create a temporary folder and make sure no key is present // Create a temporary folder and make sure no key is present
dir, err := os.MkdirTemp("", "node-test") dir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary data directory: %v", err)
}
defer os.RemoveAll(dir)
keyfile := filepath.Join(dir, "unit-test", datadirPrivateKey) keyfile := filepath.Join(dir, "unit-test", datadirPrivateKey)

View file

@ -19,7 +19,6 @@ package node
import ( import (
"errors" "errors"
"net/http" "net/http"
"os"
"reflect" "reflect"
"testing" "testing"
"time" "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. // Tests that if the data dir is already in use, an appropriate error is returned.
func TestNodeUsedDataDir(t *testing.T) { func TestNodeUsedDataDir(t *testing.T) {
// Create a temporary folder to use as the data directory // Create a temporary folder to use as the data directory
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary data directory: %v", err)
}
defer os.RemoveAll(dir)
// Create a new node based on the data directory // Create a new node based on the data directory
original, err := New(&Config{DataDir: dir}) original, err := New(&Config{DataDir: dir})

View file

@ -28,11 +28,7 @@ import (
// the configured service context. // the configured service context.
func TestContextDatabases(t *testing.T) { func TestContextDatabases(t *testing.T) {
// Create a temporary folder and ensure no database is contained within // Create a temporary folder and ensure no database is contained within
dir, err := os.MkdirTemp("", "") dir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary data directory: %v", err)
}
defer os.RemoveAll(dir)
if _, err := os.Stat(filepath.Join(dir, "database")); err == nil { if _, err := os.Stat(filepath.Join(dir, "database")); err == nil {
t.Fatalf("non-created database already exists") t.Fatalf("non-created database already exists")

View file

@ -19,7 +19,6 @@ package discover
import ( import (
"bytes" "bytes"
"net" "net"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"testing" "testing"
@ -254,11 +253,7 @@ func TestNodeDBSeedQuery(t *testing.T) {
} }
func TestNodeDBPersistency(t *testing.T) { func TestNodeDBPersistency(t *testing.T) {
root, err := os.MkdirTemp("", "nodedb-") root := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary data folder: %v", err)
}
defer os.RemoveAll(root)
var ( var (
testKey = []byte("somekey") testKey = []byte("somekey")

View file

@ -19,7 +19,6 @@ package discv5
import ( import (
"bytes" "bytes"
"net" "net"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"testing" "testing"
@ -254,11 +253,7 @@ func TestNodeDBSeedQuery(t *testing.T) {
} }
func TestNodeDBPersistency(t *testing.T) { func TestNodeDBPersistency(t *testing.T) {
root, err := os.MkdirTemp("", "nodedb-") root := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary data folder: %v", err)
}
defer os.RemoveAll(root)
var ( var (
testKey = []byte("somekey") testKey = []byte("somekey")

View file

@ -496,7 +496,7 @@ const benchElemCount = 20000
func benchGet(b *testing.B, commit bool) { func benchGet(b *testing.B, commit bool) {
trie := new(Trie) trie := new(Trie)
if commit { if commit {
_, tmpdb := tempDB() tmpdb := tempDB(b)
trie, _ = New(common.Hash{}, tmpdb) trie, _ = New(common.Hash{}, tmpdb)
} }
k := make([]byte, 32) k := make([]byte, 32)
@ -837,16 +837,13 @@ func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts []
b.StopTimer() b.StopTimer()
} }
func tempDB() (string, *Database) { func tempDB(tb testing.TB) *Database {
dir, err := os.MkdirTemp("", "trie-bench") dir := tb.TempDir()
if err != nil {
panic(fmt.Sprintf("can't create temporary directory: %v", err))
}
diskdb, err := leveldb.New(dir, 256, 0, "", false) diskdb, err := leveldb.New(dir, 256, 0, "", false)
if err != nil { if err != nil {
panic(fmt.Sprintf("can't create temporary database: %v", err)) panic(fmt.Sprintf("can't create temporary database: %v", err))
} }
return dir, NewDatabase(diskdb) return NewDatabase(diskdb)
} }
func getString(trie *Trie, k string) []byte { func getString(trie *Trie, k string) []byte {