diff --git a/server/etcdserver/api/membership/cluster_test.go b/server/etcdserver/api/membership/cluster_test.go index c07093878c9..27e3df9c049 100644 --- a/server/etcdserver/api/membership/cluster_test.go +++ b/server/etcdserver/api/membership/cluster_test.go @@ -652,8 +652,8 @@ func TestNodeToMember(t *testing.T) { } } -func newTestCluster(t testing.TB, membs []*Member) *RaftCluster { - c := &RaftCluster{lg: zaptest.NewLogger(t), members: make(map[types.ID]*Member), removed: make(map[types.ID]bool)} +func newTestCluster(tb testing.TB, membs []*Member) *RaftCluster { + c := &RaftCluster{lg: zaptest.NewLogger(tb), members: make(map[types.ID]*Member), removed: make(map[types.ID]bool)} for _, m := range membs { c.members[m.ID] = m } diff --git a/server/etcdserver/server_test.go b/server/etcdserver/server_test.go index 7db595f5fc3..b03f9f73d0e 100644 --- a/server/etcdserver/server_test.go +++ b/server/etcdserver/server_test.go @@ -1513,12 +1513,12 @@ func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChange return &raftpb.ConfState{} } -func newTestCluster(t testing.TB) *membership.RaftCluster { - return membership.NewCluster(zaptest.NewLogger(t)) +func newTestCluster(tb testing.TB) *membership.RaftCluster { + return membership.NewCluster(zaptest.NewLogger(tb)) } -func newTestClusterWithBackend(t testing.TB, membs []*membership.Member, be backend.Backend) *membership.RaftCluster { - lg := zaptest.NewLogger(t) +func newTestClusterWithBackend(tb testing.TB, membs []*membership.Member, be backend.Backend) *membership.RaftCluster { + lg := zaptest.NewLogger(tb) c := membership.NewCluster(lg) c.SetBackend(schema.NewMembershipBackend(lg, be)) for _, m := range membs { diff --git a/server/lease/lessor_bench_test.go b/server/lease/lessor_bench_test.go index 8e6ff791b19..b28ba45c8e8 100644 --- a/server/lease/lessor_bench_test.go +++ b/server/lease/lessor_bench_test.go @@ -60,9 +60,9 @@ func demote(le *lessor) { } // return new lessor and tearDown to release resource -func setUp(t testing.TB) (le *lessor, tearDown func()) { +func setUp(tb testing.TB) (le *lessor, tearDown func()) { lg := zap.NewNop() - be, _ := betesting.NewDefaultTmpBackend(t) + be, _ := betesting.NewDefaultTmpBackend(tb) // MinLeaseTTL is negative, so we can grant expired lease in benchmark. // ExpiredLeasesRetryInterval should small, so benchmark of findExpired will recheck expired lease. le = newLessor(lg, be, nil, LessorConfig{MinLeaseTTL: -1000, ExpiredLeasesRetryInterval: 10 * time.Microsecond}) diff --git a/server/storage/backend/batch_tx_test.go b/server/storage/backend/batch_tx_test.go index 279f199a5db..25af69f11e0 100644 --- a/server/storage/backend/batch_tx_test.go +++ b/server/storage/backend/batch_tx_test.go @@ -393,9 +393,9 @@ func checkUnsafeForEach(t *testing.T, tx backend.UnsafeReader, expectedKeys, exp // runWriteback is used test the txWriteBuffer.writeback function, which is called inside tx.Unlock(). // The parameters are chosen based on defaultBatchLimit = 10000 -func runWriteback(t testing.TB, kss, vss [][]string, isSeq bool) { - b, _ := betesting.NewTmpBackend(t, time.Hour, 10000) - defer betesting.Close(t, b) +func runWriteback(tb testing.TB, kss, vss [][]string, isSeq bool) { + b, _ := betesting.NewTmpBackend(tb, time.Hour, 10000) + defer betesting.Close(tb, b) tx := b.BatchTx() diff --git a/server/storage/backend/hooks_test.go b/server/storage/backend/hooks_test.go index 9a1d33d8253..817127a55be 100644 --- a/server/storage/backend/hooks_test.go +++ b/server/storage/backend/hooks_test.go @@ -94,11 +94,11 @@ func TestBackendAutoCommitBatchIntervalHook(t *testing.T) { waitUntil(ctx, t, func() bool { return getCommitsKey(t, be) == ">ccc" }) } -func waitUntil(ctx context.Context, t testing.TB, f func() bool) { +func waitUntil(ctx context.Context, tb testing.TB, f func() bool) { for !f() { select { case <-ctx.Done(): - t.Fatalf("Context cancelled/timedout without condition met: %v", ctx.Err()) + tb.Fatalf("Context cancelled/timedout without condition met: %v", ctx.Err()) default: } time.Sleep(10 * time.Millisecond) @@ -112,28 +112,28 @@ func prepareBuckenAndKey(tx backend.BatchTx) { tx.UnsafePut(bucket, key, []byte(">")) } -func newTestHooksBackend(t testing.TB, baseConfig backend.BackendConfig) backend.Backend { +func newTestHooksBackend(tb testing.TB, baseConfig backend.BackendConfig) backend.Backend { cfg := baseConfig cfg.Hooks = backend.NewHooks(func(tx backend.UnsafeReadWriter) { k, v := tx.UnsafeRange(bucket, key, nil, 1) - t.Logf("OnPreCommit executed: %v %v", string(k[0]), string(v[0])) - assert.Len(t, k, 1) - assert.Len(t, v, 1) + tb.Logf("OnPreCommit executed: %v %v", string(k[0]), string(v[0])) + assert.Len(tb, k, 1) + assert.Len(tb, v, 1) tx.UnsafePut(bucket, key, append(v[0], byte('c'))) }) - be, _ := betesting.NewTmpBackendFromCfg(t, cfg) - t.Cleanup(func() { - betesting.Close(t, be) + be, _ := betesting.NewTmpBackendFromCfg(tb, cfg) + tb.Cleanup(func() { + betesting.Close(tb, be) }) return be } -func getCommitsKey(t testing.TB, be backend.Backend) string { +func getCommitsKey(tb testing.TB, be backend.Backend) string { rtx := be.BatchTx() rtx.Lock() defer rtx.Unlock() _, v := rtx.UnsafeRange(bucket, key, nil, 1) - assert.Len(t, v, 1) + assert.Len(tb, v, 1) return string(v[0]) } diff --git a/server/storage/backend/testing/betesting.go b/server/storage/backend/testing/betesting.go index e42908f9365..eae54de9af8 100644 --- a/server/storage/backend/testing/betesting.go +++ b/server/storage/backend/testing/betesting.go @@ -26,28 +26,28 @@ import ( "go.etcd.io/etcd/server/v3/storage/backend" ) -func NewTmpBackendFromCfg(t testing.TB, bcfg backend.BackendConfig) (backend.Backend, string) { - dir, err := os.MkdirTemp(t.TempDir(), "etcd_backend_test") +func NewTmpBackendFromCfg(tb testing.TB, bcfg backend.BackendConfig) (backend.Backend, string) { + dir, err := os.MkdirTemp(tb.TempDir(), "etcd_backend_test") if err != nil { panic(err) } tmpPath := filepath.Join(dir, "database") bcfg.Path = tmpPath - bcfg.Logger = zaptest.NewLogger(t) + bcfg.Logger = zaptest.NewLogger(tb) return backend.New(bcfg), tmpPath } // NewTmpBackend creates a backend implementation for testing. -func NewTmpBackend(t testing.TB, batchInterval time.Duration, batchLimit int) (backend.Backend, string) { - bcfg := backend.DefaultBackendConfig(zaptest.NewLogger(t)) +func NewTmpBackend(tb testing.TB, batchInterval time.Duration, batchLimit int) (backend.Backend, string) { + bcfg := backend.DefaultBackendConfig(zaptest.NewLogger(tb)) bcfg.BatchInterval, bcfg.BatchLimit = batchInterval, batchLimit - return NewTmpBackendFromCfg(t, bcfg) + return NewTmpBackendFromCfg(tb, bcfg) } -func NewDefaultTmpBackend(t testing.TB) (backend.Backend, string) { - return NewTmpBackendFromCfg(t, backend.DefaultBackendConfig(zaptest.NewLogger(t))) +func NewDefaultTmpBackend(tb testing.TB) (backend.Backend, string) { + return NewTmpBackendFromCfg(tb, backend.DefaultBackendConfig(zaptest.NewLogger(tb))) } -func Close(t testing.TB, b backend.Backend) { - assert.NoError(t, b.Close()) +func Close(tb testing.TB, b backend.Backend) { + assert.NoError(tb, b.Close()) } diff --git a/server/storage/wal/testing/waltesting.go b/server/storage/wal/testing/waltesting.go index bd1dbaade63..7613a3f7107 100644 --- a/server/storage/wal/testing/waltesting.go +++ b/server/storage/wal/testing/waltesting.go @@ -28,32 +28,32 @@ import ( "go.etcd.io/raft/v3/raftpb" ) -func NewTmpWAL(t testing.TB, reqs []etcdserverpb.InternalRaftRequest) (*wal.WAL, string) { - t.Helper() - dir, err := os.MkdirTemp(t.TempDir(), "etcd_wal_test") +func NewTmpWAL(tb testing.TB, reqs []etcdserverpb.InternalRaftRequest) (*wal.WAL, string) { + tb.Helper() + dir, err := os.MkdirTemp(tb.TempDir(), "etcd_wal_test") if err != nil { panic(err) } tmpPath := filepath.Join(dir, "wal") - lg := zaptest.NewLogger(t) + lg := zaptest.NewLogger(tb) w, err := wal.Create(lg, tmpPath, nil) if err != nil { - t.Fatalf("Failed to create WAL: %v", err) + tb.Fatalf("Failed to create WAL: %v", err) } err = w.Close() if err != nil { - t.Fatalf("Failed to close WAL: %v", err) + tb.Fatalf("Failed to close WAL: %v", err) } if len(reqs) != 0 { w, err = wal.Open(lg, tmpPath, walpb.Snapshot{}) if err != nil { - t.Fatalf("Failed to open WAL: %v", err) + tb.Fatalf("Failed to open WAL: %v", err) } var state raftpb.HardState _, state, _, err = w.ReadAll() if err != nil { - t.Fatalf("Failed to read WAL: %v", err) + tb.Fatalf("Failed to read WAL: %v", err) } var entries []raftpb.Entry for _, req := range reqs { @@ -66,27 +66,27 @@ func NewTmpWAL(t testing.TB, reqs []etcdserverpb.InternalRaftRequest) (*wal.WAL, } err = w.Save(state, entries) if err != nil { - t.Fatalf("Failed to save WAL: %v", err) + tb.Fatalf("Failed to save WAL: %v", err) } err = w.Close() if err != nil { - t.Fatalf("Failed to close WAL: %v", err) + tb.Fatalf("Failed to close WAL: %v", err) } } w, err = wal.OpenForRead(lg, tmpPath, walpb.Snapshot{}) if err != nil { - t.Fatalf("Failed to open WAL: %v", err) + tb.Fatalf("Failed to open WAL: %v", err) } return w, tmpPath } -func Reopen(t testing.TB, walPath string) *wal.WAL { - t.Helper() - lg := zaptest.NewLogger(t) +func Reopen(tb testing.TB, walPath string) *wal.WAL { + tb.Helper() + lg := zaptest.NewLogger(tb) w, err := wal.OpenForRead(lg, walPath, walpb.Snapshot{}) if err != nil { - t.Fatalf("Failed to open WAL: %v", err) + tb.Fatalf("Failed to open WAL: %v", err) } return w } diff --git a/tests/e2e/utils.go b/tests/e2e/utils.go index 8917bd8072a..3f4ca015bc7 100644 --- a/tests/e2e/utils.go +++ b/tests/e2e/utils.go @@ -69,13 +69,13 @@ func newClient(t *testing.T, entpoints []string, cfg e2e.ClientConfig) *clientv3 } // tlsInfo follows the Client-to-server communication in https://etcd.io/docs/v3.6/op-guide/security/#basic-setup -func tlsInfo(t testing.TB, cfg e2e.ClientConfig) (*transport.TLSInfo, error) { +func tlsInfo(tb testing.TB, cfg e2e.ClientConfig) (*transport.TLSInfo, error) { switch cfg.ConnectionType { case e2e.ClientNonTLS, e2e.ClientTLSAndNonTLS: return nil, nil case e2e.ClientTLS: if cfg.AutoTLS { - tls, err := transport.SelfCert(zap.NewNop(), t.TempDir(), []string{"localhost"}, 1) + tls, err := transport.SelfCert(zap.NewNop(), tb.TempDir(), []string{"localhost"}, 1) if err != nil { return nil, fmt.Errorf("failed to generate cert: %w", err) } diff --git a/tests/e2e/v2store_deprecation_test.go b/tests/e2e/v2store_deprecation_test.go index b267ae240b8..20584b208b0 100644 --- a/tests/e2e/v2store_deprecation_test.go +++ b/tests/e2e/v2store_deprecation_test.go @@ -39,13 +39,13 @@ import ( "go.etcd.io/etcd/tests/v3/framework/e2e" ) -func writeCustomV2Data(t testing.TB, epc *e2e.EtcdProcessCluster, count int) { +func writeCustomV2Data(tb testing.TB, epc *e2e.EtcdProcessCluster, count int) { for i := 0; i < count; i++ { if err := e2e.CURLPut(epc, e2e.CURLReq{ Endpoint: "/v2/keys/foo", Value: "bar" + fmt.Sprint(i), Expected: expect.ExpectedResponse{Value: `{"action":"set","node":{"key":"/foo","value":"bar` + fmt.Sprint(i)}, }); err != nil { - t.Fatalf("failed put with curl (%v)", err) + tb.Fatalf("failed put with curl (%v)", err) } } } @@ -191,47 +191,47 @@ func TestV2DeprecationSnapshotRecover(t *testing.T) { assert.NoError(t, epc.Close()) } -func runEtcdAndCreateSnapshot(t testing.TB, serverVersion e2e.ClusterVersion, dataDir string, snapshotCount uint64) *e2e.EtcdProcessCluster { +func runEtcdAndCreateSnapshot(tb testing.TB, serverVersion e2e.ClusterVersion, dataDir string, snapshotCount uint64) *e2e.EtcdProcessCluster { cfg := e2e.ConfigStandalone(*e2e.NewConfig( e2e.WithVersion(serverVersion), e2e.WithDataDirPath(dataDir), e2e.WithSnapshotCount(snapshotCount), e2e.WithKeepDataDir(true), )) - epc, err := e2e.NewEtcdProcessCluster(context.TODO(), t, e2e.WithConfig(cfg)) - assert.NoError(t, err) + epc, err := e2e.NewEtcdProcessCluster(context.TODO(), tb, e2e.WithConfig(cfg)) + assert.NoError(tb, err) return epc } -func addAndRemoveKeysAndMembers(ctx context.Context, t testing.TB, cc *e2e.EtcdctlV3, snapshotCount uint64) (members []uint64) { +func addAndRemoveKeysAndMembers(ctx context.Context, tb testing.TB, cc *e2e.EtcdctlV3, snapshotCount uint64) (members []uint64) { // Execute some non-trivial key&member operation var i uint64 for i = 0; i < snapshotCount*3; i++ { err := cc.Put(ctx, fmt.Sprintf("%d", i), "1", config.PutOptions{}) - require.NoError(t, err) + require.NoError(tb, err) } member1, err := cc.MemberAddAsLearner(ctx, "member1", []string{"http://127.0.0.1:2000"}) - require.NoError(t, err) + require.NoError(tb, err) members = append(members, member1.Member.ID) for i = 0; i < snapshotCount*2; i++ { _, err = cc.Delete(ctx, fmt.Sprintf("%d", i), config.DeleteOptions{}) - require.NoError(t, err) + require.NoError(tb, err) } _, err = cc.MemberRemove(ctx, member1.Member.ID) - require.NoError(t, err) + require.NoError(tb, err) for i = 0; i < snapshotCount; i++ { err = cc.Put(ctx, fmt.Sprintf("%d", i), "2", config.PutOptions{}) - require.NoError(t, err) + require.NoError(tb, err) } member2, err := cc.MemberAddAsLearner(ctx, "member2", []string{"http://127.0.0.1:2001"}) - require.NoError(t, err) + require.NoError(tb, err) members = append(members, member2.Member.ID) for i = 0; i < snapshotCount/2; i++ { err = cc.Put(ctx, fmt.Sprintf("%d", i), "3", config.PutOptions{}) - assert.NoError(t, err) + assert.NoError(tb, err) } return members } @@ -240,39 +240,39 @@ func filterSnapshotFiles(path string) bool { return strings.HasSuffix(path, ".snap") } -func assertSnapshotsMatch(t testing.TB, firstDataDir, secondDataDir string, patch func([]byte) []byte) { - lg := zaptest.NewLogger(t) +func assertSnapshotsMatch(tb testing.TB, firstDataDir, secondDataDir string, patch func([]byte) []byte) { + lg := zaptest.NewLogger(tb) firstFiles, err := fileutil.ListFiles(firstDataDir, filterSnapshotFiles) - require.NoError(t, err) + require.NoError(tb, err) secondFiles, err := fileutil.ListFiles(secondDataDir, filterSnapshotFiles) - require.NoError(t, err) - assert.NotEmpty(t, firstFiles) - assert.NotEmpty(t, secondFiles) - assert.Equal(t, len(firstFiles), len(secondFiles)) + require.NoError(tb, err) + assert.NotEmpty(tb, firstFiles) + assert.NotEmpty(tb, secondFiles) + assert.Equal(tb, len(firstFiles), len(secondFiles)) sort.Strings(firstFiles) sort.Strings(secondFiles) for i := 0; i < len(firstFiles); i++ { firstSnapshot, err := snap.Read(lg, firstFiles[i]) - require.NoError(t, err) + require.NoError(tb, err) secondSnapshot, err := snap.Read(lg, secondFiles[i]) - require.NoError(t, err) - assertMembershipEqual(t, openSnap(patch(firstSnapshot.Data)), openSnap(patch(secondSnapshot.Data))) + require.NoError(tb, err) + assertMembershipEqual(tb, openSnap(patch(firstSnapshot.Data)), openSnap(patch(secondSnapshot.Data))) } } -func assertMembershipEqual(t testing.TB, firstStore v2store.Store, secondStore v2store.Store) { - rc1 := membership.NewCluster(zaptest.NewLogger(t)) +func assertMembershipEqual(tb testing.TB, firstStore v2store.Store, secondStore v2store.Store) { + rc1 := membership.NewCluster(zaptest.NewLogger(tb)) rc1.SetStore(firstStore) rc1.Recover(func(lg *zap.Logger, v *semver.Version) {}) - rc2 := membership.NewCluster(zaptest.NewLogger(t)) + rc2 := membership.NewCluster(zaptest.NewLogger(tb)) rc2.SetStore(secondStore) rc2.Recover(func(lg *zap.Logger, v *semver.Version) {}) // membership should match if !reflect.DeepEqual(rc1.Members(), rc2.Members()) { - t.Logf("memberids_from_last_version = %+v, member_ids_from_current_version = %+v", rc1.MemberIDs(), rc2.MemberIDs()) - t.Errorf("members_from_last_version_snapshot = %+v, members_from_current_version_snapshot %+v", rc1.Members(), rc2.Members()) + tb.Logf("memberids_from_last_version = %+v, member_ids_from_current_version = %+v", rc1.MemberIDs(), rc2.MemberIDs()) + tb.Errorf("members_from_last_version_snapshot = %+v, members_from_current_version_snapshot %+v", rc1.Members(), rc2.Members()) } } diff --git a/tests/framework/e2e/cluster.go b/tests/framework/e2e/cluster.go index 3a2f8388835..604c8516553 100644 --- a/tests/framework/e2e/cluster.go +++ b/tests/framework/e2e/cluster.go @@ -418,23 +418,23 @@ func WithCipherSuites(suites []string) EPClusterOption { // NewEtcdProcessCluster launches a new cluster from etcd processes, returning // a new EtcdProcessCluster once all nodes are ready to accept client requests. -func NewEtcdProcessCluster(ctx context.Context, t testing.TB, opts ...EPClusterOption) (*EtcdProcessCluster, error) { +func NewEtcdProcessCluster(ctx context.Context, tb testing.TB, opts ...EPClusterOption) (*EtcdProcessCluster, error) { cfg := NewConfig(opts...) - epc, err := InitEtcdProcessCluster(t, cfg) + epc, err := InitEtcdProcessCluster(tb, cfg) if err != nil { return nil, err } - return StartEtcdProcessCluster(ctx, t, epc, cfg) + return StartEtcdProcessCluster(ctx, tb, epc, cfg) } // InitEtcdProcessCluster initializes a new cluster based on the given config. // It doesn't start the cluster. -func InitEtcdProcessCluster(t testing.TB, cfg *EtcdProcessClusterConfig) (*EtcdProcessCluster, error) { - SkipInShortMode(t) +func InitEtcdProcessCluster(tb testing.TB, cfg *EtcdProcessClusterConfig) (*EtcdProcessCluster, error) { + SkipInShortMode(tb) if cfg.Logger == nil { - cfg.Logger = zaptest.NewLogger(t) + cfg.Logger = zaptest.NewLogger(tb) } if cfg.BasePort == 0 { cfg.BasePort = EtcdProcessBasePort @@ -453,17 +453,17 @@ func InitEtcdProcessCluster(t testing.TB, cfg *EtcdProcessClusterConfig) (*EtcdP } } - etcdCfgs := cfg.EtcdAllServerProcessConfigs(t) + etcdCfgs := cfg.EtcdAllServerProcessConfigs(tb) epc := &EtcdProcessCluster{ Cfg: cfg, - lg: zaptest.NewLogger(t), + lg: zaptest.NewLogger(tb), Procs: make([]EtcdProcess, cfg.ClusterSize), nextSeq: cfg.ClusterSize, } // launch etcd processes for i := range etcdCfgs { - proc, err := NewEtcdProcess(t, etcdCfgs[i]) + proc, err := NewEtcdProcess(tb, etcdCfgs[i]) if err != nil { epc.Close() return nil, fmt.Errorf("cannot configure: %w", err) @@ -475,7 +475,7 @@ func InitEtcdProcessCluster(t testing.TB, cfg *EtcdProcessClusterConfig) (*EtcdP } // StartEtcdProcessCluster launches a new cluster from etcd processes. -func StartEtcdProcessCluster(ctx context.Context, t testing.TB, epc *EtcdProcessCluster, cfg *EtcdProcessClusterConfig) (*EtcdProcessCluster, error) { +func StartEtcdProcessCluster(ctx context.Context, tb testing.TB, epc *EtcdProcessCluster, cfg *EtcdProcessClusterConfig) (*EtcdProcessCluster, error) { if cfg.RollingStart { if err := epc.RollingStart(ctx); err != nil { return nil, fmt.Errorf("cannot rolling-start: %w", err) @@ -489,11 +489,11 @@ func StartEtcdProcessCluster(ctx context.Context, t testing.TB, epc *EtcdProcess for _, proc := range epc.Procs { if cfg.GoFailEnabled && !proc.Failpoints().Enabled() { epc.Close() - t.Skip("please run 'make gofail-enable && make build' before running the test") + tb.Skip("please run 'make gofail-enable && make build' before running the test") } } if cfg.InitialLeaderIndex >= 0 { - if err := epc.MoveLeader(ctx, t, cfg.InitialLeaderIndex); err != nil { + if err := epc.MoveLeader(ctx, tb, cfg.InitialLeaderIndex); err != nil { return nil, fmt.Errorf("failed to move leader: %w", err) } } @@ -1043,29 +1043,29 @@ func findMemberIDByEndpoint(members []*etcdserverpb.Member, endpoint string) (ui // WaitLeader returns index of the member in c.Members() that is leader // or fails the test (if not established in 30s). -func (epc *EtcdProcessCluster) WaitLeader(t testing.TB) int { +func (epc *EtcdProcessCluster) WaitLeader(tb testing.TB) int { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - return epc.WaitMembersForLeader(ctx, t, epc.Procs) + return epc.WaitMembersForLeader(ctx, tb, epc.Procs) } // WaitMembersForLeader waits until given members agree on the same leader, // and returns its 'index' in the 'membs' list -func (epc *EtcdProcessCluster) WaitMembersForLeader(ctx context.Context, t testing.TB, membs []EtcdProcess) int { +func (epc *EtcdProcessCluster) WaitMembersForLeader(ctx context.Context, tb testing.TB, membs []EtcdProcess) int { cc := epc.Etcdctl() // ensure leader is up via linearizable get for { select { case <-ctx.Done(): - t.Fatal("WaitMembersForLeader timeout") + tb.Fatal("WaitMembersForLeader timeout") default: } _, err := cc.Get(ctx, "0", config.GetOptions{Timeout: 10*config.TickDuration + time.Second}) if err == nil || strings.Contains(err.Error(), "Key not found") { break } - t.Logf("WaitMembersForLeader Get err: %v", err) + tb.Logf("WaitMembersForLeader Get err: %v", err) } leaders := make(map[uint64]struct{}) @@ -1073,7 +1073,7 @@ func (epc *EtcdProcessCluster) WaitMembersForLeader(ctx context.Context, t testi for { select { case <-ctx.Done(): - t.Fatal("WaitMembersForLeader timeout") + tb.Fatal("WaitMembersForLeader timeout") default: } for i := range membs { @@ -1083,7 +1083,7 @@ func (epc *EtcdProcessCluster) WaitMembersForLeader(ctx context.Context, t testi // if member[i] has stopped continue } - t.Fatal(err) + tb.Fatal(err) } members[resp[0].Header.MemberId] = i leaders[resp[0].Leader] = struct{}{} @@ -1098,24 +1098,24 @@ func (epc *EtcdProcessCluster) WaitMembersForLeader(ctx context.Context, t testi } for l := range leaders { if index, ok := members[l]; ok { - t.Logf("members agree on a leader, members:%v , leader:%v", members, l) + tb.Logf("members agree on a leader, members:%v , leader:%v", members, l) return index } - t.Fatalf("members agree on a leader which is not one of members, members:%v , leader:%v", members, l) + tb.Fatalf("members agree on a leader which is not one of members, members:%v , leader:%v", members, l) } - t.Fatal("impossible path of execution") + tb.Fatal("impossible path of execution") return -1 } // MoveLeader moves the leader to the ith process. -func (epc *EtcdProcessCluster) MoveLeader(ctx context.Context, t testing.TB, i int) error { +func (epc *EtcdProcessCluster) MoveLeader(ctx context.Context, tb testing.TB, i int) error { if i < 0 || i >= len(epc.Procs) { return fmt.Errorf("invalid index: %d, must between 0 and %d", i, len(epc.Procs)-1) } - t.Logf("moving leader to Procs[%d]", i) - oldLeader := epc.WaitMembersForLeader(ctx, t, epc.Procs) + tb.Logf("moving leader to Procs[%d]", i) + oldLeader := epc.WaitMembersForLeader(ctx, tb, epc.Procs) if oldLeader == i { - t.Logf("Procs[%d] is already the leader", i) + tb.Logf("Procs[%d] is already the leader", i) return nil } resp, err := epc.Procs[i].Etcdctl().Status(ctx) @@ -1127,10 +1127,10 @@ func (epc *EtcdProcessCluster) MoveLeader(ctx context.Context, t testing.TB, i i if err != nil { return err } - newLeader := epc.WaitMembersForLeader(ctx, t, epc.Procs) + newLeader := epc.WaitMembersForLeader(ctx, tb, epc.Procs) if newLeader != i { - t.Fatalf("expect new leader to be Procs[%d] but got Procs[%d]", i, newLeader) + tb.Fatalf("expect new leader to be Procs[%d] but got Procs[%d]", i, newLeader) } - t.Logf("moved leader from Procs[%d] to Procs[%d]", oldLeader, i) + tb.Logf("moved leader from Procs[%d] to Procs[%d]", oldLeader, i) return nil } diff --git a/tests/framework/e2e/cluster_direct.go b/tests/framework/e2e/cluster_direct.go index 70c60dbf4c0..ea46ea31d01 100644 --- a/tests/framework/e2e/cluster_direct.go +++ b/tests/framework/e2e/cluster_direct.go @@ -18,6 +18,6 @@ package e2e import "testing" -func NewEtcdProcess(t testing.TB, cfg *EtcdServerProcessConfig) (EtcdProcess, error) { - return NewEtcdServerProcess(t, cfg) +func NewEtcdProcess(tb testing.TB, cfg *EtcdServerProcessConfig) (EtcdProcess, error) { + return NewEtcdServerProcess(tb, cfg) } diff --git a/tests/framework/e2e/e2e.go b/tests/framework/e2e/e2e.go index f78df57926e..6f3954d5da7 100644 --- a/tests/framework/e2e/e2e.go +++ b/tests/framework/e2e/e2e.go @@ -39,11 +39,11 @@ func (e e2eRunner) TestMain(m *testing.M) { os.Exit(v) } -func (e e2eRunner) BeforeTest(t testing.TB) { - BeforeTest(t) +func (e e2eRunner) BeforeTest(tb testing.TB) { + BeforeTest(tb) } -func (e e2eRunner) NewCluster(ctx context.Context, t testing.TB, opts ...config.ClusterOption) intf.Cluster { +func (e e2eRunner) NewCluster(ctx context.Context, tb testing.TB, opts ...config.ClusterOption) intf.Cluster { cfg := config.NewClusterConfig(opts...) e2eConfig := NewConfig( WithClusterSize(cfg.ClusterSize), @@ -68,7 +68,7 @@ func (e e2eRunner) NewCluster(ctx context.Context, t testing.TB, opts ...config. e2eConfig.Client.AutoTLS = false e2eConfig.Client.ConnectionType = ClientTLS default: - t.Fatalf("ClientTLS config %q not supported", cfg.ClientTLS) + tb.Fatalf("ClientTLS config %q not supported", cfg.ClientTLS) } switch cfg.PeerTLS { case config.NoTLS: @@ -81,13 +81,13 @@ func (e e2eRunner) NewCluster(ctx context.Context, t testing.TB, opts ...config. e2eConfig.IsPeerTLS = true e2eConfig.IsPeerAutoTLS = false default: - t.Fatalf("PeerTLS config %q not supported", cfg.PeerTLS) + tb.Fatalf("PeerTLS config %q not supported", cfg.PeerTLS) } - epc, err := NewEtcdProcessCluster(ctx, t, WithConfig(e2eConfig)) + epc, err := NewEtcdProcessCluster(ctx, tb, WithConfig(e2eConfig)) if err != nil { - t.Fatalf("could not start etcd integrationCluster: %s", err) + tb.Fatalf("could not start etcd integrationCluster: %s", err) } - return &e2eCluster{t, *epc} + return &e2eCluster{tb, *epc} } type e2eCluster struct { diff --git a/tests/framework/e2e/etcd_process.go b/tests/framework/e2e/etcd_process.go index 445ea26e94c..cac10b6ddcc 100644 --- a/tests/framework/e2e/etcd_process.go +++ b/tests/framework/e2e/etcd_process.go @@ -102,7 +102,7 @@ type EtcdServerProcessConfig struct { Proxy *proxy.ServerConfig } -func NewEtcdServerProcess(t testing.TB, cfg *EtcdServerProcessConfig) (*EtcdServerProcess, error) { +func NewEtcdServerProcess(tb testing.TB, cfg *EtcdServerProcessConfig) (*EtcdServerProcess, error) { if !fileutil.Exist(cfg.ExecPath) { return nil, fmt.Errorf("could not find etcd binary: %s", cfg.ExecPath) } @@ -122,7 +122,7 @@ func NewEtcdServerProcess(t testing.TB, cfg *EtcdServerProcessConfig) (*EtcdServ } } if cfg.LazyFSEnabled { - ep.lazyfs = newLazyFS(cfg.lg, cfg.DataDirPath, t) + ep.lazyfs = newLazyFS(cfg.lg, cfg.DataDirPath, tb) } return ep, nil } diff --git a/tests/framework/e2e/testing.go b/tests/framework/e2e/testing.go index 7d7de27fddd..99aa8dac6d6 100644 --- a/tests/framework/e2e/testing.go +++ b/tests/framework/e2e/testing.go @@ -20,7 +20,7 @@ import ( "go.etcd.io/etcd/client/pkg/v3/testutil" ) -func BeforeTest(t testing.TB) { - SkipInShortMode(t) - testutil.BeforeTest(t) +func BeforeTest(tb testing.TB) { + SkipInShortMode(tb) + testutil.BeforeTest(tb) } diff --git a/tests/framework/e2e/util.go b/tests/framework/e2e/util.go index d72f2d4939d..94e1cd6a84a 100644 --- a/tests/framework/e2e/util.go +++ b/tests/framework/e2e/util.go @@ -150,8 +150,8 @@ func ToTLS(s string) string { return s } -func SkipInShortMode(t testing.TB) { - testutil.SkipTestIfShortMode(t, "e2e tests are not running in --short mode") +func SkipInShortMode(tb testing.TB) { + testutil.SkipTestIfShortMode(tb, "e2e tests are not running in --short mode") } func mergeEnvVariables(envVars map[string]string) []string { diff --git a/tests/framework/integration/cluster.go b/tests/framework/integration/cluster.go index 9ee1cd54d51..98614c24ef7 100644 --- a/tests/framework/integration/cluster.go +++ b/tests/framework/integration/cluster.go @@ -409,23 +409,23 @@ func (c *Cluster) WaitMembersMatch(t testutil.TB, membs []*pb.Member) { // WaitLeader returns index of the member in c.Members that is leader // or fails the test (if not established in 30s). -func (c *Cluster) WaitLeader(t testing.TB) int { - return c.WaitMembersForLeader(t, c.Members) +func (c *Cluster) WaitLeader(tb testing.TB) int { + return c.WaitMembersForLeader(tb, c.Members) } // WaitMembersForLeader waits until given members agree on the same leader, // and returns its 'index' in the 'membs' list -func (c *Cluster) WaitMembersForLeader(t testing.TB, membs []*Member) int { - t.Logf("WaitMembersForLeader") +func (c *Cluster) WaitMembersForLeader(tb testing.TB, membs []*Member) int { + tb.Logf("WaitMembersForLeader") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() l := 0 - for l = c.waitMembersForLeader(ctx, t, membs); l < 0; { + for l = c.waitMembersForLeader(ctx, tb, membs); l < 0; { if ctx.Err() != nil { - t.Fatalf("WaitLeader FAILED: %v", ctx.Err()) + tb.Fatalf("WaitLeader FAILED: %v", ctx.Err()) } } - t.Logf("WaitMembersForLeader succeeded. Cluster leader index: %v", l) + tb.Logf("WaitMembersForLeader succeeded. Cluster leader index: %v", l) // TODO: Consider second pass check as sometimes leadership is lost // soon after election: @@ -441,15 +441,15 @@ func (c *Cluster) WaitMembersForLeader(t testing.TB, membs []*Member) int { // WaitMembersForLeader waits until given members agree on the same leader, // and returns its 'index' in the 'membs' list -func (c *Cluster) waitMembersForLeader(ctx context.Context, t testing.TB, membs []*Member) int { +func (c *Cluster) waitMembersForLeader(ctx context.Context, tb testing.TB, membs []*Member) int { possibleLead := make(map[uint64]bool) var lead uint64 for _, m := range membs { possibleLead[uint64(m.Server.MemberID())] = true } - cc, err := c.ClusterClient(t) + cc, err := c.ClusterClient(tb) if err != nil { - t.Fatal(err) + tb.Fatal(err) } // ensure leader is up via linearizable get for { @@ -480,12 +480,12 @@ func (c *Cluster) waitMembersForLeader(ctx context.Context, t testing.TB, membs for i, m := range membs { if uint64(m.Server.MemberID()) == lead { - t.Logf("waitMembersForLeader found leader. Member: %v lead: %x", i, lead) + tb.Logf("waitMembersForLeader found leader. Member: %v lead: %x", i, lead) return i } } - t.Logf("waitMembersForLeader failed (-1)") + tb.Logf("waitMembersForLeader failed (-1)") return -1 } @@ -1450,7 +1450,7 @@ func (c *Cluster) Endpoints() []string { return endpoints } -func (c *Cluster) ClusterClient(t testing.TB, opts ...framecfg.ClientOption) (client *clientv3.Client, err error) { +func (c *Cluster) ClusterClient(tb testing.TB, opts ...framecfg.ClientOption) (client *clientv3.Client, err error) { cfg, err := c.newClientCfg() if err != nil { return nil, err @@ -1462,7 +1462,7 @@ func (c *Cluster) ClusterClient(t testing.TB, opts ...framecfg.ClientOption) (cl if err != nil { return nil, err } - t.Cleanup(func() { + tb.Cleanup(func() { client.Close() }) return client, nil diff --git a/tests/framework/integration/integration.go b/tests/framework/integration/integration.go index 6e5de0cd528..6152ca70543 100644 --- a/tests/framework/integration/integration.go +++ b/tests/framework/integration/integration.go @@ -41,11 +41,11 @@ func (e integrationRunner) TestMain(m *testing.M) { testutil.MustTestMainWithLeakDetection(m) } -func (e integrationRunner) BeforeTest(t testing.TB) { - BeforeTest(t) +func (e integrationRunner) BeforeTest(tb testing.TB) { + BeforeTest(tb) } -func (e integrationRunner) NewCluster(ctx context.Context, t testing.TB, opts ...config.ClusterOption) intf.Cluster { +func (e integrationRunner) NewCluster(ctx context.Context, tb testing.TB, opts ...config.ClusterOption) intf.Cluster { var err error cfg := config.NewClusterConfig(opts...) integrationCfg := ClusterConfig{ @@ -55,27 +55,27 @@ func (e integrationRunner) NewCluster(ctx context.Context, t testing.TB, opts .. AuthToken: cfg.AuthToken, SnapshotCount: cfg.SnapshotCount, } - integrationCfg.ClientTLS, err = tlsInfo(t, cfg.ClientTLS) + integrationCfg.ClientTLS, err = tlsInfo(tb, cfg.ClientTLS) if err != nil { - t.Fatalf("ClientTLS: %s", err) + tb.Fatalf("ClientTLS: %s", err) } - integrationCfg.PeerTLS, err = tlsInfo(t, cfg.PeerTLS) + integrationCfg.PeerTLS, err = tlsInfo(tb, cfg.PeerTLS) if err != nil { - t.Fatalf("PeerTLS: %s", err) + tb.Fatalf("PeerTLS: %s", err) } return &integrationCluster{ - Cluster: NewCluster(t, &integrationCfg), - t: t, + Cluster: NewCluster(tb, &integrationCfg), + t: tb, ctx: ctx, } } -func tlsInfo(t testing.TB, cfg config.TLSConfig) (*transport.TLSInfo, error) { +func tlsInfo(tb testing.TB, cfg config.TLSConfig) (*transport.TLSInfo, error) { switch cfg { case config.NoTLS: return nil, nil case config.AutoTLS: - tls, err := transport.SelfCert(zap.NewNop(), t.TempDir(), []string{"localhost"}, 1) + tls, err := transport.SelfCert(zap.NewNop(), tb.TempDir(), []string{"localhost"}, 1) if err != nil { return nil, fmt.Errorf("failed to generate cert: %w", err) } diff --git a/tests/framework/integration/testing.go b/tests/framework/integration/testing.go index a4d03c53212..7e0dd38d4df 100644 --- a/tests/framework/integration/testing.go +++ b/tests/framework/integration/testing.go @@ -138,18 +138,18 @@ func assertInTestContext(t testutil.TB) { } } -func NewEmbedConfig(t testing.TB, name string) *embed.Config { +func NewEmbedConfig(tb testing.TB, name string) *embed.Config { cfg := embed.NewConfig() cfg.Name = name - lg := zaptest.NewLogger(t, zaptest.Level(zapcore.InfoLevel)).Named(cfg.Name) + lg := zaptest.NewLogger(tb, zaptest.Level(zapcore.InfoLevel)).Named(cfg.Name) cfg.ZapLoggerBuilder = embed.NewZapLoggerBuilder(lg) - cfg.Dir = t.TempDir() + cfg.Dir = tb.TempDir() return cfg } -func NewClient(t testing.TB, cfg clientv3.Config) (*clientv3.Client, error) { +func NewClient(tb testing.TB, cfg clientv3.Config) (*clientv3.Client, error) { if cfg.Logger == nil { - cfg.Logger = zaptest.NewLogger(t).Named("client") + cfg.Logger = zaptest.NewLogger(tb).Named("client") } return clientv3.New(cfg) } diff --git a/tests/framework/unit/unit.go b/tests/framework/unit/unit.go index f822b7dd1f9..d09ef0bdd2b 100644 --- a/tests/framework/unit/unit.go +++ b/tests/framework/unit/unit.go @@ -42,10 +42,10 @@ func (e unitRunner) TestMain(m *testing.M) { } } -func (e unitRunner) BeforeTest(t testing.TB) { +func (e unitRunner) BeforeTest(tb testing.TB) { } -func (e unitRunner) NewCluster(ctx context.Context, t testing.TB, opts ...config.ClusterOption) intf.Cluster { - testutil.SkipTestIfShortMode(t, "Cannot create clusters in --short tests") +func (e unitRunner) NewCluster(ctx context.Context, tb testing.TB, opts ...config.ClusterOption) intf.Cluster { + testutil.SkipTestIfShortMode(tb, "Cannot create clusters in --short tests") return nil } diff --git a/tests/integration/v3_leadership_test.go b/tests/integration/v3_leadership_test.go index 2054acbade6..a2e697c2e4c 100644 --- a/tests/integration/v3_leadership_test.go +++ b/tests/integration/v3_leadership_test.go @@ -239,14 +239,14 @@ func TestFirstCommitNotification(t *testing.T) { func checkFirstCommitNotification( ctx context.Context, - t testing.TB, + tb testing.TB, member *integration.Member, leaderAppliedIndex uint64, notifier <-chan struct{}, ) error { // wait until server applies all the changes of leader for member.Server.AppliedIndex() < leaderAppliedIndex { - t.Logf("member.Server.AppliedIndex():%v <= leaderAppliedIndex:%v", member.Server.AppliedIndex(), leaderAppliedIndex) + tb.Logf("member.Server.AppliedIndex():%v <= leaderAppliedIndex:%v", member.Server.AppliedIndex(), leaderAppliedIndex) select { case <-ctx.Done(): return ctx.Err() @@ -264,7 +264,7 @@ func checkFirstCommitNotification( ) } default: - t.Logf("member.Server.AppliedIndex():%v >= leaderAppliedIndex:%v", member.Server.AppliedIndex(), leaderAppliedIndex) + tb.Logf("member.Server.AppliedIndex():%v >= leaderAppliedIndex:%v", member.Server.AppliedIndex(), leaderAppliedIndex) return fmt.Errorf( "notification was not triggered, member ID: %d", member.ID(), diff --git a/tools/.golangci.yaml b/tools/.golangci.yaml index 60925e0a467..809ff1459a0 100644 --- a/tools/.golangci.yaml +++ b/tools/.golangci.yaml @@ -32,6 +32,7 @@ linters: - stylecheck - tenv - testifylint + - thelper - unconvert # Remove unnecessary type conversions - unparam - unused @@ -47,49 +48,31 @@ linters-settings: # please keep this alphabetized confidence: 0.8 rules: - name: blank-imports - disabled: false - name: context-as-argument - disabled: false + arguments: + - allowTypesBefore: "*testing.T" - name: context-keys-type - disabled: false - name: dot-imports - disabled: false - name: early-return - disabled: false arguments: - "preserveScope" - name: error-return - disabled: false - name: error-naming - disabled: false - name: error-strings - disabled: false - name: errorf - disabled: false - name: if-return - disabled: false - name: increment-decrement - disabled: false - name: indent-error-flow - disabled: false - name: package-comments - disabled: false - name: range - disabled: false - name: receiver-naming - disabled: false - name: superfluous-else - disabled: false arguments: - "preserveScope" - name: time-naming - disabled: false - name: use-any - disabled: false - name: var-declaration - disabled: false - name: var-naming - disabled: false arguments: # The following is the configuration for var-naming rule, the first element is the allow list and the second element is the deny list. - [] # AllowList: leave it empty to use the default (empty, too). This means that we're not relaxing the rule in any way, i.e. elementId will raise a violation, it should be elementID, refer to the next line to see the list of denied initialisms. @@ -120,3 +103,16 @@ linters-settings: # please keep this alphabetized # to always require f-functions for stretchr/testify, but not for golang standard lib. # Also refer to https://github.com/etcd-io/etcd/pull/18741#issuecomment-2422395914 require-f-funcs: true + thelper: + test: + first: false + begin: false + benchmark: + first: false + begin: false + tb: + first: false + begin: false + fuzz: + first: false + begin: false