Use the T.TempDir and B.TempDir to create temp dirs for testing (#10560)

* Use t.TempDir and b.TempDir for temporary test dirs

* Remove redundant dir cleanup
This commit is contained in:
Håvard Anda Estensen 2022-04-21 22:45:44 +02:00 committed by GitHub
parent 21fc9853ee
commit 2fd7c926ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 10 additions and 62 deletions

View File

@ -3,7 +3,6 @@ package node
import ( import (
"flag" "flag"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -41,7 +40,6 @@ func TestNodeClose_OK(t *testing.T) {
node.Close() node.Close()
require.LogsContain(t, hook, "Stopping beacon node") require.LogsContain(t, hook, "Stopping beacon node")
require.NoError(t, os.RemoveAll(tmp))
} }
// TestClearDB tests clearing the database // TestClearDB tests clearing the database
@ -67,5 +65,4 @@ func TestClearDB(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.LogsContain(t, hook, "Removing database") require.LogsContain(t, hook, "Removing database")
require.NoError(t, os.RemoveAll(tmp))
} }

View File

@ -3,7 +3,6 @@ package powchaincmd
import ( import (
"flag" "flag"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -53,13 +52,8 @@ func Test_parseJWTSecretFromFile(t *testing.T) {
t.Run("empty string in file", func(t *testing.T) { t.Run("empty string in file", func(t *testing.T) {
app := cli.App{} app := cli.App{}
set := flag.NewFlagSet("test", 0) set := flag.NewFlagSet("test", 0)
fullPath := filepath.Join(os.TempDir(), "foohex") fullPath := filepath.Join(t.TempDir(), "foohex")
require.NoError(t, file.WriteFile(fullPath, []byte{})) require.NoError(t, file.WriteFile(fullPath, []byte{}))
t.Cleanup(func() {
if err := os.RemoveAll(fullPath); err != nil {
t.Fatalf("Could not delete temp dir: %v", err)
}
})
set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "") set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "")
ctx := cli.NewContext(&app, set, nil) ctx := cli.NewContext(&app, set, nil)
_, err := parseJWTSecretFromFile(ctx) _, err := parseJWTSecretFromFile(ctx)
@ -68,15 +62,10 @@ func Test_parseJWTSecretFromFile(t *testing.T) {
t.Run("less than 32 bytes", func(t *testing.T) { t.Run("less than 32 bytes", func(t *testing.T) {
app := cli.App{} app := cli.App{}
set := flag.NewFlagSet("test", 0) set := flag.NewFlagSet("test", 0)
fullPath := filepath.Join(os.TempDir(), "foohex") fullPath := filepath.Join(t.TempDir(), "foohex")
secret := bytesutil.PadTo([]byte("foo"), 31) secret := bytesutil.PadTo([]byte("foo"), 31)
hexData := fmt.Sprintf("%#x", secret) hexData := fmt.Sprintf("%#x", secret)
require.NoError(t, file.WriteFile(fullPath, []byte(hexData))) require.NoError(t, file.WriteFile(fullPath, []byte(hexData)))
t.Cleanup(func() {
if err := os.RemoveAll(fullPath); err != nil {
t.Fatalf("Could not delete temp dir: %v", err)
}
})
set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "") set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "")
ctx := cli.NewContext(&app, set, nil) ctx := cli.NewContext(&app, set, nil)
_, err := parseJWTSecretFromFile(ctx) _, err := parseJWTSecretFromFile(ctx)
@ -85,14 +74,9 @@ func Test_parseJWTSecretFromFile(t *testing.T) {
t.Run("bad data", func(t *testing.T) { t.Run("bad data", func(t *testing.T) {
app := cli.App{} app := cli.App{}
set := flag.NewFlagSet("test", 0) set := flag.NewFlagSet("test", 0)
fullPath := filepath.Join(os.TempDir(), "foohex") fullPath := filepath.Join(t.TempDir(), "foohex")
secret := []byte("foo") secret := []byte("foo")
require.NoError(t, file.WriteFile(fullPath, secret)) require.NoError(t, file.WriteFile(fullPath, secret))
t.Cleanup(func() {
if err := os.RemoveAll(fullPath); err != nil {
t.Fatalf("Could not delete temp dir: %v", err)
}
})
set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "") set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "")
ctx := cli.NewContext(&app, set, nil) ctx := cli.NewContext(&app, set, nil)
_, err := parseJWTSecretFromFile(ctx) _, err := parseJWTSecretFromFile(ctx)
@ -101,15 +85,10 @@ func Test_parseJWTSecretFromFile(t *testing.T) {
t.Run("correct format", func(t *testing.T) { t.Run("correct format", func(t *testing.T) {
app := cli.App{} app := cli.App{}
set := flag.NewFlagSet("test", 0) set := flag.NewFlagSet("test", 0)
fullPath := filepath.Join(os.TempDir(), "foohex") fullPath := filepath.Join(t.TempDir(), "foohex")
secret := bytesutil.ToBytes32([]byte("foo")) secret := bytesutil.ToBytes32([]byte("foo"))
secretHex := fmt.Sprintf("%#x", secret) secretHex := fmt.Sprintf("%#x", secret)
require.NoError(t, file.WriteFile(fullPath, []byte(secretHex))) require.NoError(t, file.WriteFile(fullPath, []byte(secretHex)))
t.Cleanup(func() {
if err := os.RemoveAll(fullPath); err != nil {
t.Fatalf("Could not delete temp dir: %v", err)
}
})
set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "") set.String(flags.ExecutionJWTSecretFlag.Name, fullPath, "")
ctx := cli.NewContext(&app, set, nil) ctx := cli.NewContext(&app, set, nil)
got, err := parseJWTSecretFromFile(ctx) got, err := parseJWTSecretFromFile(ctx)

View File

@ -3,7 +3,6 @@ package historycmd
import ( import (
"encoding/json" "encoding/json"
"flag" "flag"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -38,7 +37,7 @@ func setupCliCtx(
func TestImportExportSlashingProtectionCli_RoundTrip(t *testing.T) { func TestImportExportSlashingProtectionCli_RoundTrip(t *testing.T) {
numValidators := 10 numValidators := 10
outputPath := filepath.Join(os.TempDir(), "slashing-exports") outputPath := filepath.Join(t.TempDir(), "slashing-exports")
err := file.MkdirAll(outputPath) err := file.MkdirAll(outputPath)
require.NoError(t, err) require.NoError(t, err)
protectionFileName := "slashing_history_import.json" protectionFileName := "slashing_history_import.json"
@ -111,7 +110,7 @@ func TestImportExportSlashingProtectionCli_RoundTrip(t *testing.T) {
func TestImportExportSlashingProtectionCli_EmptyData(t *testing.T) { func TestImportExportSlashingProtectionCli_EmptyData(t *testing.T) {
numValidators := 10 numValidators := 10
outputPath := filepath.Join(os.TempDir(), "slashing-exports") outputPath := filepath.Join(t.TempDir(), "slashing-exports")
err := file.MkdirAll(outputPath) err := file.MkdirAll(outputPath)
require.NoError(t, err) require.NoError(t, err)
protectionFileName := "slashing_history_import.json" protectionFileName := "slashing_history_import.json"

View File

@ -413,13 +413,8 @@ func TestHasReadWritePermissions(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
fullPath := filepath.Join(os.TempDir(), tt.args.itemPath) fullPath := filepath.Join(t.TempDir(), tt.args.itemPath)
require.NoError(t, os.WriteFile(fullPath, []byte("foo"), tt.args.perms)) require.NoError(t, os.WriteFile(fullPath, []byte("foo"), tt.args.perms))
t.Cleanup(func() {
if err := os.RemoveAll(fullPath); err != nil {
t.Fatalf("Could not delete temp dir: %v", err)
}
})
got, err := file.HasReadWritePermissions(fullPath) got, err := file.HasReadWritePermissions(fullPath)
if (err != nil) != tt.wantErr { if (err != nil) != tt.wantErr {
t.Errorf("HasReadWritePermissions() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("HasReadWritePermissions() error = %v, wantErr %v", err, tt.wantErr)

View File

@ -20,10 +20,7 @@ type sampleRPCRequest struct {
} }
func Test_parseAndCaptureRequest(t *testing.T) { func Test_parseAndCaptureRequest(t *testing.T) {
tmpFile := filepath.Join(os.TempDir(), "faketest.log") tmpFile := filepath.Join(t.TempDir(), "faketest.log")
t.Cleanup(func() {
require.NoError(t, os.RemoveAll(tmpFile))
})
body := &sampleRPCRequest{ body := &sampleRPCRequest{
Name: "eth2", Name: "eth2",
ETHMethod: "eth2_produceBlock", ETHMethod: "eth2_produceBlock",

View File

@ -5,7 +5,6 @@ import (
"context" "context"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
@ -55,10 +54,7 @@ func Test_generateKeysFromMnemonicList(t *testing.T) {
func Test_spreadKeysAcrossImportedWallets(t *testing.T) { func Test_spreadKeysAcrossImportedWallets(t *testing.T) {
walletPassword := "Sr0ngPass0q0z929301" walletPassword := "Sr0ngPass0q0z929301"
tmpDir := filepath.Join(os.TempDir(), "testwallets") tmpDir := filepath.Join(t.TempDir(), "testwallets")
t.Cleanup(func() {
require.NoError(t, os.RemoveAll(tmpDir))
})
// Spread 5 keys across 5 wallets, meaning there is 1 // Spread 5 keys across 5 wallets, meaning there is 1
// key per wallet stored on disk. // key per wallet stored on disk.

View File

@ -3,7 +3,6 @@ package kv
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"sync" "sync"
"testing" "testing"
@ -501,7 +500,7 @@ func benchCheckSurroundVote(
shouldSurround bool, shouldSurround bool,
) { ) {
ctx := context.Background() ctx := context.Background()
validatorDB, err := NewKVStore(ctx, filepath.Join(os.TempDir(), "benchsurroundvote"), &Config{ validatorDB, err := NewKVStore(ctx, filepath.Join(b.TempDir(), "benchsurroundvote"), &Config{
PubKeys: pubKeys, PubKeys: pubKeys,
}) })
require.NoError(b, err, "Failed to instantiate DB") require.NoError(b, err, "Failed to instantiate DB")

View File

@ -16,9 +16,6 @@ import (
func setupWalletDir(t testing.TB) string { func setupWalletDir(t testing.TB) string {
walletDir := filepath.Join(t.TempDir(), "wallet") walletDir := filepath.Join(t.TempDir(), "wallet")
require.NoError(t, os.MkdirAll(walletDir, os.ModePerm)) require.NoError(t, os.MkdirAll(walletDir, os.ModePerm))
t.Cleanup(func() {
require.NoError(t, os.RemoveAll(walletDir))
})
return walletDir return walletDir
} }
@ -102,7 +99,6 @@ func Test_initializeAuthToken(t *testing.T) {
// Deleting the auth token and re-initializing means we create a jwt token // Deleting the auth token and re-initializing means we create a jwt token
// and secret from scratch again. // and secret from scratch again.
require.NoError(t, os.RemoveAll(walletDir))
srv3 := &Server{} srv3 := &Server{}
walletDir = setupWalletDir(t) walletDir = setupWalletDir(t)
token3, err := srv3.initializeAuthToken(walletDir) token3, err := srv3.initializeAuthToken(walletDir)

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -62,9 +61,6 @@ func TestServer_CreateWallet_Local(t *testing.T) {
Keymanager: pb.KeymanagerKind_IMPORTED, Keymanager: pb.KeymanagerKind_IMPORTED,
WalletPassword: strongPass, WalletPassword: strongPass,
} }
// We delete the directory at defaultWalletPath as CreateWallet will return an error if it tries to create a wallet
// where a directory already exists
require.NoError(t, os.RemoveAll(defaultWalletPath))
_, err = s.CreateWallet(ctx, req) _, err = s.CreateWallet(ctx, req)
require.NoError(t, err) require.NoError(t, err)
@ -113,9 +109,6 @@ func TestServer_CreateWallet_Local_PasswordTooWeak(t *testing.T) {
Keymanager: pb.KeymanagerKind_IMPORTED, Keymanager: pb.KeymanagerKind_IMPORTED,
WalletPassword: "", // Weak password, empty string WalletPassword: "", // Weak password, empty string
} }
// We delete the directory at defaultWalletPath as CreateWallet will return an error if it tries to create a wallet
// where a directory already exists
require.NoError(t, os.RemoveAll(defaultWalletPath))
_, err := s.CreateWallet(ctx, req) _, err := s.CreateWallet(ctx, req)
require.ErrorContains(t, "Password too weak", err) require.ErrorContains(t, "Password too weak", err)
@ -138,9 +131,6 @@ func TestServer_RecoverWallet_Derived(t *testing.T) {
WalletPassword: strongPass, WalletPassword: strongPass,
NumAccounts: 0, NumAccounts: 0,
} }
// We delete the directory at defaultWalletPath as RecoverWallet will return an error if it tries to create a wallet
// where a directory already exists
require.NoError(t, os.RemoveAll(localWalletDir))
_, err := s.RecoverWallet(ctx, req) _, err := s.RecoverWallet(ctx, req)
require.ErrorContains(t, "Must create at least 1 validator account", err) require.ErrorContains(t, "Must create at least 1 validator account", err)