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

This commit replaces ioutil.TempDir with t.TempDir in tests. The
directory created by t.TempDir is automatically removed when the test
and all its subtests complete.

Prior to this commit, temporary directory created using ioutil.TempDir
had to be removed manually by calling os.RemoveAll, which is omitted in
some tests. The error handling boilerplate e.g.

	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Fatal(err)
		}
	}

is also tedious, but t.TempDir handles this for us nicely.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2022-04-08 21:44:55 +08:00 committed by GitHub
parent bf5cacfb8f
commit 8d066f1f42
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 140 additions and 372 deletions

View File

@ -1966,14 +1966,10 @@ func TestGolangBindings(t *testing.T) {
t.Skip("go sdk not found for testing") t.Skip("go sdk not found for testing")
} }
// Create a temporary workspace for the test suite // Create a temporary workspace for the test suite
ws, err := ioutil.TempDir("", "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

@ -17,7 +17,6 @@
package keystore package keystore
import ( import (
"io/ioutil"
"math/rand" "math/rand"
"os" "os"
"runtime" "runtime"
@ -38,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 {
@ -72,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)
@ -89,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)
@ -117,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)
@ -152,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)
@ -193,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("")
@ -222,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)
@ -283,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 (
@ -345,8 +336,7 @@ func TestWalletNotifications(t *testing.T) {
// TestImportExport tests the import functionality of a keystore. // TestImportExport 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)
@ -364,8 +354,7 @@ func TestImportECDSA(t *testing.T) {
// TestImportECDSA tests the import and export functionality of a keystore. // TestImportECDSA 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)
@ -374,8 +363,7 @@ func TestImportExport(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)
if _, err = ks2.Import(json, "old", "old"); err == nil { if _, err = ks2.Import(json, "old", "old"); err == nil {
t.Errorf("importing with invalid password succeeded") t.Errorf("importing with invalid password succeeded")
} }
@ -395,8 +383,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)
@ -405,8 +392,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)
@ -462,10 +448,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 := ioutil.TempDir("", "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,8 +20,6 @@ import (
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io/ioutil"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings" "strings"
@ -32,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 := ioutil.TempDir("", "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 {
@ -45,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)
@ -66,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)
@ -87,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)
@ -102,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

@ -17,18 +17,12 @@
package main package main
import ( import (
"io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
) )
func TestMessageSignVerify(t *testing.T) { func TestMessageSignVerify(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "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

@ -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 {
@ -111,7 +111,7 @@ func TestAccountImport(t *testing.T) {
} }
func importAccountWithExpect(t *testing.T, key string, expected string) { func importAccountWithExpect(t *testing.T, key string, expected string) {
dir := tmpdir(t) dir := t.TempDir()
keyfile := filepath.Join(dir, "key.prv") keyfile := filepath.Join(dir, "key.prv")
if err := ioutil.WriteFile(keyfile, []byte(key), 0600); err != nil { if err := ioutil.WriteFile(keyfile, []byte(key), 0600); err != nil {
t.Error(err) t.Error(err)

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"
@ -92,9 +91,7 @@ func TestAttachWelcome(t *testing.T) {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
ipc = `\\.\pipe\geth` + strconv.Itoa(trulyRandInt(100000, 999999)) ipc = `\\.\pipe\geth` + strconv.Itoa(trulyRandInt(100000, 999999))
} else { } else {
ws := tmpdir(t) ipc = filepath.Join(t.TempDir(), "geth.ipc")
defer os.RemoveAll(ws)
ipc = filepath.Join(ws, "geth.ipc")
} }
// And HTTP + WS attachment // And HTTP + WS attachment
p := trulyRandInt(1024, 65533) // Yeah, sometimes this will fail, sorry :P p := trulyRandInt(1024, 65533) // Yeah, sometimes this will fail, sorry :P
@ -118,6 +115,7 @@ func TestAttachWelcome(t *testing.T) {
waitForEndpoint(t, endpoint, 3*time.Second) waitForEndpoint(t, endpoint, 3*time.Second)
testAttachWelcome(t, geth, endpoint, httpAPIs) testAttachWelcome(t, geth, endpoint, httpAPIs)
}) })
geth.ExpectExit()
} }
func testAttachWelcome(t *testing.T, geth *testgeth, endpoint, apis string) { func testAttachWelcome(t *testing.T, geth *testgeth, endpoint, apis string) {

View File

@ -19,7 +19,6 @@ package main
import ( import (
"io/ioutil" "io/ioutil"
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -106,8 +105,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 Geth instance with the requested flags set and immediately terminate // Start a Geth instance with the requested flags set and immediately terminate
if genesis != "" { if genesis != "" {

View File

@ -18,7 +18,6 @@ package main
import ( import (
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
) )
@ -73,8 +72,7 @@ var customGenesisTests = []struct {
func TestCustomGenesis(t *testing.T) { func TestCustomGenesis(t *testing.T) {
for i, tt := range customGenesisTests { for i, tt := range customGenesisTests {
// 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)
// Initialize the data directory with the custom genesis block // Initialize the data directory with the custom genesis block
json := filepath.Join(datadir, "genesis.json") json := filepath.Join(datadir, "genesis.json")

View File

@ -19,7 +19,6 @@ package main
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"testing" "testing"
"time" "time"
@ -29,14 +28,6 @@ import (
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
) )
func tmpdir(t *testing.T) string {
dir, err := ioutil.TempDir("", "geth-test")
if err != nil {
t.Fatal(err)
}
return dir
}
type testgeth struct { type testgeth struct {
*cmdtest.TestCmd *cmdtest.TestCmd
@ -82,15 +73,9 @@ func runGeth(t *testing.T, args ...string) *testgeth {
} }
} }
if tt.Datadir == "" { if tt.Datadir == "" {
tt.Datadir = tmpdir(t) // The temporary datadir will be removed automatically if something fails below.
tt.Cleanup = func() { os.RemoveAll(tt.Datadir) } tt.Datadir = t.TempDir()
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 "geth". This actually runs the test binary but the TestMain // Boot "geth". This actually runs the test binary but the TestMain

View File

@ -698,6 +698,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 := ioutil.TempDir("", "") cachedir, err := ioutil.TempDir("", "")
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)
@ -794,11 +796,7 @@ func BenchmarkHashimotoFullSmall(b *testing.B) {
func benchmarkHashimotoFullMmap(b *testing.B, name string, lock bool) { func benchmarkHashimotoFullMmap(b *testing.B, name string, lock bool) {
b.Run(name, func(b *testing.B) { b.Run(name, func(b *testing.B) {
tmpdir, err := ioutil.TempDir("", "ethash-test") tmpdir := b.TempDir()
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(tmpdir)
d := &dataset{epoch: 0} d := &dataset{epoch: 0}
d.generate(tmpdir, 1, lock, false) d.generate(tmpdir, 1, lock, false)

View File

@ -57,6 +57,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/ethereum/go-ethereum/issues/14943 // It reproduces https://github.com/ethereum/go-ethereum/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 := ioutil.TempDir("", "ethash-test") tmpdir, err := ioutil.TempDir("", "ethash-test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strings" "strings"
"testing" "testing"
@ -88,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 := ioutil.TempDir("", "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

@ -18,9 +18,7 @@ package core
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"io/ioutil"
"math/big" "math/big"
"os"
"testing" "testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -175,14 +173,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 := ioutil.TempDir("", "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)
@ -278,26 +273,18 @@ 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 := ioutil.TempDir("", "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)
} }
makeChainForBench(db, full, count) makeChainForBench(db, full, count)
db.Close() db.Close()
os.RemoveAll(dir)
} }
} }
func benchReadChain(b *testing.B, full bool, count uint64) { func benchReadChain(b *testing.B, full bool, count uint64) {
dir, err := ioutil.TempDir("", "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

@ -21,9 +21,7 @@
package core package core
import ( import (
"io/ioutil"
"math/big" "math/big"
"os"
"testing" "testing"
"time" "time"
@ -1756,11 +1754,7 @@ func testRepair(t *testing.T, tt *rewindTest, snapshots bool) {
// fmt.Println(tt.dump(true)) // fmt.Println(tt.dump(true))
// Create a temporary persistent database // Create a temporary persistent database
datadir, err := ioutil.TempDir("", "") datadir := t.TempDir()
if err != nil {
t.Fatalf("Failed to create temporary datadir: %v", err)
}
os.RemoveAll(datadir)
db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false) db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false)
if err != nil { if err != nil {
@ -1884,11 +1878,7 @@ func TestIssue23496(t *testing.T) {
//log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) //log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
// Create a temporary persistent database // Create a temporary persistent database
datadir, err := ioutil.TempDir("", "") datadir := t.TempDir()
if err != nil {
t.Fatalf("Failed to create temporary datadir: %v", err)
}
os.RemoveAll(datadir)
db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false) db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false)
if err != nil { if err != nil {

View File

@ -21,9 +21,7 @@ package core
import ( import (
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -1955,11 +1953,7 @@ func testSetHead(t *testing.T, tt *rewindTest, snapshots bool) {
// fmt.Println(tt.dump(false)) // fmt.Println(tt.dump(false))
// Create a temporary persistent database // Create a temporary persistent database
datadir, err := ioutil.TempDir("", "") datadir := t.TempDir()
if err != nil {
t.Fatalf("Failed to create temporary datadir: %v", err)
}
os.RemoveAll(datadir)
db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false) db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false)
if err != nil { if err != nil {

View File

@ -22,7 +22,6 @@ package core
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"strings" "strings"
@ -59,11 +58,7 @@ type snapshotTestBasic struct {
func (basic *snapshotTestBasic) prepare(t *testing.T) (*BlockChain, []*types.Block) { func (basic *snapshotTestBasic) prepare(t *testing.T) (*BlockChain, []*types.Block) {
// Create a temporary persistent database // Create a temporary persistent database
datadir, err := ioutil.TempDir("", "") datadir := t.TempDir()
if err != nil {
t.Fatalf("Failed to create temporary datadir: %v", err)
}
os.RemoveAll(datadir)
db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false) db, err := rawdb.NewLevelDBDatabaseWithFreezer(datadir, 0, 0, datadir, "", false)
if err != nil { if err != nil {

View File

@ -19,7 +19,6 @@ package core
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os" "os"
@ -791,15 +790,12 @@ func TestFastVsFullChains(t *testing.T) {
t.Fatalf("failed to insert receipt %d: %v", n, err) t.Fatalf("failed to insert receipt %d: %v", n, err)
} }
// Freezer style fast import the chain. // Freezer style fast import the chain.
frdir, err := ioutil.TempDir("", "") frdir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(frdir)
ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false) ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
defer ancientDb.Close()
gspec.MustCommit(ancientDb) gspec.MustCommit(ancientDb)
ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil) ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
defer ancient.Stop() defer ancient.Stop()
@ -886,18 +882,14 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil) blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
// makeDb creates a db instance for testing. // makeDb creates a db instance for testing.
makeDb := func() (ethdb.Database, func()) { makeDb := func() ethdb.Database {
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(dir)
db, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false) db, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
gspec.MustCommit(db) gspec.MustCommit(db)
return db, func() { os.RemoveAll(dir) } return db
} }
// Configure a subchain to roll back // Configure a subchain to roll back
remove := blocks[height/2].NumberU64() remove := blocks[height/2].NumberU64()
@ -917,8 +909,8 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
} }
} }
// Import the chain as an archive node and ensure all pointers are updated // Import the chain as an archive node and ensure all pointers are updated
archiveDb, delfn := makeDb() archiveDb := makeDb()
defer delfn() defer archiveDb.Close()
archiveCaching := *defaultCacheConfig archiveCaching := *defaultCacheConfig
archiveCaching.TrieDirtyDisabled = true archiveCaching.TrieDirtyDisabled = true
@ -934,8 +926,8 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
assert(t, "archive", archive, height/2, height/2, height/2) assert(t, "archive", archive, height/2, height/2, height/2)
// Import the chain as a non-archive node and ensure all pointers are updated // Import the chain as a non-archive node and ensure all pointers are updated
fastDb, delfn := makeDb() fastDb := makeDb()
defer delfn() defer fastDb.Close()
fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil) fast, _ := NewBlockChain(fastDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
defer fast.Stop() defer fast.Stop()
@ -954,8 +946,8 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
assert(t, "fast", fast, height/2, height/2, 0) assert(t, "fast", fast, height/2, height/2, 0)
// Import the chain as a ancient-first node and ensure all pointers are updated // Import the chain as a ancient-first node and ensure all pointers are updated
ancientDb, delfn := makeDb() ancientDb := makeDb()
defer delfn() defer ancientDb.Close()
ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil) ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
defer ancient.Stop() defer ancient.Stop()
@ -973,8 +965,8 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) {
t.Fatalf("failed to truncate ancient store, want %v, have %v", 1, frozen) t.Fatalf("failed to truncate ancient store, want %v, have %v", 1, frozen)
} }
// Import the chain as a light node and ensure all pointers are updated // Import the chain as a light node and ensure all pointers are updated
lightDb, delfn := makeDb() lightDb := makeDb()
defer delfn() defer lightDb.Close()
light, _ := NewBlockChain(lightDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil) light, _ := NewBlockChain(lightDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
if n, err := light.InsertHeaderChain(headers, 1); err != nil { if n, err := light.InsertHeaderChain(headers, 1); err != nil {
t.Fatalf("failed to insert header %d: %v", n, err) t.Fatalf("failed to insert header %d: %v", n, err)
@ -1753,16 +1745,13 @@ func TestBlockchainRecovery(t *testing.T) {
blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil) blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil)
// Import the chain as a ancient-first node and ensure all pointers are updated // Import the chain as a ancient-first node and ensure all pointers are updated
frdir, err := ioutil.TempDir("", "") frdir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(frdir)
ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false) ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
defer ancientDb.Close()
gspec.MustCommit(ancientDb) gspec.MustCommit(ancientDb)
ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil) ancient, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
@ -1825,15 +1814,12 @@ func TestInsertReceiptChainRollback(t *testing.T) {
} }
// Set up a BlockChain that uses the ancient store. // Set up a BlockChain that uses the ancient store.
frdir, err := ioutil.TempDir("", "") frdir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(frdir)
ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false) ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
defer ancientDb.Close()
gspec := Genesis{Config: params.AllEthashProtocolChanges} gspec := Genesis{Config: params.AllEthashProtocolChanges}
gspec.MustCommit(ancientDb) gspec.MustCommit(ancientDb)
ancientChain, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil) ancientChain, _ := NewBlockChain(ancientDb, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
@ -2090,17 +2076,13 @@ func testInsertKnownChainData(t *testing.T, typ string) {
b.OffsetTime(-9) // A higher difficulty b.OffsetTime(-9) // A higher difficulty
}) })
// Import the shared chain and the original canonical one // Import the shared chain and the original canonical one
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(dir)
chaindb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false) chaindb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
(&Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(chaindb) (&Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(chaindb)
defer os.RemoveAll(dir) defer chaindb.Close()
chain, err := NewBlockChain(chaindb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil) chain, err := NewBlockChain(chaindb, nil, params.TestChainConfig, engine, vm.Config{}, nil, nil)
if err != nil { if err != nil {
@ -2254,17 +2236,13 @@ func testInsertKnownChainDataWithMerging(t *testing.T, typ string, mergeHeight i
}) })
// Import the shared chain and the original canonical one // Import the shared chain and the original canonical one
dir, err := ioutil.TempDir("", "") dir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(dir)
chaindb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false) chaindb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), dir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
(&Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(chaindb) (&Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(chaindb)
defer os.RemoveAll(dir) defer chaindb.Close()
chain, err := NewBlockChain(chaindb, nil, &chainConfig, runEngine, vm.Config{}, nil, nil) chain, err := NewBlockChain(chaindb, nil, &chainConfig, runEngine, vm.Config{}, nil, nil)
if err != nil { if err != nil {
@ -2564,11 +2542,7 @@ func TestTransactionIndices(t *testing.T) {
} }
} }
} }
frdir, err := ioutil.TempDir("", "") frdir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(frdir)
ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false) ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
@ -2621,6 +2595,7 @@ func TestTransactionIndices(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
defer ancientDb.Close()
gspec.MustCommit(ancientDb) gspec.MustCommit(ancientDb)
limit = []uint64{0, 64 /* drop stale */, 32 /* shorten history */, 64 /* extend history */, 0 /* restore all */} limit = []uint64{0, 64 /* drop stale */, 32 /* shorten history */, 64 /* extend history */, 0 /* restore all */}
@ -2691,15 +2666,12 @@ func TestSkipStaleTxIndicesInSnapSync(t *testing.T) {
} }
} }
frdir, err := ioutil.TempDir("", "") frdir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(frdir)
ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false) ancientDb, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {
t.Fatalf("failed to create temp freezer db: %v", err) t.Fatalf("failed to create temp freezer db: %v", err)
} }
defer ancientDb.Close()
gspec.MustCommit(ancientDb) gspec.MustCommit(ancientDb)
// Import all blocks into ancient db, only HEAD-32 indices are kept. // Import all blocks into ancient db, only HEAD-32 indices are kept.

View File

@ -23,7 +23,6 @@ import (
"io/ioutil" "io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os"
"reflect" "reflect"
"testing" "testing"
@ -435,11 +434,7 @@ func checkReceiptsRLP(have, want types.Receipts) error {
func TestAncientStorage(t *testing.T) { func TestAncientStorage(t *testing.T) {
// Freezer style fast import the chain. // Freezer style fast import the chain.
frdir, err := ioutil.TempDir("", "") frdir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.RemoveAll(frdir)
db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false) db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {
@ -577,15 +572,12 @@ func TestHashesInRange(t *testing.T) {
// This measures the write speed of the WriteAncientBlocks operation. // This measures the write speed of the WriteAncientBlocks operation.
func BenchmarkWriteAncientBlocks(b *testing.B) { func BenchmarkWriteAncientBlocks(b *testing.B) {
// Open freezer database. // Open freezer database.
frdir, err := ioutil.TempDir("", "") frdir := b.TempDir()
if err != nil {
b.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.RemoveAll(frdir)
db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false) db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {
b.Fatalf("failed to create database with ancient backend") b.Fatalf("failed to create database with ancient backend")
} }
defer db.Close()
// Create the data to insert. The blocks must have consecutive numbers, so we create // Create the data to insert. The blocks must have consecutive numbers, so we create
// all of them ahead of time. However, there is no need to create receipts // all of them ahead of time. However, there is no need to create receipts
@ -886,11 +878,7 @@ func BenchmarkDecodeRLPLogs(b *testing.B) {
func TestHeadersRLPStorage(t *testing.T) { func TestHeadersRLPStorage(t *testing.T) {
// Have N headers in the freezer // Have N headers in the freezer
frdir, err := ioutil.TempDir("", "") frdir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temp freezer dir: %v", err)
}
defer os.Remove(frdir)
db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false) db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
if err != nil { if err != nil {

View File

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os" "os"
@ -50,8 +49,7 @@ func TestFreezerModify(t *testing.T) {
} }
tables := map[string]bool{"raw": true, "rlp": false} tables := map[string]bool{"raw": true, "rlp": false}
f, dir := newFreezerForTesting(t, tables) f, _ := newFreezerForTesting(t, tables)
defer os.RemoveAll(dir)
defer f.Close() defer f.Close()
// Commit test data. // Commit test data.
@ -97,7 +95,6 @@ func TestFreezerModifyRollback(t *testing.T) {
t.Parallel() t.Parallel()
f, dir := newFreezerForTesting(t, freezerTestTableDef) f, dir := newFreezerForTesting(t, freezerTestTableDef)
defer os.RemoveAll(dir)
theError := errors.New("oops") theError := errors.New("oops")
_, err := f.ModifyAncients(func(op ethdb.AncientWriteOp) error { _, err := f.ModifyAncients(func(op ethdb.AncientWriteOp) error {
@ -128,8 +125,7 @@ func TestFreezerModifyRollback(t *testing.T) {
func TestFreezerConcurrentModifyRetrieve(t *testing.T) { func TestFreezerConcurrentModifyRetrieve(t *testing.T) {
t.Parallel() t.Parallel()
f, dir := newFreezerForTesting(t, freezerTestTableDef) f, _ := newFreezerForTesting(t, freezerTestTableDef)
defer os.RemoveAll(dir)
defer f.Close() defer f.Close()
var ( var (
@ -189,8 +185,7 @@ func TestFreezerConcurrentModifyRetrieve(t *testing.T) {
// This test runs ModifyAncients and TruncateHead concurrently with each other. // This test runs ModifyAncients and TruncateHead concurrently with each other.
func TestFreezerConcurrentModifyTruncate(t *testing.T) { func TestFreezerConcurrentModifyTruncate(t *testing.T) {
f, dir := newFreezerForTesting(t, freezerTestTableDef) f, _ := newFreezerForTesting(t, freezerTestTableDef)
defer os.RemoveAll(dir)
defer f.Close() defer f.Close()
var item = make([]byte, 256) var item = make([]byte, 256)
@ -256,11 +251,7 @@ func TestFreezerConcurrentModifyTruncate(t *testing.T) {
func TestFreezerReadonlyValidate(t *testing.T) { func TestFreezerReadonlyValidate(t *testing.T) {
tables := map[string]bool{"a": true, "b": true} tables := map[string]bool{"a": true, "b": true}
dir, err := ioutil.TempDir("", "freezer") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
// Open non-readonly freezer and fill individual tables // Open non-readonly freezer and fill individual tables
// with different amount of data. // with different amount of data.
f, err := newFreezer(dir, "", false, 2049, tables) f, err := newFreezer(dir, "", false, 2049, tables)
@ -295,10 +286,7 @@ func TestFreezerReadonlyValidate(t *testing.T) {
func newFreezerForTesting(t *testing.T, tables map[string]bool) (*freezer, string) { func newFreezerForTesting(t *testing.T, tables map[string]bool) (*freezer, string) {
t.Helper() t.Helper()
dir, err := ioutil.TempDir("", "freezer") dir := t.TempDir()
if err != nil {
t.Fatal(err)
}
// note: using low max table size here to ensure the tests actually // note: using low max table size here to ensure the tests actually
// switch between multiple files. // switch between multiple files.
f, err := newFreezer(dir, "", false, 2049, tables) f, err := newFreezer(dir, "", false, 2049, tables)
@ -350,16 +338,8 @@ func TestRenameWindows(t *testing.T) {
) )
// Create 2 temp dirs // Create 2 temp dirs
dir1, err := os.MkdirTemp("", "rename-test") dir1 := t.TempDir()
if err != nil { dir2 := t.TempDir()
t.Fatal(err)
}
defer os.Remove(dir1)
dir2, err := os.MkdirTemp("", "rename-test")
if err != nil {
t.Fatal(err)
}
defer os.Remove(dir2)
// Create file in dir1 and fill with data // Create file in dir1 and fill with data
f, err := os.Create(path.Join(dir1, fname)) f, err := os.Create(path.Join(dir1, fname))

View File

@ -18,14 +18,11 @@ package snapshot
import ( import (
"bytes" "bytes"
"io/ioutil"
"os"
"testing" "testing"
"github.com/VictoriaMetrics/fastcache" "github.com/VictoriaMetrics/fastcache"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethdb/leveldb" "github.com/ethereum/go-ethereum/ethdb/leveldb"
"github.com/ethereum/go-ethereum/ethdb/memorydb" "github.com/ethereum/go-ethereum/ethdb/memorydb"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
@ -518,18 +515,13 @@ func TestDiskMidAccountPartialMerge(t *testing.T) {
// TestDiskSeek tests that seek-operations work on the disk layer // TestDiskSeek tests that seek-operations work on the disk layer
func TestDiskSeek(t *testing.T) { func TestDiskSeek(t *testing.T) {
// Create some accounts in the disk layer // Create some accounts in the disk layer
var db ethdb.Database diskdb, err := leveldb.New(t.TempDir(), 256, 0, "", false)
if err != nil {
if dir, err := ioutil.TempDir("", "disklayer-test"); err != nil {
t.Fatal(err) t.Fatal(err)
} else {
defer os.RemoveAll(dir)
diskdb, err := leveldb.New(dir, 256, 0, "", false)
if err != nil {
t.Fatal(err)
}
db = rawdb.NewDatabase(diskdb)
} }
db := rawdb.NewDatabase(diskdb)
defer db.Close()
// Fill even keys [0,2,4...] // Fill even keys [0,2,4...]
for i := 0; i < 0xff; i += 2 { for i := 0; i < 0xff; i += 2 {
acc := common.Hash{byte(i)} acc := common.Hash{byte(i)}

View File

@ -19,7 +19,6 @@ package downloader
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"strings" "strings"
@ -55,20 +54,20 @@ type downloadTester struct {
} }
// newTester creates a new downloader test mocker. // newTester creates a new downloader test mocker.
func newTester() *downloadTester { func newTester(t *testing.T) *downloadTester {
return newTesterWithNotification(nil) return newTesterWithNotification(t, nil)
} }
// newTester creates a new downloader test mocker. // newTester creates a new downloader test mocker.
func newTesterWithNotification(success func()) *downloadTester { func newTesterWithNotification(t *testing.T, success func()) *downloadTester {
freezer, err := ioutil.TempDir("", "") freezer := t.TempDir()
if err != nil {
panic(err)
}
db, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), freezer, "", false) db, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), freezer, "", false)
if err != nil { if err != nil {
panic(err) panic(err)
} }
t.Cleanup(func() {
db.Close()
})
core.GenesisBlockForTesting(db, testAddress, big.NewInt(1000000000000000)) core.GenesisBlockForTesting(db, testAddress, big.NewInt(1000000000000000))
chain, err := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil) chain, err := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
@ -440,7 +439,7 @@ func TestCanonicalSynchronisation66Snap(t *testing.T) { testCanonSync(t, eth.ET
func TestCanonicalSynchronisation66Light(t *testing.T) { testCanonSync(t, eth.ETH66, LightSync) } func TestCanonicalSynchronisation66Light(t *testing.T) { testCanonSync(t, eth.ETH66, LightSync) }
func testCanonSync(t *testing.T, protocol uint, mode SyncMode) { func testCanonSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
// Create a small enough block chain to download // Create a small enough block chain to download
@ -460,7 +459,7 @@ func TestThrottling66Full(t *testing.T) { testThrottling(t, eth.ETH66, FullSync)
func TestThrottling66Snap(t *testing.T) { testThrottling(t, eth.ETH66, SnapSync) } func TestThrottling66Snap(t *testing.T) { testThrottling(t, eth.ETH66, SnapSync) }
func testThrottling(t *testing.T, protocol uint, mode SyncMode) { func testThrottling(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
// Create a long block chain to download and the tester // Create a long block chain to download and the tester
@ -540,7 +539,7 @@ func TestForkedSync66Snap(t *testing.T) { testForkedSync(t, eth.ETH66, SnapSync
func TestForkedSync66Light(t *testing.T) { testForkedSync(t, eth.ETH66, LightSync) } func TestForkedSync66Light(t *testing.T) { testForkedSync(t, eth.ETH66, LightSync) }
func testForkedSync(t *testing.T, protocol uint, mode SyncMode) { func testForkedSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + 80) chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + 80)
@ -567,7 +566,7 @@ func TestHeavyForkedSync66Snap(t *testing.T) { testHeavyForkedSync(t, eth.ETH66
func TestHeavyForkedSync66Light(t *testing.T) { testHeavyForkedSync(t, eth.ETH66, LightSync) } func TestHeavyForkedSync66Light(t *testing.T) { testHeavyForkedSync(t, eth.ETH66, LightSync) }
func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) { func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + 80) chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + 80)
@ -596,7 +595,7 @@ func TestBoundedForkedSync66Snap(t *testing.T) { testBoundedForkedSync(t, eth.E
func TestBoundedForkedSync66Light(t *testing.T) { testBoundedForkedSync(t, eth.ETH66, LightSync) } func TestBoundedForkedSync66Light(t *testing.T) { testBoundedForkedSync(t, eth.ETH66, LightSync) }
func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) { func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chainA := testChainForkLightA chainA := testChainForkLightA
@ -630,7 +629,7 @@ func TestBoundedHeavyForkedSync66Light(t *testing.T) {
} }
func testBoundedHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) { func testBoundedHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
// Create a long enough forked chain // Create a long enough forked chain
@ -657,7 +656,7 @@ func TestCancel66Snap(t *testing.T) { testCancel(t, eth.ETH66, SnapSync) }
func TestCancel66Light(t *testing.T) { testCancel(t, eth.ETH66, LightSync) } func TestCancel66Light(t *testing.T) { testCancel(t, eth.ETH66, LightSync) }
func testCancel(t *testing.T, protocol uint, mode SyncMode) { func testCancel(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(MaxHeaderFetch) chain := testChainBase.shorten(MaxHeaderFetch)
@ -684,7 +683,7 @@ func TestMultiSynchronisation66Snap(t *testing.T) { testMultiSynchronisation(t,
func TestMultiSynchronisation66Light(t *testing.T) { testMultiSynchronisation(t, eth.ETH66, LightSync) } func TestMultiSynchronisation66Light(t *testing.T) { testMultiSynchronisation(t, eth.ETH66, LightSync) }
func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) { func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
// Create various peers with various parts of the chain // Create various peers with various parts of the chain
@ -708,7 +707,7 @@ func TestMultiProtoSynchronisation66Snap(t *testing.T) { testMultiProtoSync(t,
func TestMultiProtoSynchronisation66Light(t *testing.T) { testMultiProtoSync(t, eth.ETH66, LightSync) } func TestMultiProtoSynchronisation66Light(t *testing.T) { testMultiProtoSync(t, eth.ETH66, LightSync) }
func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) { func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
// Create a small enough block chain to download // Create a small enough block chain to download
@ -740,7 +739,7 @@ func TestEmptyShortCircuit66Snap(t *testing.T) { testEmptyShortCircuit(t, eth.E
func TestEmptyShortCircuit66Light(t *testing.T) { testEmptyShortCircuit(t, eth.ETH66, LightSync) } func TestEmptyShortCircuit66Light(t *testing.T) { testEmptyShortCircuit(t, eth.ETH66, LightSync) }
func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) { func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
// Create a block chain to download // Create a block chain to download
@ -788,7 +787,7 @@ func TestMissingHeaderAttack66Snap(t *testing.T) { testMissingHeaderAttack(t, e
func TestMissingHeaderAttack66Light(t *testing.T) { testMissingHeaderAttack(t, eth.ETH66, LightSync) } func TestMissingHeaderAttack66Light(t *testing.T) { testMissingHeaderAttack(t, eth.ETH66, LightSync) }
func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) { func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(blockCacheMaxItems - 15) chain := testChainBase.shorten(blockCacheMaxItems - 15)
@ -814,7 +813,7 @@ func TestShiftedHeaderAttack66Snap(t *testing.T) { testShiftedHeaderAttack(t, e
func TestShiftedHeaderAttack66Light(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH66, LightSync) } func TestShiftedHeaderAttack66Light(t *testing.T) { testShiftedHeaderAttack(t, eth.ETH66, LightSync) }
func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) { func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(blockCacheMaxItems - 15) chain := testChainBase.shorten(blockCacheMaxItems - 15)
@ -840,7 +839,7 @@ func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
func TestInvalidHeaderRollback66Snap(t *testing.T) { testInvalidHeaderRollback(t, eth.ETH66, SnapSync) } func TestInvalidHeaderRollback66Snap(t *testing.T) { testInvalidHeaderRollback(t, eth.ETH66, SnapSync) }
func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) { func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
// Create a small enough block chain to download // Create a small enough block chain to download
@ -926,7 +925,7 @@ func TestHighTDStarvationAttack66Light(t *testing.T) {
} }
func testHighTDStarvationAttack(t *testing.T, protocol uint, mode SyncMode) { func testHighTDStarvationAttack(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(1) chain := testChainBase.shorten(1)
@ -962,7 +961,7 @@ func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) {
{errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop {errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
} }
// Run the tests and check disconnection status // Run the tests and check disconnection status
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(1) chain := testChainBase.shorten(1)
@ -990,7 +989,7 @@ func TestSyncProgress66Snap(t *testing.T) { testSyncProgress(t, eth.ETH66, Snap
func TestSyncProgress66Light(t *testing.T) { testSyncProgress(t, eth.ETH66, LightSync) } func TestSyncProgress66Light(t *testing.T) { testSyncProgress(t, eth.ETH66, LightSync) }
func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(blockCacheMaxItems - 15) chain := testChainBase.shorten(blockCacheMaxItems - 15)
@ -1067,7 +1066,7 @@ func TestForkedSyncProgress66Snap(t *testing.T) { testForkedSyncProgress(t, eth
func TestForkedSyncProgress66Light(t *testing.T) { testForkedSyncProgress(t, eth.ETH66, LightSync) } func TestForkedSyncProgress66Light(t *testing.T) { testForkedSyncProgress(t, eth.ETH66, LightSync) }
func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + MaxHeaderFetch) chainA := testChainForkLightA.shorten(len(testChainBase.blocks) + MaxHeaderFetch)
@ -1138,7 +1137,7 @@ func TestFailedSyncProgress66Snap(t *testing.T) { testFailedSyncProgress(t, eth
func TestFailedSyncProgress66Light(t *testing.T) { testFailedSyncProgress(t, eth.ETH66, LightSync) } func TestFailedSyncProgress66Light(t *testing.T) { testFailedSyncProgress(t, eth.ETH66, LightSync) }
func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(blockCacheMaxItems - 15) chain := testChainBase.shorten(blockCacheMaxItems - 15)
@ -1204,7 +1203,7 @@ func TestFakedSyncProgress66Snap(t *testing.T) { testFakedSyncProgress(t, eth.E
func TestFakedSyncProgress66Light(t *testing.T) { testFakedSyncProgress(t, eth.ETH66, LightSync) } func TestFakedSyncProgress66Light(t *testing.T) { testFakedSyncProgress(t, eth.ETH66, LightSync) }
func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) { func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
chain := testChainBase.shorten(blockCacheMaxItems - 15) chain := testChainBase.shorten(blockCacheMaxItems - 15)
@ -1351,7 +1350,7 @@ func TestCheckpointEnforcement66Light(t *testing.T) {
func testCheckpointEnforcement(t *testing.T, protocol uint, mode SyncMode) { func testCheckpointEnforcement(t *testing.T, protocol uint, mode SyncMode) {
// Create a new tester with a particular hard coded checkpoint block // Create a new tester with a particular hard coded checkpoint block
tester := newTester() tester := newTester(t)
defer tester.terminate() defer tester.terminate()
tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256 tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256
@ -1394,7 +1393,7 @@ func testBeaconSync(t *testing.T, protocol uint, mode SyncMode) {
for _, c := range cases { for _, c := range cases {
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
success := make(chan struct{}) success := make(chan struct{})
tester := newTesterWithNotification(func() { tester := newTesterWithNotification(t, func() {
close(success) close(success)
}) })
defer tester.terminate() defer tester.terminate()

View File

@ -18,9 +18,7 @@ package filters
import ( import (
"context" "context"
"io/ioutil"
"math/big" "math/big"
"os"
"testing" "testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -42,11 +40,7 @@ func makeReceipt(addr common.Address) *types.Receipt {
} }
func BenchmarkFilters(b *testing.B) { func BenchmarkFilters(b *testing.B) {
dir, err := ioutil.TempDir("", "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)
@ -100,11 +94,7 @@ func BenchmarkFilters(b *testing.B) {
} }
func TestFilters(t *testing.T) { func TestFilters(t *testing.T) {
dir, err := ioutil.TempDir("", "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

@ -40,10 +40,7 @@ import (
) )
func TestBuildSchema(t *testing.T) { func TestBuildSchema(t *testing.T) {
ddir, err := ioutil.TempDir("", "graphql-buildschema") ddir := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary datadir: %v", err)
}
// Copy config // Copy config
conf := node.DefaultConfig conf := node.DefaultConfig
conf.DataDir = ddir conf.DataDir = ddir

View File

@ -23,9 +23,7 @@
package guide package guide
import ( import (
"io/ioutil"
"math/big" "math/big"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -38,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 := ioutil.TempDir("", "") 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

@ -40,23 +40,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 := ioutil.TempDir("", "jsre-test") dir := t.TempDir()
if err != nil {
t.Fatal("cannot create temporary directory:", err)
}
if testjs != "" { if testjs != "" {
if err := ioutil.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil { if err := ioutil.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 {
@ -78,8 +74,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 {
@ -114,8 +109,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

@ -184,11 +184,7 @@ func TestAndroid(t *testing.T) {
t.Logf("initialization took %v", time.Since(start)) t.Logf("initialization took %v", time.Since(start))
} }
// Create and switch to a temporary workspace // Create and switch to a temporary workspace
workspace, err := ioutil.TempDir("", "geth-android-") workspace := t.TempDir()
if err != nil {
t.Fatalf("failed to create temporary workspace: %v", err)
}
defer os.RemoveAll(workspace)
pwd, err := os.Getwd() pwd, err := os.Getwd()
if err != nil { if err != nil {

View File

@ -32,11 +32,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 := ioutil.TempDir("", "") 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 {
@ -62,7 +58,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})
@ -109,11 +108,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 := ioutil.TempDir("", "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

@ -20,10 +20,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"os"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
@ -88,11 +86,7 @@ func TestNodeStartMultipleTimes(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 := ioutil.TempDir("", "") 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

@ -19,9 +19,7 @@ package enode
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"testing" "testing"
@ -300,11 +298,7 @@ func testSeedQuery() error {
} }
func TestDBPersistency(t *testing.T) { func TestDBPersistency(t *testing.T) {
root, err := ioutil.TempDir("", "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

@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"path/filepath" "path/filepath"
@ -109,11 +108,8 @@ func (ui *headlessUi) ShowInfo(message string) {
} }
func tmpDirName(t *testing.T) string { func tmpDirName(t *testing.T) string {
d, err := ioutil.TempDir("", "eth-keystore-test") d := t.TempDir()
if err != nil { d, err := filepath.EvalSymlinks(d)
t.Fatal(err)
}
d, err = filepath.EvalSymlinks(d)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -18,7 +18,6 @@ package fourbyte
import ( import (
"fmt" "fmt"
"io/ioutil"
"strings" "strings"
"testing" "testing"
@ -57,10 +56,7 @@ func TestEmbeddedDatabase(t *testing.T) {
// Tests that custom 4byte datasets can be handled too. // Tests that custom 4byte datasets can be handled too.
func TestCustomDatabase(t *testing.T) { func TestCustomDatabase(t *testing.T) {
// Create a new custom 4byte database with no embedded component // Create a new custom 4byte database with no embedded component
tmpdir, err := ioutil.TempDir("", "signer-4byte-test") tmpdir := t.TempDir()
if err != nil {
t.Fatal(err)
}
filename := fmt.Sprintf("%s/4byte_custom.json", tmpdir) filename := fmt.Sprintf("%s/4byte_custom.json", tmpdir)
db, err := NewWithFile(filename) db, err := NewWithFile(filename)

View File

@ -62,10 +62,7 @@ func TestFileStorage(t *testing.T) {
CipherText: common.Hex2Bytes("2df87baf86b5073ef1f03e3cc738de75b511400f5465bb0ddeacf47ae4dc267d"), CipherText: common.Hex2Bytes("2df87baf86b5073ef1f03e3cc738de75b511400f5465bb0ddeacf47ae4dc267d"),
}, },
} }
d, err := ioutil.TempDir("", "eth-encrypted-storage-test") d := t.TempDir()
if err != nil {
t.Fatal(err)
}
stored := &AESEncryptedStorage{ stored := &AESEncryptedStorage{
filename: fmt.Sprintf("%v/vault.json", d), filename: fmt.Sprintf("%v/vault.json", d),
key: []byte("AES256Key-32Characters1234567890"), key: []byte("AES256Key-32Characters1234567890"),
@ -95,10 +92,7 @@ func TestFileStorage(t *testing.T) {
func TestEnd2End(t *testing.T) { func TestEnd2End(t *testing.T) {
log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(3), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true)))) log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(3), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
d, err := ioutil.TempDir("", "eth-encrypted-storage-test") d := t.TempDir()
if err != nil {
t.Fatal(err)
}
s1 := &AESEncryptedStorage{ s1 := &AESEncryptedStorage{
filename: fmt.Sprintf("%v/vault.json", d), filename: fmt.Sprintf("%v/vault.json", d),
@ -120,10 +114,7 @@ func TestSwappedKeys(t *testing.T) {
// K1:V1, K2:V2 can be swapped into K1:V2, K2:V1 // K1:V1, K2:V2 can be swapped into K1:V2, K2:V1
log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(3), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true)))) log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(3), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
d, err := ioutil.TempDir("", "eth-encrypted-storage-test") d := t.TempDir()
if err != nil {
t.Fatal(err)
}
s1 := &AESEncryptedStorage{ s1 := &AESEncryptedStorage{
filename: fmt.Sprintf("%v/vault.json", d), filename: fmt.Sprintf("%v/vault.json", d),

View File

@ -22,7 +22,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"hash" "hash"
"io/ioutil"
"math/big" "math/big"
"math/rand" "math/rand"
"os" "os"
@ -545,7 +544,7 @@ const benchElemCount = 20000
func benchGet(b *testing.B, commit bool) { func benchGet(b *testing.B, commit bool) {
trie, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase())) trie, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()))
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)
@ -1115,16 +1114,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 := ioutil.TempDir("", "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 {