From e9edc5432cffce26d53906528ecd125dfae3a699 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Mon, 24 Jan 2022 22:40:34 +0800 Subject: [PATCH] *: use `T.TempDir` to create temporary test directory The directory created by `T.TempDir()` and is automatically removed when the test and all its subtests complete. Reference: https://pkg.go.dev/testing#T.TempDir Signed-off-by: Eng Zer Jun --- client/pkg/fileutil/fileutil_test.go | 38 ++--- client/pkg/fileutil/preallocate_test.go | 6 +- client/pkg/fileutil/purge_test.go | 18 +-- client/pkg/fileutil/read_dir_test.go | 6 +- .../pkg/transport/keepalive_listener_test.go | 3 +- client/pkg/transport/listener_test.go | 48 ++---- client/pkg/transport/transport_test.go | 3 +- server/embed/auth_test.go | 7 +- server/embed/serve_test.go | 8 +- .../etcdserver/api/rafthttp/snapshot_test.go | 6 +- server/etcdserver/server_test.go | 12 +- server/lease/lessor_test.go | 5 +- server/storage/wal/file_pipeline_test.go | 19 +-- server/storage/wal/repair_test.go | 12 +- server/storage/wal/wal_bench_test.go | 7 +- server/storage/wal/wal_test.go | 149 ++++-------------- tests/e2e/etcd_config_test.go | 26 +-- tests/integration/member_test.go | 7 +- tests/integration/v3_grpc_test.go | 50 ++---- tools/etcd-dump-logs/etcd-dump-log_test.go | 6 +- 20 files changed, 98 insertions(+), 338 deletions(-) diff --git a/client/pkg/fileutil/fileutil_test.go b/client/pkg/fileutil/fileutil_test.go index 995a917786a..2de28ec2e42 100644 --- a/client/pkg/fileutil/fileutil_test.go +++ b/client/pkg/fileutil/fileutil_test.go @@ -30,15 +30,11 @@ import ( ) func TestIsDirWriteable(t *testing.T) { - tmpdir, err := os.MkdirTemp("", "") - if err != nil { - t.Fatalf("unexpected os.MkdirTemp error: %v", err) - } - defer os.RemoveAll(tmpdir) - if err = IsDirWriteable(tmpdir); err != nil { + tmpdir := t.TempDir() + if err := IsDirWriteable(tmpdir); err != nil { t.Fatalf("unexpected IsDirWriteable error: %v", err) } - if err = os.Chmod(tmpdir, 0444); err != nil { + if err := os.Chmod(tmpdir, 0444); err != nil { t.Fatalf("unexpected os.Chmod error: %v", err) } me, err := user.Current() @@ -59,22 +55,18 @@ func TestIsDirWriteable(t *testing.T) { } func TestCreateDirAll(t *testing.T) { - tmpdir, err := os.MkdirTemp(os.TempDir(), "foo") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() tmpdir2 := filepath.Join(tmpdir, "testdir") - if err = CreateDirAll(zaptest.NewLogger(t), tmpdir2); err != nil { + if err := CreateDirAll(zaptest.NewLogger(t), tmpdir2); err != nil { t.Fatal(err) } - if err = os.WriteFile(filepath.Join(tmpdir2, "text.txt"), []byte("test text"), PrivateFileMode); err != nil { + if err := os.WriteFile(filepath.Join(tmpdir2, "text.txt"), []byte("test text"), PrivateFileMode); err != nil { t.Fatal(err) } - if err = CreateDirAll(zaptest.NewLogger(t), tmpdir2); err == nil || !strings.Contains(err.Error(), "to be empty, got") { + if err := CreateDirAll(zaptest.NewLogger(t), tmpdir2); err == nil || !strings.Contains(err.Error(), "to be empty, got") { t.Fatalf("unexpected error %v", err) } } @@ -107,11 +99,7 @@ func TestExist(t *testing.T) { } func TestDirEmpty(t *testing.T) { - dir, err := os.MkdirTemp(os.TempDir(), "empty_dir") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() if !DirEmpty(dir) { t.Fatalf("expected DirEmpty true, got %v", DirEmpty(dir)) @@ -177,19 +165,15 @@ func TestZeroToEnd(t *testing.T) { } func TestDirPermission(t *testing.T) { - tmpdir, err := os.MkdirTemp(os.TempDir(), "foo") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() tmpdir2 := filepath.Join(tmpdir, "testpermission") // create a new dir with 0700 - if err = CreateDirAll(zaptest.NewLogger(t), tmpdir2); err != nil { + if err := CreateDirAll(zaptest.NewLogger(t), tmpdir2); err != nil { t.Fatal(err) } // check dir permission with mode different than created dir - if err = CheckDirPermission(tmpdir2, 0600); err == nil { + if err := CheckDirPermission(tmpdir2, 0600); err == nil { t.Errorf("expected error, got nil") } } diff --git a/client/pkg/fileutil/preallocate_test.go b/client/pkg/fileutil/preallocate_test.go index a3b477365a0..47a006704b2 100644 --- a/client/pkg/fileutil/preallocate_test.go +++ b/client/pkg/fileutil/preallocate_test.go @@ -62,11 +62,7 @@ func testPreallocateFixed(t *testing.T, f *os.File) { } func runPreallocTest(t *testing.T, test func(*testing.T, *os.File)) { - p, err := os.MkdirTemp(os.TempDir(), "preallocateTest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() f, err := os.CreateTemp(p, "") if err != nil { diff --git a/client/pkg/fileutil/purge_test.go b/client/pkg/fileutil/purge_test.go index 4f2beb2785d..bafa11af716 100644 --- a/client/pkg/fileutil/purge_test.go +++ b/client/pkg/fileutil/purge_test.go @@ -26,17 +26,13 @@ import ( ) func TestPurgeFile(t *testing.T) { - dir, err := os.MkdirTemp("", "purgefile") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() // minimal file set for i := 0; i < 3; i++ { f, ferr := os.Create(filepath.Join(dir, fmt.Sprintf("%d.test", i))) if ferr != nil { - t.Fatal(err) + t.Fatal(ferr) } f.Close() } @@ -56,7 +52,7 @@ func TestPurgeFile(t *testing.T) { go func(n int) { f, ferr := os.Create(filepath.Join(dir, fmt.Sprintf("%d.test", n))) if ferr != nil { - t.Error(err) + t.Error(ferr) } f.Close() }(i) @@ -92,15 +88,11 @@ func TestPurgeFile(t *testing.T) { } func TestPurgeFileHoldingLockFile(t *testing.T) { - dir, err := os.MkdirTemp("", "purgefile") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() for i := 0; i < 10; i++ { var f *os.File - f, err = os.Create(filepath.Join(dir, fmt.Sprintf("%d.test", i))) + f, err := os.Create(filepath.Join(dir, fmt.Sprintf("%d.test", i))) if err != nil { t.Fatal(err) } diff --git a/client/pkg/fileutil/read_dir_test.go b/client/pkg/fileutil/read_dir_test.go index ecc936cb0dc..79a37d886ca 100644 --- a/client/pkg/fileutil/read_dir_test.go +++ b/client/pkg/fileutil/read_dir_test.go @@ -22,11 +22,7 @@ import ( ) func TestReadDir(t *testing.T) { - tmpdir, err := os.MkdirTemp("", "") - defer os.RemoveAll(tmpdir) - if err != nil { - t.Fatalf("unexpected os.MkdirTemp error: %v", err) - } + tmpdir := t.TempDir() files := []string{"def", "abc", "xyz", "ghi"} for _, f := range files { diff --git a/client/pkg/transport/keepalive_listener_test.go b/client/pkg/transport/keepalive_listener_test.go index 425f53368b5..d5020544e4c 100644 --- a/client/pkg/transport/keepalive_listener_test.go +++ b/client/pkg/transport/keepalive_listener_test.go @@ -49,11 +49,10 @@ func TestNewKeepAliveListener(t *testing.T) { } // tls - tlsinfo, del, err := createSelfCert() + tlsinfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create tmpfile: %v", err) } - defer del() tlsInfo := TLSInfo{CertFile: tlsinfo.CertFile, KeyFile: tlsinfo.KeyFile} tlsInfo.parseFunc = fakeCertificateParserFunc(tls.Certificate{}, nil) tlscfg, err := tlsInfo.ServerConfig() diff --git a/client/pkg/transport/listener_test.go b/client/pkg/transport/listener_test.go index f1937d694ac..b49e56fc77b 100644 --- a/client/pkg/transport/listener_test.go +++ b/client/pkg/transport/listener_test.go @@ -28,20 +28,17 @@ import ( "go.uber.org/zap/zaptest" ) -func createSelfCert(hosts ...string) (*TLSInfo, func(), error) { - return createSelfCertEx("127.0.0.1") +func createSelfCert(t *testing.T, hosts ...string) (*TLSInfo, error) { + return createSelfCertEx(t, "127.0.0.1") } -func createSelfCertEx(host string, additionalUsages ...x509.ExtKeyUsage) (*TLSInfo, func(), error) { - d, terr := os.MkdirTemp("", "etcd-test-tls-") - if terr != nil { - return nil, nil, terr - } +func createSelfCertEx(t *testing.T, host string, additionalUsages ...x509.ExtKeyUsage) (*TLSInfo, error) { + d := t.TempDir() info, err := SelfCert(zap.NewExample(), d, []string{host + ":0"}, 1, additionalUsages...) if err != nil { - return nil, nil, err + return nil, err } - return &info, func() { os.RemoveAll(d) }, nil + return &info, nil } func fakeCertificateParserFunc(cert tls.Certificate, err error) func(certPEMBlock, keyPEMBlock []byte) (tls.Certificate, error) { @@ -53,20 +50,18 @@ func fakeCertificateParserFunc(cert tls.Certificate, err error) func(certPEMBloc // TestNewListenerTLSInfo tests that NewListener with valid TLSInfo returns // a TLS listener that accepts TLS connections. func TestNewListenerTLSInfo(t *testing.T) { - tlsInfo, del, err := createSelfCert() + tlsInfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() testNewListenerTLSInfoAccept(t, *tlsInfo) } func TestNewListenerWithOpts(t *testing.T) { - tlsInfo, del, err := createSelfCert() + tlsInfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() tests := map[string]struct { opts []ListenerOption @@ -124,11 +119,10 @@ func TestNewListenerWithOpts(t *testing.T) { } func TestNewListenerWithSocketOpts(t *testing.T) { - tlsInfo, del, err := createSelfCert() + tlsInfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() tests := map[string]struct { opts []ListenerOption @@ -257,21 +251,19 @@ func TestNewListenerTLSInfoSkipClientSANVerify(t *testing.T) { } func testNewListenerTLSInfoClientCheck(t *testing.T, skipClientSANVerify, goodClientHost, acceptExpected bool) { - tlsInfo, del, err := createSelfCert() + tlsInfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() host := "127.0.0.222" if goodClientHost { host = "127.0.0.1" } - clientTLSInfo, del2, err := createSelfCertEx(host, x509.ExtKeyUsageClientAuth) + clientTLSInfo, err := createSelfCertEx(t, host, x509.ExtKeyUsageClientAuth) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del2() tlsInfo.SkipClientSANVerify = skipClientSANVerify tlsInfo.TrustedCAFile = clientTLSInfo.CertFile @@ -344,11 +336,10 @@ func TestNewListenerTLSEmptyInfo(t *testing.T) { } func TestNewTransportTLSInfo(t *testing.T) { - tlsinfo, del, err := createSelfCert() + tlsinfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() tests := []TLSInfo{ {}, @@ -416,11 +407,10 @@ func TestTLSInfoEmpty(t *testing.T) { } func TestTLSInfoMissingFields(t *testing.T) { - tlsinfo, del, err := createSelfCert() + tlsinfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() tests := []TLSInfo{ {CertFile: tlsinfo.CertFile}, @@ -441,11 +431,10 @@ func TestTLSInfoMissingFields(t *testing.T) { } func TestTLSInfoParseFuncError(t *testing.T) { - tlsinfo, del, err := createSelfCert() + tlsinfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() tests := []struct { info TLSInfo @@ -474,11 +463,10 @@ func TestTLSInfoParseFuncError(t *testing.T) { func TestTLSInfoConfigFuncs(t *testing.T) { ln := zaptest.NewLogger(t) - tlsinfo, del, err := createSelfCert() + tlsinfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() tests := []struct { info TLSInfo @@ -531,11 +519,7 @@ func TestNewListenerUnixSocket(t *testing.T) { // TestNewListenerTLSInfoSelfCert tests that a new certificate accepts connections. func TestNewListenerTLSInfoSelfCert(t *testing.T) { - tmpdir, err := os.MkdirTemp(os.TempDir(), "tlsdir") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() tlsinfo, err := SelfCert(zap.NewExample(), tmpdir, []string{"127.0.0.1"}, 1) if err != nil { t.Fatal(err) diff --git a/client/pkg/transport/transport_test.go b/client/pkg/transport/transport_test.go index afd325da4f6..315f32cf2dc 100644 --- a/client/pkg/transport/transport_test.go +++ b/client/pkg/transport/transport_test.go @@ -25,11 +25,10 @@ import ( // TestNewTransportTLSInvalidCipherSuitesTLS12 expects a client with invalid // cipher suites fail to handshake with the server. func TestNewTransportTLSInvalidCipherSuitesTLS12(t *testing.T) { - tlsInfo, del, err := createSelfCert() + tlsInfo, err := createSelfCert(t) if err != nil { t.Fatalf("unable to create cert: %v", err) } - defer del() cipherSuites := []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, diff --git a/server/embed/auth_test.go b/server/embed/auth_test.go index 57c0a3644be..a09e618f66c 100644 --- a/server/embed/auth_test.go +++ b/server/embed/auth_test.go @@ -16,18 +16,13 @@ package embed import ( "context" - "os" "testing" "go.etcd.io/etcd/server/v3/etcdserver/api/v3client" ) func TestEnableAuth(t *testing.T) { - tdir, err := os.MkdirTemp(os.TempDir(), "auth-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tdir) + tdir := t.TempDir() cfg := NewConfig() cfg.Dir = tdir e, err := StartEtcd(cfg) diff --git a/server/embed/serve_test.go b/server/embed/serve_test.go index 4773107de0a..1d3cdec9362 100644 --- a/server/embed/serve_test.go +++ b/server/embed/serve_test.go @@ -25,11 +25,7 @@ import ( // TestStartEtcdWrongToken ensures that StartEtcd with wrong configs returns with error. func TestStartEtcdWrongToken(t *testing.T) { - tdir, err := os.MkdirTemp(t.TempDir(), "token-test") - - if err != nil { - t.Fatal(err) - } + tdir := t.TempDir() cfg := NewConfig() @@ -47,7 +43,7 @@ func TestStartEtcdWrongToken(t *testing.T) { cfg.Dir = tdir cfg.AuthToken = "wrong-token" - if _, err = StartEtcd(cfg); err != auth.ErrInvalidAuthOpts { + if _, err := StartEtcd(cfg); err != auth.ErrInvalidAuthOpts { t.Fatalf("expected %v, got %v", auth.ErrInvalidAuthOpts, err) } } diff --git a/server/etcdserver/api/rafthttp/snapshot_test.go b/server/etcdserver/api/rafthttp/snapshot_test.go index 69dfad81e22..b1d8cdbbdeb 100644 --- a/server/etcdserver/api/rafthttp/snapshot_test.go +++ b/server/etcdserver/api/rafthttp/snapshot_test.go @@ -94,11 +94,7 @@ func TestSnapshotSend(t *testing.T) { } func testSnapshotSend(t *testing.T, sm *snap.Message) (bool, []os.DirEntry) { - d, err := os.MkdirTemp(os.TempDir(), "snapdir") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(d) + d := t.TempDir() r := &fakeRaft{} tr := &Transport{pipelineRt: &http.Transport{}, ClusterID: types.ID(1), Raft: r} diff --git a/server/etcdserver/server_test.go b/server/etcdserver/server_test.go index 32d368d8fc6..547442abb7a 100644 --- a/server/etcdserver/server_test.go +++ b/server/etcdserver/server_test.go @@ -1086,11 +1086,7 @@ func TestSnapshotOrdering(t *testing.T) { cl := membership.NewCluster(lg) cl.SetStore(st) - testdir, err := os.MkdirTemp(t.TempDir(), "testsnapdir") - if err != nil { - t.Fatalf("couldn't open tempdir (%v)", err) - } - defer os.RemoveAll(testdir) + testdir := t.TempDir() snapdir := filepath.Join(testdir, "member", "snap") if err := os.MkdirAll(snapdir, 0755); err != nil { @@ -1242,11 +1238,7 @@ func TestConcurrentApplyAndSnapshotV3(t *testing.T) { cl := membership.NewCluster(lg) cl.SetStore(st) - testdir, err := os.MkdirTemp(t.TempDir(), "testsnapdir") - if err != nil { - t.Fatalf("Couldn't open tempdir (%v)", err) - } - defer os.RemoveAll(testdir) + testdir := t.TempDir() if err := os.MkdirAll(testdir+"/member/snap", 0755); err != nil { t.Fatalf("Couldn't make snap dir (%v)", err) } diff --git a/server/lease/lessor_test.go b/server/lease/lessor_test.go index 27ca86fd882..740294c5084 100644 --- a/server/lease/lessor_test.go +++ b/server/lease/lessor_test.go @@ -669,10 +669,7 @@ func (fd *fakeDeleter) DeleteRange(key, end []byte) (int64, int64) { } func NewTestBackend(t *testing.T) (string, backend.Backend) { - tmpPath, err := os.MkdirTemp("", "lease") - if err != nil { - t.Fatalf("failed to create tmpdir (%v)", err) - } + tmpPath := t.TempDir() bcfg := backend.DefaultBackendConfig() bcfg.Path = filepath.Join(tmpPath, "be") return tmpPath, backend.New(bcfg) diff --git a/server/storage/wal/file_pipeline_test.go b/server/storage/wal/file_pipeline_test.go index 49079c60ef9..30ce5cc04ac 100644 --- a/server/storage/wal/file_pipeline_test.go +++ b/server/storage/wal/file_pipeline_test.go @@ -16,18 +16,13 @@ package wal import ( "math" - "os" "testing" "go.uber.org/zap" ) func TestFilePipeline(t *testing.T) { - tdir, err := os.MkdirTemp(os.TempDir(), "wal-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tdir) + tdir := t.TempDir() fp := newFilePipeline(zap.NewExample(), tdir, SegmentSizeBytes) defer fp.Close() @@ -40,11 +35,7 @@ func TestFilePipeline(t *testing.T) { } func TestFilePipelineFailPreallocate(t *testing.T) { - tdir, err := os.MkdirTemp(os.TempDir(), "wal-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tdir) + tdir := t.TempDir() fp := newFilePipeline(zap.NewExample(), tdir, math.MaxInt64) defer fp.Close() @@ -56,11 +47,7 @@ func TestFilePipelineFailPreallocate(t *testing.T) { } func TestFilePipelineFailLockFile(t *testing.T) { - tdir, err := os.MkdirTemp(os.TempDir(), "wal-test") - if err != nil { - t.Fatal(err) - } - os.RemoveAll(tdir) + tdir := t.TempDir() fp := newFilePipeline(zap.NewExample(), tdir, math.MaxInt64) defer fp.Close() diff --git a/server/storage/wal/repair_test.go b/server/storage/wal/repair_test.go index 4aee003f031..e1c3e2a807d 100644 --- a/server/storage/wal/repair_test.go +++ b/server/storage/wal/repair_test.go @@ -43,11 +43,7 @@ func TestRepairTruncate(t *testing.T) { } func testRepair(t *testing.T, ents [][]raftpb.Entry, corrupt corruptFunc, expectedEnts int) { - p, err := os.MkdirTemp(os.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() // create WAL w, err := Create(zap.NewExample(), p, nil) @@ -183,11 +179,7 @@ func TestRepairWriteTearMiddle(t *testing.T) { } func TestRepairFailDeleteDir(t *testing.T) { - p, err := os.MkdirTemp(os.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() w, err := Create(zap.NewExample(), p, nil) if err != nil { diff --git a/server/storage/wal/wal_bench_test.go b/server/storage/wal/wal_bench_test.go index b3e03bc24f5..ca7e98e1b40 100644 --- a/server/storage/wal/wal_bench_test.go +++ b/server/storage/wal/wal_bench_test.go @@ -15,7 +15,6 @@ package wal import ( - "os" "testing" "go.uber.org/zap" @@ -36,11 +35,7 @@ func BenchmarkWrite1000EntryBatch500(b *testing.B) { benchmarkWriteEntry(b, func BenchmarkWrite1000EntryBatch1000(b *testing.B) { benchmarkWriteEntry(b, 1000, 1000) } func benchmarkWriteEntry(b *testing.B, size int, batch int) { - p, err := os.MkdirTemp(os.TempDir(), "waltest") - if err != nil { - b.Fatal(err) - } - defer os.RemoveAll(p) + p := b.TempDir() w, err := Create(zap.NewExample(), p, []byte("somedata")) if err != nil { diff --git a/server/storage/wal/wal_test.go b/server/storage/wal/wal_test.go index ed698cc9f9b..5a326476e9d 100644 --- a/server/storage/wal/wal_test.go +++ b/server/storage/wal/wal_test.go @@ -44,11 +44,7 @@ var ( ) func TestNew(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() w, err := Create(zap.NewExample(), p, []byte("somedata")) if err != nil { @@ -98,29 +94,21 @@ func TestNew(t *testing.T) { } func TestCreateFailFromPollutedDir(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() os.WriteFile(filepath.Join(p, "test.wal"), []byte("data"), os.ModeTemporary) - _, err = Create(zap.NewExample(), p, []byte("data")) + _, err := Create(zap.NewExample(), p, []byte("data")) if err != os.ErrExist { t.Fatalf("expected %v, got %v", os.ErrExist, err) } } func TestWalCleanup(t *testing.T) { - testRoot, err := os.MkdirTemp(t.TempDir(), "waltestroot") - if err != nil { - t.Fatal(err) - } + testRoot := t.TempDir() p, err := os.MkdirTemp(testRoot, "waltest") if err != nil { t.Fatal(err) } - defer os.RemoveAll(testRoot) logger := zap.NewExample() w, err := Create(logger, p, []byte("")) @@ -143,11 +131,7 @@ func TestWalCleanup(t *testing.T) { } func TestCreateFailFromNoSpaceLeft(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() oldSegmentSizeBytes := SegmentSizeBytes defer func() { @@ -155,31 +139,23 @@ func TestCreateFailFromNoSpaceLeft(t *testing.T) { }() SegmentSizeBytes = math.MaxInt64 - _, err = Create(zap.NewExample(), p, []byte("data")) + _, err := Create(zap.NewExample(), p, []byte("data")) if err == nil { // no space left on device t.Fatalf("expected error 'no space left on device', got nil") } } func TestNewForInitedDir(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() os.Create(filepath.Join(p, walName(0, 0))) - if _, err = Create(zap.NewExample(), p, nil); err == nil || err != os.ErrExist { + if _, err := Create(zap.NewExample(), p, nil); err == nil || err != os.ErrExist { t.Errorf("err = %v, want %v", err, os.ErrExist) } } func TestOpenAtIndex(t *testing.T) { - dir, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() f, err := os.Create(filepath.Join(dir, walName(0, 0))) if err != nil { @@ -218,11 +194,7 @@ func TestOpenAtIndex(t *testing.T) { } w.Close() - emptydir, err := os.MkdirTemp(t.TempDir(), "waltestempty") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(emptydir) + emptydir := t.TempDir() if _, err = Open(zap.NewExample(), emptydir, walpb.Snapshot{}); err != ErrFileNotFound { t.Errorf("err = %v, want %v", err, ErrFileNotFound) } @@ -233,10 +205,7 @@ func TestOpenAtIndex(t *testing.T) { // it corrupts one of the files by completely truncating it. func TestVerify(t *testing.T) { lg := zaptest.NewLogger(t) - walDir, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } + walDir := t.TempDir() // create WAL w, err := Create(lg, walDir, nil) @@ -285,11 +254,7 @@ func TestVerify(t *testing.T) { // TODO: split it into smaller tests for better readability func TestCut(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() w, err := Create(zap.NewExample(), p, nil) if err != nil { @@ -347,11 +312,7 @@ func TestCut(t *testing.T) { } func TestSaveWithCut(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() w, err := Create(zap.NewExample(), p, []byte("metadata")) if err != nil { @@ -410,11 +371,7 @@ func TestSaveWithCut(t *testing.T) { } func TestRecover(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() w, err := Create(zap.NewExample(), p, []byte("metadata")) if err != nil { @@ -525,11 +482,7 @@ func TestScanWalName(t *testing.T) { } func TestRecoverAfterCut(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() md, err := Create(zap.NewExample(), p, []byte("metadata")) if err != nil { @@ -583,11 +536,7 @@ func TestRecoverAfterCut(t *testing.T) { } func TestOpenAtUncommittedIndex(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() w, err := Create(zap.NewExample(), p, nil) if err != nil { @@ -617,11 +566,7 @@ func TestOpenAtUncommittedIndex(t *testing.T) { // it releases the lock of part of data, and excepts that OpenForRead // can read out all files even if some are locked for write. func TestOpenForRead(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() // create WAL w, err := Create(zap.NewExample(), p, nil) if err != nil { @@ -658,11 +603,7 @@ func TestOpenForRead(t *testing.T) { } func TestOpenWithMaxIndex(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() // create WAL w, err := Create(zap.NewExample(), p, nil) if err != nil { @@ -701,11 +642,7 @@ func TestSaveEmpty(t *testing.T) { } func TestReleaseLockTo(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() // create WAL w, err := Create(zap.NewExample(), p, nil) defer func() { @@ -773,11 +710,7 @@ func TestReleaseLockTo(t *testing.T) { // TestTailWriteNoSlackSpace ensures that tail writes append if there's no preallocated space. func TestTailWriteNoSlackSpace(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() // create initial WAL w, err := Create(zap.NewExample(), p, []byte("metadata")) @@ -839,11 +772,8 @@ func TestTailWriteNoSlackSpace(t *testing.T) { // TestRestartCreateWal ensures that an interrupted WAL initialization is clobbered on restart func TestRestartCreateWal(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() + var err error // make temporary directory so it looks like initialization is interrupted tmpdir := filepath.Clean(p) + ".tmp" @@ -879,11 +809,7 @@ func TestOpenOnTornWrite(t *testing.T) { clobberIdx := 20 overwriteEntries := 5 - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() w, err := Create(zap.NewExample(), p, nil) defer func() { if err = w.Close(); err != nil && err != os.ErrInvalid { @@ -964,11 +890,7 @@ func TestOpenOnTornWrite(t *testing.T) { } func TestRenameFail(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() oldSegmentSizeBytes := SegmentSizeBytes defer func() { @@ -976,10 +898,7 @@ func TestRenameFail(t *testing.T) { }() SegmentSizeBytes = math.MaxInt64 - tp, terr := os.MkdirTemp(t.TempDir(), "waltest") - if terr != nil { - t.Fatal(terr) - } + tp := t.TempDir() os.RemoveAll(tp) w := &WAL{ @@ -994,11 +913,7 @@ func TestRenameFail(t *testing.T) { // TestReadAllFail ensure ReadAll error if used without opening the WAL func TestReadAllFail(t *testing.T) { - dir, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() // create initial WAL f, err := Create(zap.NewExample(), dir, []byte("metadata")) @@ -1016,11 +931,7 @@ func TestReadAllFail(t *testing.T) { // TestValidSnapshotEntries ensures ValidSnapshotEntries returns all valid wal snapshot entries, accounting // for hardstate func TestValidSnapshotEntries(t *testing.T) { - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() snap0 := walpb.Snapshot{} snap1 := walpb.Snapshot{Index: 1, Term: 1, ConfState: &confState} state1 := raftpb.HardState{Commit: 1, Term: 1} @@ -1073,11 +984,7 @@ func TestValidSnapshotEntriesAfterPurgeWal(t *testing.T) { defer func() { SegmentSizeBytes = oldSegmentSizeBytes }() - p, err := os.MkdirTemp(t.TempDir(), "waltest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() snap0 := walpb.Snapshot{} snap1 := walpb.Snapshot{Index: 1, Term: 1, ConfState: &confState} state1 := raftpb.HardState{Commit: 1, Term: 1} diff --git a/tests/e2e/etcd_config_test.go b/tests/e2e/etcd_config_test.go index 1c30d230bec..e00421024d1 100644 --- a/tests/e2e/etcd_config_test.go +++ b/tests/e2e/etcd_config_test.go @@ -47,11 +47,7 @@ func TestEtcdMultiPeer(t *testing.T) { peers, tmpdirs := make([]string, 3), make([]string, 3) for i := range peers { peers[i] = fmt.Sprintf("e%d=http://127.0.0.1:%d", i, e2e.EtcdProcessBasePort+i) - d, err := os.MkdirTemp("", fmt.Sprintf("e%d.etcd", i)) - if err != nil { - t.Fatal(err) - } - tmpdirs[i] = d + tmpdirs[i] = t.TempDir() } ic := strings.Join(peers, ",") @@ -61,7 +57,6 @@ func TestEtcdMultiPeer(t *testing.T) { if procs[i] != nil { procs[i].Stop() } - os.RemoveAll(tmpdirs[i]) } }() for i := range procs { @@ -93,11 +88,7 @@ func TestEtcdMultiPeer(t *testing.T) { func TestEtcdUnixPeers(t *testing.T) { e2e.SkipInShortMode(t) - d, err := os.MkdirTemp("", "e1.etcd") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(d) + d := t.TempDir() proc, err := e2e.SpawnCmd( []string{ e2e.BinDir + "/etcd", @@ -127,11 +118,7 @@ func TestEtcdPeerCNAuth(t *testing.T) { peers, tmpdirs := make([]string, 3), make([]string, 3) for i := range peers { peers[i] = fmt.Sprintf("e%d=https://127.0.0.1:%d", i, e2e.EtcdProcessBasePort+i) - d, err := os.MkdirTemp("", fmt.Sprintf("e%d.etcd", i)) - if err != nil { - t.Fatal(err) - } - tmpdirs[i] = d + tmpdirs[i] = t.TempDir() } ic := strings.Join(peers, ",") @@ -141,7 +128,6 @@ func TestEtcdPeerCNAuth(t *testing.T) { if procs[i] != nil { procs[i].Stop() } - os.RemoveAll(tmpdirs[i]) } }() @@ -210,11 +196,7 @@ func TestEtcdPeerNameAuth(t *testing.T) { peers, tmpdirs := make([]string, 3), make([]string, 3) for i := range peers { peers[i] = fmt.Sprintf("e%d=https://127.0.0.1:%d", i, e2e.EtcdProcessBasePort+i) - d, err := os.MkdirTemp("", fmt.Sprintf("e%d.etcd", i)) - if err != nil { - t.Fatal(err) - } - tmpdirs[i] = d + tmpdirs[i] = t.TempDir() } ic := strings.Join(peers, ",") diff --git a/tests/integration/member_test.go b/tests/integration/member_test.go index f358e771df9..9443e1ba29e 100644 --- a/tests/integration/member_test.go +++ b/tests/integration/member_test.go @@ -17,7 +17,6 @@ package integration import ( "context" "fmt" - "os" "testing" "github.com/stretchr/testify/assert" @@ -67,11 +66,7 @@ func TestLaunchDuplicateMemberShouldFail(t *testing.T) { size := 3 c := integration.NewCluster(t, &integration.ClusterConfig{Size: size}) m := c.Members[0].Clone(t) - var err error - m.DataDir, err = os.MkdirTemp(t.TempDir(), "etcd") - if err != nil { - t.Fatal(err) - } + m.DataDir = t.TempDir() defer c.Terminate(t) if err := m.Launch(); err == nil { diff --git a/tests/integration/v3_grpc_test.go b/tests/integration/v3_grpc_test.go index 620cc5d9c1e..78b5c6c66cf 100644 --- a/tests/integration/v3_grpc_test.go +++ b/tests/integration/v3_grpc_test.go @@ -1626,40 +1626,28 @@ func TestTLSGRPCAcceptSecureAll(t *testing.T) { // when all certs are atomically replaced by directory renaming. // And expects server to reject client requests, and vice versa. func TestTLSReloadAtomicReplace(t *testing.T) { - tmpDir, err := os.MkdirTemp(t.TempDir(), "fixtures-tmp") - if err != nil { - t.Fatal(err) - } + tmpDir := t.TempDir() os.RemoveAll(tmpDir) - defer os.RemoveAll(tmpDir) - certsDir, err := os.MkdirTemp(t.TempDir(), "fixtures-to-load") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(certsDir) + certsDir := t.TempDir() - certsDirExp, err := os.MkdirTemp(t.TempDir(), "fixtures-expired") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(certsDirExp) + certsDirExp := t.TempDir() cloneFunc := func() transport.TLSInfo { tlsInfo, terr := copyTLSFiles(integration.TestTLSInfo, certsDir) if terr != nil { t.Fatal(terr) } - if _, err = copyTLSFiles(integration.TestTLSInfoExpired, certsDirExp); err != nil { + if _, err := copyTLSFiles(integration.TestTLSInfoExpired, certsDirExp); err != nil { t.Fatal(err) } return tlsInfo } replaceFunc := func() { - if err = os.Rename(certsDir, tmpDir); err != nil { + if err := os.Rename(certsDir, tmpDir); err != nil { t.Fatal(err) } - if err = os.Rename(certsDirExp, certsDir); err != nil { + if err := os.Rename(certsDirExp, certsDir); err != nil { t.Fatal(err) } // after rename, @@ -1668,13 +1656,13 @@ func TestTLSReloadAtomicReplace(t *testing.T) { // 'certsDirExp' does not exist } revertFunc := func() { - if err = os.Rename(tmpDir, certsDirExp); err != nil { + if err := os.Rename(tmpDir, certsDirExp); err != nil { t.Fatal(err) } - if err = os.Rename(certsDir, tmpDir); err != nil { + if err := os.Rename(certsDir, tmpDir); err != nil { t.Fatal(err) } - if err = os.Rename(certsDirExp, certsDir); err != nil { + if err := os.Rename(certsDirExp, certsDir); err != nil { t.Fatal(err) } } @@ -1685,11 +1673,7 @@ func TestTLSReloadAtomicReplace(t *testing.T) { // when new certs are copied over, one by one. And expects server // to reject client requests, and vice versa. func TestTLSReloadCopy(t *testing.T) { - certsDir, err := os.MkdirTemp(t.TempDir(), "fixtures-to-load") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(certsDir) + certsDir := t.TempDir() cloneFunc := func() transport.TLSInfo { tlsInfo, terr := copyTLSFiles(integration.TestTLSInfo, certsDir) @@ -1699,12 +1683,12 @@ func TestTLSReloadCopy(t *testing.T) { return tlsInfo } replaceFunc := func() { - if _, err = copyTLSFiles(integration.TestTLSInfoExpired, certsDir); err != nil { + if _, err := copyTLSFiles(integration.TestTLSInfoExpired, certsDir); err != nil { t.Fatal(err) } } revertFunc := func() { - if _, err = copyTLSFiles(integration.TestTLSInfo, certsDir); err != nil { + if _, err := copyTLSFiles(integration.TestTLSInfo, certsDir); err != nil { t.Fatal(err) } } @@ -1715,11 +1699,7 @@ func TestTLSReloadCopy(t *testing.T) { // when new certs are copied over, one by one. And expects server // to reject client requests, and vice versa. func TestTLSReloadCopyIPOnly(t *testing.T) { - certsDir, err := os.MkdirTemp(t.TempDir(), "fixtures-to-load") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(certsDir) + certsDir := t.TempDir() cloneFunc := func() transport.TLSInfo { tlsInfo, terr := copyTLSFiles(integration.TestTLSInfoIP, certsDir) @@ -1729,12 +1709,12 @@ func TestTLSReloadCopyIPOnly(t *testing.T) { return tlsInfo } replaceFunc := func() { - if _, err = copyTLSFiles(integration.TestTLSInfoExpiredIP, certsDir); err != nil { + if _, err := copyTLSFiles(integration.TestTLSInfoExpiredIP, certsDir); err != nil { t.Fatal(err) } } revertFunc := func() { - if _, err = copyTLSFiles(integration.TestTLSInfoIP, certsDir); err != nil { + if _, err := copyTLSFiles(integration.TestTLSInfoIP, certsDir); err != nil { t.Fatal(err) } } diff --git a/tools/etcd-dump-logs/etcd-dump-log_test.go b/tools/etcd-dump-logs/etcd-dump-log_test.go index bd0cb056e8d..bef7e064861 100644 --- a/tools/etcd-dump-logs/etcd-dump-log_test.go +++ b/tools/etcd-dump-logs/etcd-dump-log_test.go @@ -47,11 +47,7 @@ func TestEtcdDumpLogEntryType(t *testing.T) { decoder_correctoutputformat := filepath.Join(binDir, "/testdecoder/decoder_correctoutputformat.sh") decoder_wrongoutputformat := filepath.Join(binDir, "/testdecoder/decoder_wrongoutputformat.sh") - p, err := os.MkdirTemp(os.TempDir(), "etcddumplogstest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(p) + p := t.TempDir() memberdir := filepath.Join(p, "member") err = os.Mkdir(memberdir, 0744)