Skip to content

Commit 8d066f1

Browse files
authored
all: use T.TempDir to create temporary test directories (ethereum#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>
1 parent bf5cacf commit 8d066f1

34 files changed

+140
-372
lines changed

accounts/abi/bind/bind_test.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1966,14 +1966,10 @@ func TestGolangBindings(t *testing.T) {
19661966
t.Skip("go sdk not found for testing")
19671967
}
19681968
// Create a temporary workspace for the test suite
1969-
ws, err := ioutil.TempDir("", "binding-test")
1970-
if err != nil {
1971-
t.Fatalf("failed to create temporary workspace: %v", err)
1972-
}
1973-
//defer os.RemoveAll(ws)
1969+
ws := t.TempDir()
19741970

19751971
pkg := filepath.Join(ws, "bindtest")
1976-
if err = os.MkdirAll(pkg, 0700); err != nil {
1972+
if err := os.MkdirAll(pkg, 0700); err != nil {
19771973
t.Fatalf("failed to create package: %v", err)
19781974
}
19791975
// Generate the test suite for all the contracts

accounts/keystore/account_cache_test.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ func TestWatchNewFile(t *testing.T) {
5555
t.Parallel()
5656

5757
dir, ks := tmpKeyStore(t, false)
58-
defer os.RemoveAll(dir)
5958

6059
// Ensure the watcher is started before adding any files.
6160
ks.Accounts()

accounts/keystore/keystore_test.go

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package keystore
1818

1919
import (
20-
"io/ioutil"
2120
"math/rand"
2221
"os"
2322
"runtime"
@@ -38,7 +37,6 @@ var testSigData = make([]byte, 32)
3837

3938
func TestKeyStore(t *testing.T) {
4039
dir, ks := tmpKeyStore(t, true)
41-
defer os.RemoveAll(dir)
4240

4341
a, err := ks.NewAccount("foo")
4442
if err != nil {
@@ -72,8 +70,7 @@ func TestKeyStore(t *testing.T) {
7270
}
7371

7472
func TestSign(t *testing.T) {
75-
dir, ks := tmpKeyStore(t, true)
76-
defer os.RemoveAll(dir)
73+
_, ks := tmpKeyStore(t, true)
7774

7875
pass := "" // not used but required by API
7976
a1, err := ks.NewAccount(pass)
@@ -89,8 +86,7 @@ func TestSign(t *testing.T) {
8986
}
9087

9188
func TestSignWithPassphrase(t *testing.T) {
92-
dir, ks := tmpKeyStore(t, true)
93-
defer os.RemoveAll(dir)
89+
_, ks := tmpKeyStore(t, true)
9490

9591
pass := "passwd"
9692
acc, err := ks.NewAccount(pass)
@@ -117,8 +113,7 @@ func TestSignWithPassphrase(t *testing.T) {
117113
}
118114

119115
func TestTimedUnlock(t *testing.T) {
120-
dir, ks := tmpKeyStore(t, true)
121-
defer os.RemoveAll(dir)
116+
_, ks := tmpKeyStore(t, true)
122117

123118
pass := "foo"
124119
a1, err := ks.NewAccount(pass)
@@ -152,8 +147,7 @@ func TestTimedUnlock(t *testing.T) {
152147
}
153148

154149
func TestOverrideUnlock(t *testing.T) {
155-
dir, ks := tmpKeyStore(t, false)
156-
defer os.RemoveAll(dir)
150+
_, ks := tmpKeyStore(t, false)
157151

158152
pass := "foo"
159153
a1, err := ks.NewAccount(pass)
@@ -193,8 +187,7 @@ func TestOverrideUnlock(t *testing.T) {
193187

194188
// This test should fail under -race if signing races the expiration goroutine.
195189
func TestSignRace(t *testing.T) {
196-
dir, ks := tmpKeyStore(t, false)
197-
defer os.RemoveAll(dir)
190+
_, ks := tmpKeyStore(t, false)
198191

199192
// Create a test account.
200193
a1, err := ks.NewAccount("")
@@ -222,8 +215,7 @@ func TestSignRace(t *testing.T) {
222215
// addition and removal of wallet event subscriptions.
223216
func TestWalletNotifierLifecycle(t *testing.T) {
224217
// Create a temporary kesytore to test with
225-
dir, ks := tmpKeyStore(t, false)
226-
defer os.RemoveAll(dir)
218+
_, ks := tmpKeyStore(t, false)
227219

228220
// Ensure that the notification updater is not running yet
229221
time.Sleep(250 * time.Millisecond)
@@ -283,8 +275,7 @@ type walletEvent struct {
283275
// Tests that wallet notifications and correctly fired when accounts are added
284276
// or deleted from the keystore.
285277
func TestWalletNotifications(t *testing.T) {
286-
dir, ks := tmpKeyStore(t, false)
287-
defer os.RemoveAll(dir)
278+
_, ks := tmpKeyStore(t, false)
288279

289280
// Subscribe to the wallet feed and collect events.
290281
var (
@@ -345,8 +336,7 @@ func TestWalletNotifications(t *testing.T) {
345336

346337
// TestImportExport tests the import functionality of a keystore.
347338
func TestImportECDSA(t *testing.T) {
348-
dir, ks := tmpKeyStore(t, true)
349-
defer os.RemoveAll(dir)
339+
_, ks := tmpKeyStore(t, true)
350340
key, err := crypto.GenerateKey()
351341
if err != nil {
352342
t.Fatalf("failed to generate key: %v", key)
@@ -364,8 +354,7 @@ func TestImportECDSA(t *testing.T) {
364354

365355
// TestImportECDSA tests the import and export functionality of a keystore.
366356
func TestImportExport(t *testing.T) {
367-
dir, ks := tmpKeyStore(t, true)
368-
defer os.RemoveAll(dir)
357+
_, ks := tmpKeyStore(t, true)
369358
acc, err := ks.NewAccount("old")
370359
if err != nil {
371360
t.Fatalf("failed to create account: %v", acc)
@@ -374,8 +363,7 @@ func TestImportExport(t *testing.T) {
374363
if err != nil {
375364
t.Fatalf("failed to export account: %v", acc)
376365
}
377-
dir2, ks2 := tmpKeyStore(t, true)
378-
defer os.RemoveAll(dir2)
366+
_, ks2 := tmpKeyStore(t, true)
379367
if _, err = ks2.Import(json, "old", "old"); err == nil {
380368
t.Errorf("importing with invalid password succeeded")
381369
}
@@ -395,8 +383,7 @@ func TestImportExport(t *testing.T) {
395383
// TestImportRace tests the keystore on races.
396384
// This test should fail under -race if importing races.
397385
func TestImportRace(t *testing.T) {
398-
dir, ks := tmpKeyStore(t, true)
399-
defer os.RemoveAll(dir)
386+
_, ks := tmpKeyStore(t, true)
400387
acc, err := ks.NewAccount("old")
401388
if err != nil {
402389
t.Fatalf("failed to create account: %v", acc)
@@ -405,8 +392,7 @@ func TestImportRace(t *testing.T) {
405392
if err != nil {
406393
t.Fatalf("failed to export account: %v", acc)
407394
}
408-
dir2, ks2 := tmpKeyStore(t, true)
409-
defer os.RemoveAll(dir2)
395+
_, ks2 := tmpKeyStore(t, true)
410396
var atom uint32
411397
var wg sync.WaitGroup
412398
wg.Add(2)
@@ -462,10 +448,7 @@ func checkEvents(t *testing.T, want []walletEvent, have []walletEvent) {
462448
}
463449

464450
func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
465-
d, err := ioutil.TempDir("", "eth-keystore-test")
466-
if err != nil {
467-
t.Fatal(err)
468-
}
451+
d := t.TempDir()
469452
newKs := NewPlaintextKeyStore
470453
if encrypted {
471454
newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }

accounts/keystore/plain_test.go

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ import (
2020
"crypto/rand"
2121
"encoding/hex"
2222
"fmt"
23-
"io/ioutil"
24-
"os"
2523
"path/filepath"
2624
"reflect"
2725
"strings"
@@ -32,10 +30,7 @@ import (
3230
)
3331

3432
func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) {
35-
d, err := ioutil.TempDir("", "geth-keystore-test")
36-
if err != nil {
37-
t.Fatal(err)
38-
}
33+
d := t.TempDir()
3934
if encrypted {
4035
ks = &keyStorePassphrase{d, veryLightScryptN, veryLightScryptP, true}
4136
} else {
@@ -45,8 +40,7 @@ func tmpKeyStoreIface(t *testing.T, encrypted bool) (dir string, ks keyStore) {
4540
}
4641

4742
func TestKeyStorePlain(t *testing.T) {
48-
dir, ks := tmpKeyStoreIface(t, false)
49-
defer os.RemoveAll(dir)
43+
_, ks := tmpKeyStoreIface(t, false)
5044

5145
pass := "" // not used but required by API
5246
k1, account, err := storeNewKey(ks, rand.Reader, pass)
@@ -66,8 +60,7 @@ func TestKeyStorePlain(t *testing.T) {
6660
}
6761

6862
func TestKeyStorePassphrase(t *testing.T) {
69-
dir, ks := tmpKeyStoreIface(t, true)
70-
defer os.RemoveAll(dir)
63+
_, ks := tmpKeyStoreIface(t, true)
7164

7265
pass := "foo"
7366
k1, account, err := storeNewKey(ks, rand.Reader, pass)
@@ -87,8 +80,7 @@ func TestKeyStorePassphrase(t *testing.T) {
8780
}
8881

8982
func TestKeyStorePassphraseDecryptionFail(t *testing.T) {
90-
dir, ks := tmpKeyStoreIface(t, true)
91-
defer os.RemoveAll(dir)
83+
_, ks := tmpKeyStoreIface(t, true)
9284

9385
pass := "foo"
9486
k1, account, err := storeNewKey(ks, rand.Reader, pass)
@@ -102,7 +94,6 @@ func TestKeyStorePassphraseDecryptionFail(t *testing.T) {
10294

10395
func TestImportPreSaleKey(t *testing.T) {
10496
dir, ks := tmpKeyStoreIface(t, true)
105-
defer os.RemoveAll(dir)
10697

10798
// file content of a presale key file generated with:
10899
// python pyethsaletool.py genwallet

cmd/ethkey/message_test.go

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,12 @@
1717
package main
1818

1919
import (
20-
"io/ioutil"
21-
"os"
2220
"path/filepath"
2321
"testing"
2422
)
2523

2624
func TestMessageSignVerify(t *testing.T) {
27-
tmpdir, err := ioutil.TempDir("", "ethkey-test")
28-
if err != nil {
29-
t.Fatal("Can't create temporary directory:", err)
30-
}
31-
defer os.RemoveAll(tmpdir)
25+
tmpdir := t.TempDir()
3226

3327
keyfile := filepath.Join(tmpdir, "the-keyfile")
3428
message := "test message"

cmd/geth/accountcmd_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ import (
3333
// are copied into a temporary keystore directory.
3434

3535
func tmpDatadirWithKeystore(t *testing.T) string {
36-
datadir := tmpdir(t)
36+
datadir := t.TempDir()
3737
keystore := filepath.Join(datadir, "keystore")
3838
source := filepath.Join("..", "..", "accounts", "keystore", "testdata", "keystore")
3939
if err := cp.CopyAll(keystore, source); err != nil {
@@ -111,7 +111,7 @@ func TestAccountImport(t *testing.T) {
111111
}
112112

113113
func importAccountWithExpect(t *testing.T, key string, expected string) {
114-
dir := tmpdir(t)
114+
dir := t.TempDir()
115115
keyfile := filepath.Join(dir, "key.prv")
116116
if err := ioutil.WriteFile(keyfile, []byte(key), 0600); err != nil {
117117
t.Error(err)

cmd/geth/consolecmd_test.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package main
1919
import (
2020
"crypto/rand"
2121
"math/big"
22-
"os"
2322
"path/filepath"
2423
"runtime"
2524
"strconv"
@@ -92,9 +91,7 @@ func TestAttachWelcome(t *testing.T) {
9291
if runtime.GOOS == "windows" {
9392
ipc = `\\.\pipe\geth` + strconv.Itoa(trulyRandInt(100000, 999999))
9493
} else {
95-
ws := tmpdir(t)
96-
defer os.RemoveAll(ws)
97-
ipc = filepath.Join(ws, "geth.ipc")
94+
ipc = filepath.Join(t.TempDir(), "geth.ipc")
9895
}
9996
// And HTTP + WS attachment
10097
p := trulyRandInt(1024, 65533) // Yeah, sometimes this will fail, sorry :P
@@ -118,6 +115,7 @@ func TestAttachWelcome(t *testing.T) {
118115
waitForEndpoint(t, endpoint, 3*time.Second)
119116
testAttachWelcome(t, geth, endpoint, httpAPIs)
120117
})
118+
geth.ExpectExit()
121119
}
122120

123121
func testAttachWelcome(t *testing.T, geth *testgeth, endpoint, apis string) {

cmd/geth/dao_test.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package main
1919
import (
2020
"io/ioutil"
2121
"math/big"
22-
"os"
2322
"path/filepath"
2423
"testing"
2524

@@ -106,8 +105,7 @@ func TestDAOForkBlockNewChain(t *testing.T) {
106105

107106
func testDAOForkBlockNewChain(t *testing.T, test int, genesis string, expectBlock *big.Int, expectVote bool) {
108107
// Create a temporary data directory to use and inspect later
109-
datadir := tmpdir(t)
110-
defer os.RemoveAll(datadir)
108+
datadir := t.TempDir()
111109

112110
// Start a Geth instance with the requested flags set and immediately terminate
113111
if genesis != "" {

cmd/geth/genesis_test.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ package main
1818

1919
import (
2020
"io/ioutil"
21-
"os"
2221
"path/filepath"
2322
"testing"
2423
)
@@ -73,8 +72,7 @@ var customGenesisTests = []struct {
7372
func TestCustomGenesis(t *testing.T) {
7473
for i, tt := range customGenesisTests {
7574
// Create a temporary data directory to use and inspect later
76-
datadir := tmpdir(t)
77-
defer os.RemoveAll(datadir)
75+
datadir := t.TempDir()
7876

7977
// Initialize the data directory with the custom genesis block
8078
json := filepath.Join(datadir, "genesis.json")

cmd/geth/run_test.go

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package main
1919
import (
2020
"context"
2121
"fmt"
22-
"io/ioutil"
2322
"os"
2423
"testing"
2524
"time"
@@ -29,14 +28,6 @@ import (
2928
"github.com/ethereum/go-ethereum/rpc"
3029
)
3130

32-
func tmpdir(t *testing.T) string {
33-
dir, err := ioutil.TempDir("", "geth-test")
34-
if err != nil {
35-
t.Fatal(err)
36-
}
37-
return dir
38-
}
39-
4031
type testgeth struct {
4132
*cmdtest.TestCmd
4233

@@ -82,15 +73,9 @@ func runGeth(t *testing.T, args ...string) *testgeth {
8273
}
8374
}
8475
if tt.Datadir == "" {
85-
tt.Datadir = tmpdir(t)
86-
tt.Cleanup = func() { os.RemoveAll(tt.Datadir) }
76+
// The temporary datadir will be removed automatically if something fails below.
77+
tt.Datadir = t.TempDir()
8778
args = append([]string{"--datadir", tt.Datadir}, args...)
88-
// Remove the temporary datadir if something fails below.
89-
defer func() {
90-
if t.Failed() {
91-
tt.Cleanup()
92-
}
93-
}()
9479
}
9580

9681
// Boot "geth". This actually runs the test binary but the TestMain

0 commit comments

Comments
 (0)