From d59fa331c53534881693384008c7e26501dbfc7a Mon Sep 17 00:00:00 2001 From: redwrasse Date: Fri, 6 Sep 2024 11:40:37 -0700 Subject: [PATCH] Replaces rest of error equality checks with errors.Is Signed-off-by: redwrasse --- client/internal/v2/client.go | 4 +- client/internal/v2/client_test.go | 10 ++--- client/internal/v2/keys.go | 2 +- client/pkg/fileutil/lock_linux.go | 3 +- client/pkg/fileutil/lock_solaris.go | 3 +- client/pkg/fileutil/lock_test.go | 3 +- client/pkg/fileutil/lock_windows.go | 4 +- client/pkg/fileutil/preallocate_darwin.go | 3 +- client/v3/client.go | 6 +-- client/v3/client_test.go | 2 +- client/v3/experimental/recipes/key.go | 5 ++- client/v3/watch.go | 2 +- contrib/raftexample/kvstore.go | 3 +- contrib/raftexample/raft.go | 3 +- etcdctl/ctlv3/command/auth_command.go | 3 +- etcdctl/ctlv3/command/watch_command_test.go | 3 +- pkg/ioutil/readcloser_test.go | 5 ++- server/auth/jwt_test.go | 3 +- server/auth/store_test.go | 44 +++++++++---------- server/embed/etcd_test.go | 3 +- server/embed/serve_test.go | 3 +- server/etcdmain/config_test.go | 7 +-- .../etcdserver/api/membership/cluster_test.go | 3 +- .../etcdserver/api/rafthttp/msg_codec_test.go | 5 ++- server/etcdserver/api/rafthttp/pipeline.go | 2 +- .../api/rafthttp/snapshot_sender.go | 3 +- server/etcdserver/api/rafthttp/stream.go | 5 ++- server/etcdserver/api/rafthttp/stream_test.go | 2 +- .../etcdserver/api/snap/snapshotter_test.go | 9 ++-- .../etcdserver/api/v2discovery/discovery.go | 4 +- .../api/v2discovery/discovery_test.go | 8 ++-- .../api/v3discovery/discovery_test.go | 6 +-- server/etcdserver/api/v3rpc/lease.go | 13 +++--- server/etcdserver/api/v3rpc/util.go | 3 +- server/etcdserver/api/v3rpc/util_test.go | 2 +- server/etcdserver/api/v3rpc/watch.go | 9 ++-- server/etcdserver/api/v3rpc/watch_test.go | 3 +- server/etcdserver/apply/apply_auth_test.go | 5 ++- server/etcdserver/server_test.go | 5 ++- server/lease/leasehttp/http.go | 2 +- server/lease/lessor_test.go | 7 +-- server/proxy/grpcproxy/lease.go | 3 +- server/proxy/grpcproxy/maintenance.go | 3 +- server/storage/mvcc/index_test.go | 7 +-- server/storage/mvcc/key_index_test.go | 5 ++- server/storage/mvcc/kv_test.go | 5 ++- server/storage/mvcc/kvstore_test.go | 3 +- server/storage/mvcc/watcher_test.go | 9 ++-- server/storage/schema/actions_test.go | 3 +- server/storage/schema/migration_test.go | 3 +- server/storage/wal/decoder.go | 3 +- server/storage/wal/repair_test.go | 3 +- server/storage/wal/wal_test.go | 8 ++-- tests/e2e/ctl_v3_member_test.go | 5 ++- tests/e2e/ctl_v3_snapshot_test.go | 3 +- .../concurrency/example_mutex_test.go | 3 +- .../clientv3/connectivity/black_hole_test.go | 11 ++--- .../connectivity/network_partition_test.go | 10 ++--- .../connectivity/server_shutdown_test.go | 3 +- .../recipes/v3_double_barrier_test.go | 3 +- .../experimental/recipes/v3_lock_test.go | 3 +- .../clientv3/lease/leasing_test.go | 7 +-- .../integration/clientv3/maintenance_test.go | 5 ++- .../integration/clientv3/ordering_kv_test.go | 6 +-- .../clientv3/ordering_util_test.go | 5 ++- tests/integration/clientv3/txn_test.go | 5 ++- tests/integration/clientv3/user_test.go | 13 +++--- tests/integration/v3_grpc_test.go | 7 +-- tests/integration/v3_tls_test.go | 3 +- 69 files changed, 209 insertions(+), 158 deletions(-) diff --git a/client/internal/v2/client.go b/client/internal/v2/client.go index 8a4ecdf7b4a..da45433549a 100644 --- a/client/internal/v2/client.go +++ b/client/internal/v2/client.go @@ -365,10 +365,10 @@ func (c *httpClusterClient) Do(ctx context.Context, act httpAction) (*http.Respo resp, body, err = hc.Do(ctx, action) if err != nil { cerr.Errors = append(cerr.Errors, err) - if err == ctx.Err() { + if errors.Is(err, ctx.Err()) { return nil, nil, ctx.Err() } - if err == context.Canceled || err == context.DeadlineExceeded { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return nil, nil, err } } else if resp.StatusCode/100 == 5 { diff --git a/client/internal/v2/client_test.go b/client/internal/v2/client_test.go index 83aae018dad..c7350ba8204 100644 --- a/client/internal/v2/client_test.go +++ b/client/internal/v2/client_test.go @@ -169,7 +169,7 @@ func TestSimpleHTTPClientDoNilRequest(t *testing.T) { tr.errchan <- errors.New("fixture") _, _, err := c.Do(context.Background(), &nilAction{}) - if err != ErrNoRequest { + if !errors.Is(err, ErrNoRequest) { t.Fatalf("expected non-nil error, got nil") } } @@ -256,7 +256,7 @@ func TestSimpleHTTPClientDoCancelContextResponseBodyClosedWithBlockingBody(t *te }() _, _, err := c.Do(ctx, &fakeAction{}) - if err != context.Canceled { + if !errors.Is(err, context.Canceled) { t.Fatalf("expected %+v, got %+v", context.Canceled, err) } @@ -478,7 +478,7 @@ func TestHTTPClusterClientDoDeadlineExceedContext(t *testing.T) { select { case err := <-errc: - if err != context.DeadlineExceeded { + if !errors.Is(err, context.DeadlineExceeded) { t.Errorf("err = %+v, want %+v", err, context.DeadlineExceeded) } case <-time.After(time.Second): @@ -528,7 +528,7 @@ func TestHTTPClusterClientDoCanceledContext(t *testing.T) { select { case err := <-errc: - if err != errFakeCancelContext { + if !errors.Is(err, errFakeCancelContext) { t.Errorf("err = %+v, want %+v", err, errFakeCancelContext) } case <-time.After(time.Second): @@ -881,7 +881,7 @@ func TestHTTPClusterClientAutoSyncCancelContext(t *testing.T) { cancel() err = hc.AutoSync(ctx, time.Hour) - if err != context.Canceled { + if !errors.Is(err, context.Canceled) { t.Fatalf("incorrect error value: want=%v got=%v", context.Canceled, err) } } diff --git a/client/internal/v2/keys.go b/client/internal/v2/keys.go index 8be1057f04e..764cc7290d7 100644 --- a/client/internal/v2/keys.go +++ b/client/internal/v2/keys.go @@ -459,7 +459,7 @@ func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) { resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body) if err != nil { - if err == ErrEmptyBody { + if errors.Is(err, ErrEmptyBody) { continue } return nil, err diff --git a/client/pkg/fileutil/lock_linux.go b/client/pkg/fileutil/lock_linux.go index c33a2f4afc7..fd424be771b 100644 --- a/client/pkg/fileutil/lock_linux.go +++ b/client/pkg/fileutil/lock_linux.go @@ -17,6 +17,7 @@ package fileutil import ( + "errors" "fmt" "io" "os" @@ -64,7 +65,7 @@ func ofdTryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error flock := wrlck if err = syscall.FcntlFlock(f.Fd(), unix.F_OFD_SETLK, &flock); err != nil { f.Close() - if err == syscall.EWOULDBLOCK { + if errors.Is(err, syscall.EWOULDBLOCK) { err = ErrLocked } return nil, err diff --git a/client/pkg/fileutil/lock_solaris.go b/client/pkg/fileutil/lock_solaris.go index 2e892fecc65..b4cba97f798 100644 --- a/client/pkg/fileutil/lock_solaris.go +++ b/client/pkg/fileutil/lock_solaris.go @@ -17,6 +17,7 @@ package fileutil import ( + "errors" "os" "syscall" ) @@ -35,7 +36,7 @@ func TryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) { } if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &lock); err != nil { f.Close() - if err == syscall.EAGAIN { + if errors.Is(err, syscall.EAGAIN) { err = ErrLocked } return nil, err diff --git a/client/pkg/fileutil/lock_test.go b/client/pkg/fileutil/lock_test.go index b7f6fd5ce57..49e7eb62320 100644 --- a/client/pkg/fileutil/lock_test.go +++ b/client/pkg/fileutil/lock_test.go @@ -15,6 +15,7 @@ package fileutil import ( + "errors" "os" "testing" "time" @@ -40,7 +41,7 @@ func TestLockAndUnlock(t *testing.T) { } // try lock a locked file - if _, err = TryLockFile(f.Name(), os.O_WRONLY, PrivateFileMode); err != ErrLocked { + if _, err = TryLockFile(f.Name(), os.O_WRONLY, PrivateFileMode); !errors.Is(err, ErrLocked) { t.Fatal(err) } diff --git a/client/pkg/fileutil/lock_windows.go b/client/pkg/fileutil/lock_windows.go index 51010bdf81c..a767b0f57f6 100644 --- a/client/pkg/fileutil/lock_windows.go +++ b/client/pkg/fileutil/lock_windows.go @@ -88,9 +88,9 @@ func lockFile(fd windows.Handle, flags uint32) error { err := windows.LockFileEx(fd, flags|windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &windows.Overlapped{}) if err == nil { return nil - } else if err.Error() == errLocked.Error() { + } else if errors.Is(err, errLocked) { return ErrLocked - } else if err != windows.ERROR_LOCK_VIOLATION { + } else if !errors.Is(err, windows.ERROR_LOCK_VIOLATION) { return err } return nil diff --git a/client/pkg/fileutil/preallocate_darwin.go b/client/pkg/fileutil/preallocate_darwin.go index e74968d0351..79519959234 100644 --- a/client/pkg/fileutil/preallocate_darwin.go +++ b/client/pkg/fileutil/preallocate_darwin.go @@ -17,6 +17,7 @@ package fileutil import ( + "errors" "os" "syscall" @@ -44,7 +45,7 @@ func preallocFixed(f *os.File, sizeInBytes int64) error { } // wrong argument to fallocate syscall - if err == unix.EINVAL { + if errors.Is(err, unix.EINVAL) { // filesystem "st_blocks" are allocated in the units of // "Allocation Block Size" (run "diskutil info /" command) var stat syscall.Stat_t diff --git a/client/v3/client.go b/client/v3/client.go index 8789acb38c8..6b7b5632fed 100644 --- a/client/v3/client.go +++ b/client/v3/client.go @@ -294,7 +294,7 @@ func (c *Client) getToken(ctx context.Context) error { resp, err := c.Auth.Authenticate(ctx, c.Username, c.Password) if err != nil { - if err == rpctypes.ErrAuthNotEnabled { + if errors.Is(err, rpctypes.ErrAuthNotEnabled) { c.authTokenBundle.UpdateAuthToken("") return nil } @@ -627,7 +627,7 @@ func canceledByCaller(stopCtx context.Context, err error) bool { return false } - return err == context.Canceled || err == context.DeadlineExceeded + return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) } // IsConnCanceled returns true, if error is from a closed gRPC connection. @@ -645,7 +645,7 @@ func IsConnCanceled(err error) bool { } // >= gRPC v1.10.x - if err == context.Canceled { + if errors.Is(err, context.Canceled) { return true } diff --git a/client/v3/client_test.go b/client/v3/client_test.go index db8bb1773f9..fe996ea8e69 100644 --- a/client/v3/client_test.go +++ b/client/v3/client_test.go @@ -449,7 +449,7 @@ func TestClientRejectOldCluster(t *testing.T) { }, } - if err := c.checkVersion(); err != tt.expectedError { + if err := c.checkVersion(); !errors.Is(err, tt.expectedError) { t.Errorf("heckVersion err:%v", err) } }) diff --git a/client/v3/experimental/recipes/key.go b/client/v3/experimental/recipes/key.go index 10362c18fbe..ce90010538b 100644 --- a/client/v3/experimental/recipes/key.go +++ b/client/v3/experimental/recipes/key.go @@ -16,6 +16,7 @@ package recipe import ( "context" + "errors" "fmt" "strings" "time" @@ -51,7 +52,7 @@ func newUniqueKV(kv v3.KV, prefix string, val string) (*RemoteKV, error) { if err == nil { return &RemoteKV{kv, newKey, rev, val}, nil } - if err != ErrKeyExists { + if !errors.Is(err, ErrKeyExists) { return nil, err } } @@ -155,7 +156,7 @@ func newUniqueEphemeralKV(s *concurrency.Session, prefix, val string) (ek *Ephem for { newKey := fmt.Sprintf("%s/%v", prefix, time.Now().UnixNano()) ek, err = newEphemeralKV(s, newKey, val) - if err == nil || err != ErrKeyExists { + if err == nil || !errors.Is(err, ErrKeyExists) { break } } diff --git a/client/v3/watch.go b/client/v3/watch.go index bfa753cfd71..c81a9e3e11d 100644 --- a/client/v3/watch.go +++ b/client/v3/watch.go @@ -395,7 +395,7 @@ func (w *watcher) Close() (err error) { } } // Consider context.Canceled as a successful close - if err == context.Canceled { + if errors.Is(err, context.Canceled) { err = nil } return err diff --git a/contrib/raftexample/kvstore.go b/contrib/raftexample/kvstore.go index b319677cada..11bbf1fc6e7 100644 --- a/contrib/raftexample/kvstore.go +++ b/contrib/raftexample/kvstore.go @@ -18,6 +18,7 @@ import ( "bytes" "encoding/gob" "encoding/json" + "errors" "log" "strings" "sync" @@ -113,7 +114,7 @@ func (s *kvstore) getSnapshot() ([]byte, error) { func (s *kvstore) loadSnapshot() (*raftpb.Snapshot, error) { snapshot, err := s.snapshotter.Load() - if err == snap.ErrNoSnapshot { + if errors.Is(err, snap.ErrNoSnapshot) { return nil, nil } if err != nil { diff --git a/contrib/raftexample/raft.go b/contrib/raftexample/raft.go index 18b5354dd32..fac1a099ac5 100644 --- a/contrib/raftexample/raft.go +++ b/contrib/raftexample/raft.go @@ -16,6 +16,7 @@ package main import ( "context" + "errors" "fmt" "log" "net/http" @@ -392,7 +393,7 @@ func (rc *raftNode) maybeTriggerSnapshot(applyDoneC <-chan struct{}) { compactIndex = rc.appliedIndex - snapshotCatchUpEntriesN } if err := rc.raftStorage.Compact(compactIndex); err != nil { - if err != raft.ErrCompacted { + if !errors.Is(err, raft.ErrCompacted) { panic(err) } } else { diff --git a/etcdctl/ctlv3/command/auth_command.go b/etcdctl/ctlv3/command/auth_command.go index 0e443450013..13ccda44d16 100644 --- a/etcdctl/ctlv3/command/auth_command.go +++ b/etcdctl/ctlv3/command/auth_command.go @@ -15,6 +15,7 @@ package command import ( + "errors" "fmt" "github.com/spf13/cobra" @@ -82,7 +83,7 @@ func authEnableCommandFunc(cmd *cobra.Command, args []string) { if _, err = cli.AuthEnable(ctx); err == nil { break } - if err == rpctypes.ErrRootRoleNotExist { + if errors.Is(err, rpctypes.ErrRootRoleNotExist) { if _, err = cli.RoleAdd(ctx, "root"); err != nil { break } diff --git a/etcdctl/ctlv3/command/watch_command_test.go b/etcdctl/ctlv3/command/watch_command_test.go index 2292deadcbb..ad4668606ec 100644 --- a/etcdctl/ctlv3/command/watch_command_test.go +++ b/etcdctl/ctlv3/command/watch_command_test.go @@ -15,6 +15,7 @@ package command import ( + "errors" "reflect" "testing" ) @@ -534,7 +535,7 @@ func Test_parseWatchArgs(t *testing.T) { } for i, ts := range tt { watchArgs, execArgs, err := parseWatchArgs(ts.osArgs, ts.commandArgs, ts.envKey, ts.envRange, ts.interactive) - if err != ts.err { + if !errors.Is(err, ts.err) { t.Fatalf("#%d: error expected %v, got %v", i, ts.err, err) } if !reflect.DeepEqual(watchArgs, ts.watchArgs) { diff --git a/pkg/ioutil/readcloser_test.go b/pkg/ioutil/readcloser_test.go index 6d13bdcec02..381a797f7af 100644 --- a/pkg/ioutil/readcloser_test.go +++ b/pkg/ioutil/readcloser_test.go @@ -16,6 +16,7 @@ package ioutil import ( "bytes" + "errors" "io" "testing" ) @@ -28,7 +29,7 @@ func (rc *readerNilCloser) Close() error { return nil } func TestExactReadCloserExpectEOF(t *testing.T) { buf := bytes.NewBuffer(make([]byte, 10)) rc := NewExactReadCloser(&readerNilCloser{buf}, 1) - if _, err := rc.Read(make([]byte, 10)); err != ErrExpectEOF { + if _, err := rc.Read(make([]byte, 10)); !errors.Is(err, ErrExpectEOF) { t.Fatalf("expected %v, got %v", ErrExpectEOF, err) } } @@ -40,7 +41,7 @@ func TestExactReadCloserShort(t *testing.T) { if _, err := rc.Read(make([]byte, 10)); err != nil { t.Fatalf("Read expected nil err, got %v", err) } - if err := rc.Close(); err != ErrShortRead { + if err := rc.Close(); !errors.Is(err, ErrShortRead) { t.Fatalf("Close expected %v, got %v", ErrShortRead, err) } } diff --git a/server/auth/jwt_test.go b/server/auth/jwt_test.go index 27369092dd3..7d211ebf3b0 100644 --- a/server/auth/jwt_test.go +++ b/server/auth/jwt_test.go @@ -16,6 +16,7 @@ package auth import ( "context" + "errors" "fmt" "testing" "time" @@ -139,7 +140,7 @@ func testJWTInfo(t *testing.T, opts map[string]string) { } _, aerr := verify.assign(ctx, "abc", 123) - if aerr != ErrVerifyOnly { + if !errors.Is(aerr, ErrVerifyOnly) { t.Fatalf("unexpected error when attempting to sign with public key: %v", aerr) } diff --git a/server/auth/store_test.go b/server/auth/store_test.go index a05102f652f..4e1d0c4aac5 100644 --- a/server/auth/store_test.go +++ b/server/auth/store_test.go @@ -165,13 +165,13 @@ func TestUserAdd(t *testing.T) { if err == nil { t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err) } - if err != ErrUserAlreadyExist { + if !errors.Is(err, ErrUserAlreadyExist) { t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err) } ua = &pb.AuthUserAddRequest{Name: "", Options: &authpb.UserAddOptions{NoPassword: false}} _, err = as.UserAdd(ua) // add a user with empty name - if err != ErrUserEmpty { + if !errors.Is(err, ErrUserEmpty) { t.Fatal(err) } @@ -227,7 +227,7 @@ func TestCheckPassword(t *testing.T) { if err == nil { t.Fatalf("expected %v, got %v", ErrAuthFailed, err) } - if err != ErrAuthFailed { + if !errors.Is(err, ErrAuthFailed) { t.Fatalf("expected %v, got %v", ErrAuthFailed, err) } @@ -242,7 +242,7 @@ func TestCheckPassword(t *testing.T) { if err == nil { t.Fatalf("expected %v, got %v", ErrAuthFailed, err) } - if err != ErrAuthFailed { + if !errors.Is(err, ErrAuthFailed) { t.Fatalf("expected %v, got %v", ErrAuthFailed, err) } } @@ -264,7 +264,7 @@ func TestUserDelete(t *testing.T) { if err == nil { t.Fatalf("expected %v, got %v", ErrUserNotFound, err) } - if err != ErrUserNotFound { + if !errors.Is(err, ErrUserNotFound) { t.Fatalf("expected %v, got %v", ErrUserNotFound, err) } @@ -288,7 +288,7 @@ func TestUserDeleteAndPermCache(t *testing.T) { // delete a non-existing user _, err = as.UserDelete(ud) - if err != ErrUserNotFound { + if !errors.Is(err, ErrUserNotFound) { t.Fatalf("expected %v, got %v", ErrUserNotFound, err) } @@ -336,7 +336,7 @@ func TestUserChangePassword(t *testing.T) { if err == nil { t.Fatalf("expected %v, got %v", ErrUserNotFound, err) } - if err != ErrUserNotFound { + if !errors.Is(err, ErrUserNotFound) { t.Fatalf("expected %v, got %v", ErrUserNotFound, err) } @@ -359,7 +359,7 @@ func TestRoleAdd(t *testing.T) { // add a role with empty name _, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: ""}) - if err != ErrRoleEmpty { + if !errors.Is(err, ErrRoleEmpty) { t.Fatal(err) } } @@ -379,7 +379,7 @@ func TestUserGrant(t *testing.T) { if err == nil { t.Errorf("expected %v, got %v", ErrUserNotFound, err) } - if err != ErrUserNotFound { + if !errors.Is(err, ErrUserNotFound) { t.Errorf("expected %v, got %v", ErrUserNotFound, err) } } @@ -455,7 +455,7 @@ func TestIsOpPermitted(t *testing.T) { as.rangePermCacheMu.Lock() delete(as.rangePermCache, "foo") as.rangePermCacheMu.Unlock() - if err := as.isOpPermitted("foo", as.Revision(), perm.Key, perm.RangeEnd, perm.PermType); err != ErrPermissionDenied { + if err := as.isOpPermitted("foo", as.Revision(), perm.Key, perm.RangeEnd, perm.PermType); !errors.Is(err, ErrPermissionDenied) { t.Fatal(err) } @@ -545,7 +545,7 @@ func TestRoleGrantPermission(t *testing.T) { Name: "role-test-1", }) - if err != ErrPermissionNotGiven { + if !errors.Is(err, ErrPermissionNotGiven) { t.Error(err) } @@ -887,13 +887,13 @@ func TestAuthInfoFromCtx(t *testing.T) { ctx = metadata.NewIncomingContext(context.Background(), metadata.New(map[string]string{rpctypes.TokenFieldNameGRPC: "Invalid Token"})) _, err = as.AuthInfoFromCtx(ctx) - if err != ErrInvalidAuthToken { + if !errors.Is(err, ErrInvalidAuthToken) { t.Errorf("expected %v, got %v", ErrInvalidAuthToken, err) } ctx = metadata.NewIncomingContext(context.Background(), metadata.New(map[string]string{rpctypes.TokenFieldNameGRPC: "Invalid.Token"})) _, err = as.AuthInfoFromCtx(ctx) - if err != ErrInvalidAuthToken { + if !errors.Is(err, ErrInvalidAuthToken) { t.Errorf("expected %v, got %v", ErrInvalidAuthToken, err) } @@ -914,14 +914,14 @@ func TestAuthDisable(t *testing.T) { as.AuthDisable() ctx := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(2)), AuthenticateParamSimpleTokenPrefix{}, "dummy") _, err := as.Authenticate(ctx, "foo", "bar") - if err != ErrAuthNotEnabled { + if !errors.Is(err, ErrAuthNotEnabled) { t.Errorf("expected %v, got %v", ErrAuthNotEnabled, err) } // Disabling disabled auth to make sure it can return safely if store is already disabled. as.AuthDisable() _, err = as.Authenticate(ctx, "foo", "bar") - if err != ErrAuthNotEnabled { + if !errors.Is(err, ErrAuthNotEnabled) { t.Errorf("expected %v, got %v", ErrAuthNotEnabled, err) } } @@ -980,19 +980,19 @@ func TestIsAdminPermitted(t *testing.T) { // invalid user err = as.IsAdminPermitted(&AuthInfo{Username: "rooti", Revision: 1}) - if err != ErrUserNotFound { + if !errors.Is(err, ErrUserNotFound) { t.Errorf("expected %v, got %v", ErrUserNotFound, err) } // empty user err = as.IsAdminPermitted(&AuthInfo{Username: "", Revision: 1}) - if err != ErrUserEmpty { + if !errors.Is(err, ErrUserEmpty) { t.Errorf("expected %v, got %v", ErrUserEmpty, err) } // non-admin user err = as.IsAdminPermitted(&AuthInfo{Username: "foo", Revision: 1}) - if err != ErrPermissionDenied { + if !errors.Is(err, ErrPermissionDenied) { t.Errorf("expected %v, got %v", ErrPermissionDenied, err) } @@ -1013,13 +1013,13 @@ func TestRecoverFromSnapshot(t *testing.T) { if err == nil { t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err) } - if err != ErrUserAlreadyExist { + if !errors.Is(err, ErrUserAlreadyExist) { t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err) } ua = &pb.AuthUserAddRequest{Name: "", Options: &authpb.UserAddOptions{NoPassword: false}} _, err = as.UserAdd(ua) // add a user with empty name - if err != ErrUserEmpty { + if !errors.Is(err, ErrUserEmpty) { t.Fatal(err) } @@ -1195,7 +1195,7 @@ func TestUserNoPasswordAdd(t *testing.T) { ctx := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(1)), AuthenticateParamSimpleTokenPrefix{}, "dummy") _, err = as.Authenticate(ctx, username, "") - if err != ErrAuthFailed { + if !errors.Is(err, ErrAuthFailed) { t.Fatalf("expected %v, got %v", ErrAuthFailed, err) } } @@ -1237,7 +1237,7 @@ func TestUserChangePasswordWithOldLog(t *testing.T) { if err == nil { t.Fatalf("expected %v, got %v", ErrUserNotFound, err) } - if err != ErrUserNotFound { + if !errors.Is(err, ErrUserNotFound) { t.Fatalf("expected %v, got %v", ErrUserNotFound, err) } } diff --git a/server/embed/etcd_test.go b/server/embed/etcd_test.go index e22b6d3544a..206cbb737b4 100644 --- a/server/embed/etcd_test.go +++ b/server/embed/etcd_test.go @@ -15,6 +15,7 @@ package embed import ( + "errors" "net/url" "testing" @@ -32,7 +33,7 @@ func TestEmptyClientTLSInfo_createMetricsListener(t *testing.T) { Scheme: "https", Host: "localhost:8080", } - if _, err := e.createMetricsListener(murl); err != ErrMissingClientTLSInfoForMetricsURL { + if _, err := e.createMetricsListener(murl); !errors.Is(err, ErrMissingClientTLSInfoForMetricsURL) { t.Fatalf("expected error %v, got %v", ErrMissingClientTLSInfoForMetricsURL, err) } } diff --git a/server/embed/serve_test.go b/server/embed/serve_test.go index 3e23c9ee9af..6150beeecf1 100644 --- a/server/embed/serve_test.go +++ b/server/embed/serve_test.go @@ -15,6 +15,7 @@ package embed import ( + "errors" "fmt" "net/url" "os" @@ -43,7 +44,7 @@ func TestStartEtcdWrongToken(t *testing.T) { cfg.Dir = tdir cfg.AuthToken = "wrong-token" - if _, err := StartEtcd(cfg); err != auth.ErrInvalidAuthOpts { + if _, err := StartEtcd(cfg); !errors.Is(err, auth.ErrInvalidAuthOpts) { t.Fatalf("expected %v, got %v", auth.ErrInvalidAuthOpts, err) } } diff --git a/server/etcdmain/config_test.go b/server/etcdmain/config_test.go index 21ceaafb0e5..f002102897a 100644 --- a/server/etcdmain/config_test.go +++ b/server/etcdmain/config_test.go @@ -15,6 +15,7 @@ package etcdmain import ( + "errors" "flag" "fmt" "net/url" @@ -224,7 +225,7 @@ func TestConfigParsingConflictClusteringFlags(t *testing.T) { for i, tt := range conflictArgs { cfg := newConfig() - if err := cfg.parse(tt); err != embed.ErrConflictBootstrapFlags { + if err := cfg.parse(tt); !errors.Is(err, embed.ErrConflictBootstrapFlags) { t.Errorf("%d: err = %v, want %v", i, err, embed.ErrConflictBootstrapFlags) } } @@ -267,7 +268,7 @@ func TestConfigFileConflictClusteringFlags(t *testing.T) { args := []string{fmt.Sprintf("--config-file=%s", tmpfile.Name())} cfg := newConfig() - if err := cfg.parse(args); err != embed.ErrConflictBootstrapFlags { + if err := cfg.parse(args); !errors.Is(err, embed.ErrConflictBootstrapFlags) { t.Errorf("%d: err = %v, want %v", i, err, embed.ErrConflictBootstrapFlags) } } @@ -310,7 +311,7 @@ func TestConfigParsingMissedAdvertiseClientURLsFlag(t *testing.T) { for i, tt := range tests { cfg := newConfig() - if err := cfg.parse(tt.args); err != tt.werr { + if err := cfg.parse(tt.args); !errors.Is(err, tt.werr) { t.Errorf("%d: err = %v, want %v", i, err, tt.werr) } } diff --git a/server/etcdserver/api/membership/cluster_test.go b/server/etcdserver/api/membership/cluster_test.go index e5eb210c887..c07093878c9 100644 --- a/server/etcdserver/api/membership/cluster_test.go +++ b/server/etcdserver/api/membership/cluster_test.go @@ -16,6 +16,7 @@ package membership import ( "encoding/json" + "errors" "fmt" "path" "reflect" @@ -458,7 +459,7 @@ func TestClusterValidateConfigurationChangeV2(t *testing.T) { } for i, tt := range tests { err := cl.ValidateConfigurationChange(tt.cc) - if err != tt.werr { + if !errors.Is(err, tt.werr) { t.Errorf("#%d: validateConfigurationChange error = %v, want %v", i, err, tt.werr) } } diff --git a/server/etcdserver/api/rafthttp/msg_codec_test.go b/server/etcdserver/api/rafthttp/msg_codec_test.go index 9b14b45095e..cde7916fc1b 100644 --- a/server/etcdserver/api/rafthttp/msg_codec_test.go +++ b/server/etcdserver/api/rafthttp/msg_codec_test.go @@ -16,6 +16,7 @@ package rafthttp import ( "bytes" + "errors" "reflect" "testing" @@ -77,13 +78,13 @@ func TestMessage(t *testing.T) { for i, tt := range tests { b := &bytes.Buffer{} enc := &messageEncoder{w: b} - if err := enc.encode(&tt.msg); err != tt.encodeErr { + if err := enc.encode(&tt.msg); !errors.Is(err, tt.encodeErr) { t.Errorf("#%d: encode message error expected %v, got %v", i, tt.encodeErr, err) continue } dec := &messageDecoder{r: b} m, err := dec.decode() - if err != tt.decodeErr { + if !errors.Is(err, tt.decodeErr) { t.Errorf("#%d: decode message error expected %v, got %v", i, tt.decodeErr, err) continue } diff --git a/server/etcdserver/api/rafthttp/pipeline.go b/server/etcdserver/api/rafthttp/pipeline.go index 50b8c8dd3f1..0790b58d03b 100644 --- a/server/etcdserver/api/rafthttp/pipeline.go +++ b/server/etcdserver/api/rafthttp/pipeline.go @@ -165,7 +165,7 @@ func (p *pipeline) post(data []byte) (err error) { p.picker.unreachable(u) // errMemberRemoved is a critical error since a removed member should // always be stopped. So we use reportCriticalError to report it to errorc. - if err == errMemberRemoved { + if errors.Is(err, errMemberRemoved) { reportCriticalError(err, p.errorc) } return err diff --git a/server/etcdserver/api/rafthttp/snapshot_sender.go b/server/etcdserver/api/rafthttp/snapshot_sender.go index 1f0253f1465..07971cbbddc 100644 --- a/server/etcdserver/api/rafthttp/snapshot_sender.go +++ b/server/etcdserver/api/rafthttp/snapshot_sender.go @@ -17,6 +17,7 @@ package rafthttp import ( "bytes" "context" + "errors" "io" "net/http" "time" @@ -110,7 +111,7 @@ func (s *snapshotSender) send(merged snap.Message) { // errMemberRemoved is a critical error since a removed member should // always be stopped. So we use reportCriticalError to report it to errorc. - if err == errMemberRemoved { + if errors.Is(err, errMemberRemoved) { reportCriticalError(err, s.errorc) } diff --git a/server/etcdserver/api/rafthttp/stream.go b/server/etcdserver/api/rafthttp/stream.go index 63ffe8fdcbe..ed91b27bd78 100644 --- a/server/etcdserver/api/rafthttp/stream.go +++ b/server/etcdserver/api/rafthttp/stream.go @@ -16,6 +16,7 @@ package rafthttp import ( "context" + "errors" "fmt" "io" "net/http" @@ -403,7 +404,7 @@ func (cr *streamReader) run() { for { rc, err := cr.dial(t) if err != nil { - if err != errUnsupportedStreamType { + if !errors.Is(err, errUnsupportedStreamType) { cr.status.deactivate(failureType{source: t.String(), action: "dial"}, err.Error()) } } else { @@ -428,7 +429,7 @@ func (cr *streamReader) run() { } switch { // all data is read out - case err == io.EOF: + case errors.Is(err, io.EOF): // connection is closed by the remote case transport.IsClosedConnError(err): default: diff --git a/server/etcdserver/api/rafthttp/stream_test.go b/server/etcdserver/api/rafthttp/stream_test.go index 5ff4265e568..428010286d9 100644 --- a/server/etcdserver/api/rafthttp/stream_test.go +++ b/server/etcdserver/api/rafthttp/stream_test.go @@ -256,7 +256,7 @@ func TestStreamReaderDialDetectUnsupport(t *testing.T) { } _, err := sr.dial(typ) - if err != errUnsupportedStreamType { + if !errors.Is(err, errUnsupportedStreamType) { t.Errorf("#%d: error = %v, want %v", i, err, errUnsupportedStreamType) } } diff --git a/server/etcdserver/api/snap/snapshotter_test.go b/server/etcdserver/api/snap/snapshotter_test.go index 02ce02b4a13..cad3059fb18 100644 --- a/server/etcdserver/api/snap/snapshotter_test.go +++ b/server/etcdserver/api/snap/snapshotter_test.go @@ -15,6 +15,7 @@ package snap import ( + "errors" "fmt" "hash/crc32" "os" @@ -80,7 +81,7 @@ func TestBadCRC(t *testing.T) { crcTable = crc32.MakeTable(crc32.Koopman) _, err = Read(zaptest.NewLogger(t), filepath.Join(dir, fmt.Sprintf("%016x-%016x.snap", 1, 1))) - if err == nil || err != ErrCRCMismatch { + if err == nil || !errors.Is(err, ErrCRCMismatch) { t.Errorf("err = %v, want %v", err, ErrCRCMismatch) } } @@ -221,7 +222,7 @@ func TestNoSnapshot(t *testing.T) { defer os.RemoveAll(dir) ss := New(zaptest.NewLogger(t), dir) _, err = ss.Load() - if err != ErrNoSnapshot { + if !errors.Is(err, ErrNoSnapshot) { t.Errorf("err = %v, want %v", err, ErrNoSnapshot) } } @@ -240,7 +241,7 @@ func TestEmptySnapshot(t *testing.T) { } _, err = Read(zaptest.NewLogger(t), filepath.Join(dir, "1.snap")) - if err != ErrEmptySnapshot { + if !errors.Is(err, ErrEmptySnapshot) { t.Errorf("err = %v, want %v", err, ErrEmptySnapshot) } } @@ -262,7 +263,7 @@ func TestAllSnapshotBroken(t *testing.T) { ss := New(zaptest.NewLogger(t), dir) _, err = ss.Load() - if err != ErrNoSnapshot { + if !errors.Is(err, ErrNoSnapshot) { t.Errorf("err = %v, want %v", err, ErrNoSnapshot) } } diff --git a/server/etcdserver/api/v2discovery/discovery.go b/server/etcdserver/api/v2discovery/discovery.go index 5993d4458ec..039c8da7d52 100644 --- a/server/etcdserver/api/v2discovery/discovery.go +++ b/server/etcdserver/api/v2discovery/discovery.go @@ -187,7 +187,7 @@ func (d *discovery) joinCluster(config string) (string, error) { func (d *discovery) getCluster() (string, error) { nodes, size, index, err := d.checkCluster() if err != nil { - if err == ErrFullCluster { + if errors.Is(err, ErrFullCluster) { return nodesToCluster(nodes, size) } return "", err @@ -227,7 +227,7 @@ func (d *discovery) checkCluster() ([]*client.Node, uint64, uint64, error) { if eerr, ok := err.(*client.Error); ok && eerr.Code == client.ErrorCodeKeyNotFound { return nil, 0, 0, ErrSizeNotFound } - if err == client.ErrInvalidJSON { + if errors.Is(err, client.ErrInvalidJSON) { return nil, 0, 0, ErrBadDiscoveryEndpoint } if ce, ok := err.(*client.ClusterError); ok { diff --git a/server/etcdserver/api/v2discovery/discovery_test.go b/server/etcdserver/api/v2discovery/discovery_test.go index 91dbfd72aac..3b59517f999 100644 --- a/server/etcdserver/api/v2discovery/discovery_test.go +++ b/server/etcdserver/api/v2discovery/discovery_test.go @@ -212,7 +212,7 @@ func TestCheckCluster(t *testing.T) { } }() ns, size, index, err := d.checkCluster() - if err != tt.werr { + if !errors.Is(err, tt.werr) { t.Errorf("#%d: err = %v, want %v", i, err, tt.werr) } if reflect.DeepEqual(ns, tt.nodes) { @@ -336,7 +336,7 @@ func TestCreateSelf(t *testing.T) { for i, tt := range tests { d := newTestDiscovery(t, "1000", 1, tt.c) - if err := d.createSelf(""); err != tt.werr { + if err := d.createSelf(""); !errors.Is(err, tt.werr) { t.Errorf("#%d: err = %v, want %v", i, err, nil) } } @@ -383,7 +383,7 @@ func TestNodesToCluster(t *testing.T) { for i, tt := range tests { cluster, err := nodesToCluster(tt.nodes, tt.size) - if err != tt.werr { + if !errors.Is(err, tt.werr) { t.Errorf("#%d: err = %v, want %v", i, err, tt.werr) } if !reflect.DeepEqual(cluster, tt.wcluster) { @@ -435,7 +435,7 @@ func TestRetryFailure(t *testing.T) { fc.Advance(time.Second * (0x1 << i)) } }() - if _, _, _, err := d.checkCluster(); err != ErrTooManyRetries { + if _, _, _, err := d.checkCluster(); !errors.Is(err, ErrTooManyRetries) { t.Errorf("err = %v, want %v", err, ErrTooManyRetries) } } diff --git a/server/etcdserver/api/v3discovery/discovery_test.go b/server/etcdserver/api/v3discovery/discovery_test.go index 10d63e6486d..89b4d3cbbef 100644 --- a/server/etcdserver/api/v3discovery/discovery_test.go +++ b/server/etcdserver/api/v3discovery/discovery_test.go @@ -91,7 +91,7 @@ func TestGetClusterSize(t *testing.T) { clusterToken: "fakeToken", } - if cs, err := d.getClusterSize(); err != tc.expectedErr { + if cs, err := d.getClusterSize(); !errors.Is(err, tc.expectedErr) { t.Errorf("Unexpected error, expected: %v got: %v", tc.expectedErr, err) } else { if err == nil && cs != tc.expectedSize { @@ -387,7 +387,7 @@ func TestCheckCluster(t *testing.T) { } clsInfo, _, _, err := d.checkCluster() - if err != tc.expectedError { + if !errors.Is(err, tc.expectedError) { t.Errorf("Unexpected error, expected: %v, got: %v", tc.expectedError, err) } @@ -724,7 +724,7 @@ func TestGetInitClusterStr(t *testing.T) { } retStr, err := clsInfo.getInitClusterStr(tc.clusterSize) - if err != tc.expectedError { + if !errors.Is(err, tc.expectedError) { t.Errorf("Unexpected error, expected: %v, got: %v", tc.expectedError, err) } diff --git a/server/etcdserver/api/v3rpc/lease.go b/server/etcdserver/api/v3rpc/lease.go index 86f35113cd9..19c5973bd81 100644 --- a/server/etcdserver/api/v3rpc/lease.go +++ b/server/etcdserver/api/v3rpc/lease.go @@ -16,6 +16,7 @@ package v3rpc import ( "context" + "errors" "io" "go.uber.org/zap" @@ -61,10 +62,10 @@ func (ls *LeaseServer) LeaseRevoke(ctx context.Context, rr *pb.LeaseRevokeReques func (ls *LeaseServer) LeaseTimeToLive(ctx context.Context, rr *pb.LeaseTimeToLiveRequest) (*pb.LeaseTimeToLiveResponse, error) { resp, err := ls.le.LeaseTimeToLive(ctx, rr) - if err != nil && err != lease.ErrLeaseNotFound { + if err != nil && !errors.Is(err, lease.ErrLeaseNotFound) { return nil, togRPCError(err) } - if err == lease.ErrLeaseNotFound { + if errors.Is(err, lease.ErrLeaseNotFound) { resp = &pb.LeaseTimeToLiveResponse{ Header: &pb.ResponseHeader{}, ID: rr.ID, @@ -80,7 +81,7 @@ func (ls *LeaseServer) LeaseLeases(ctx context.Context, rr *pb.LeaseLeasesReques if err != nil && err != lease.ErrLeaseNotFound { return nil, togRPCError(err) } - if err == lease.ErrLeaseNotFound { + if errors.Is(err, lease.ErrLeaseNotFound) { resp = &pb.LeaseLeasesResponse{ Header: &pb.ResponseHeader{}, Leases: []*pb.LeaseStatus{}, @@ -100,7 +101,7 @@ func (ls *LeaseServer) LeaseKeepAlive(stream pb.Lease_LeaseKeepAliveServer) (err case <-stream.Context().Done(): // the only server-side cancellation is noleader for now. err = stream.Context().Err() - if err == context.Canceled { + if errors.Is(err, context.Canceled) { err = rpctypes.ErrGRPCNoLeader } } @@ -110,7 +111,7 @@ func (ls *LeaseServer) LeaseKeepAlive(stream pb.Lease_LeaseKeepAliveServer) (err func (ls *LeaseServer) leaseKeepAlive(stream pb.Lease_LeaseKeepAliveServer) error { for { req, err := stream.Recv() - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } if err != nil { @@ -133,7 +134,7 @@ func (ls *LeaseServer) leaseKeepAlive(stream pb.Lease_LeaseKeepAliveServer) erro ls.hdr.fill(resp.Header) ttl, err := ls.le.LeaseRenew(stream.Context(), lease.LeaseID(req.ID)) - if err == lease.ErrLeaseNotFound { + if errors.Is(err, lease.ErrLeaseNotFound) { err = nil ttl = 0 } diff --git a/server/etcdserver/api/v3rpc/util.go b/server/etcdserver/api/v3rpc/util.go index a31e6cbecca..2354b0cb243 100644 --- a/server/etcdserver/api/v3rpc/util.go +++ b/server/etcdserver/api/v3rpc/util.go @@ -16,6 +16,7 @@ package v3rpc import ( "context" + errorspkg "errors" "strings" "google.golang.org/grpc/codes" @@ -95,7 +96,7 @@ var toGRPCErrorMap = map[error]error{ func togRPCError(err error) error { // let gRPC server convert to codes.Canceled, codes.DeadlineExceeded - if err == context.Canceled || err == context.DeadlineExceeded { + if errorspkg.Is(err, context.Canceled) || errorspkg.Is(err, context.DeadlineExceeded) { return err } grpcErr, ok := toGRPCErrorMap[err] diff --git a/server/etcdserver/api/v3rpc/util_test.go b/server/etcdserver/api/v3rpc/util_test.go index ed686021d2b..8bd569301c4 100644 --- a/server/etcdserver/api/v3rpc/util_test.go +++ b/server/etcdserver/api/v3rpc/util_test.go @@ -38,7 +38,7 @@ func TestGRPCError(t *testing.T) { {err: errors.New("foo"), exp: status.Error(codes.Unknown, "foo")}, } for i := range tt { - if err := togRPCError(tt[i].err); err != tt[i].exp { + if err := togRPCError(tt[i].err); !errors.Is(err, tt[i].exp) { if _, ok := status.FromError(err); ok { if err.Error() == tt[i].exp.Error() { continue diff --git a/server/etcdserver/api/v3rpc/watch.go b/server/etcdserver/api/v3rpc/watch.go index 6e72b1ceb89..abb465e21d7 100644 --- a/server/etcdserver/api/v3rpc/watch.go +++ b/server/etcdserver/api/v3rpc/watch.go @@ -16,6 +16,7 @@ package v3rpc import ( "context" + "errors" "io" "math/rand" "sync" @@ -211,13 +212,13 @@ func (ws *watchServer) Watch(stream pb.Watch_WatchServer) (err error) { // revisited. select { case err = <-errc: - if err == context.Canceled { + if errors.Is(err, context.Canceled) { err = rpctypes.ErrGRPCWatchCanceled } close(sws.ctrlStream) case <-stream.Context().Done(): err = stream.Context().Err() - if err == context.Canceled { + if errors.Is(err, context.Canceled) { err = rpctypes.ErrGRPCWatchCanceled } } @@ -241,7 +242,7 @@ func (sws *serverWatchStream) isWatchPermitted(wcr *pb.WatchCreateRequest) error func (sws *serverWatchStream) recvLoop() error { for { req, err := sws.gRPCStream.Recv() - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } if err != nil { @@ -280,7 +281,7 @@ func (sws *serverWatchStream) recvLoop() error { case auth.ErrUserEmpty: cancelReason = rpctypes.ErrGRPCUserEmpty.Error() default: - if err != auth.ErrPermissionDenied { + if !errors.Is(err, auth.ErrPermissionDenied) { sws.lg.Error("unexpected error code", zap.Error(err)) } cancelReason = rpctypes.ErrGRPCPermissionDenied.Error() diff --git a/server/etcdserver/api/v3rpc/watch_test.go b/server/etcdserver/api/v3rpc/watch_test.go index bd3f4943b2e..e7868ddf8d2 100644 --- a/server/etcdserver/api/v3rpc/watch_test.go +++ b/server/etcdserver/api/v3rpc/watch_test.go @@ -16,6 +16,7 @@ package v3rpc import ( "bytes" + "errors" "math" "testing" @@ -69,7 +70,7 @@ func TestSendFragment(t *testing.T) { return nil } err := sendFragments(tt[i].wr, tt[i].maxRequestBytes, testSend) - if err != tt[i].werr { + if !errors.Is(err, tt[i].werr) { t.Errorf("#%d: expected error %v, got %v", i, tt[i].werr, err) } got := len(fragmentedResp) diff --git a/server/etcdserver/apply/apply_auth_test.go b/server/etcdserver/apply/apply_auth_test.go index 6516f41b52f..e7445a10aa9 100644 --- a/server/etcdserver/apply/apply_auth_test.go +++ b/server/etcdserver/apply/apply_auth_test.go @@ -16,6 +16,7 @@ package apply import ( "context" + "errors" "testing" "time" @@ -387,8 +388,8 @@ func TestAuthApplierV3_AdminPermission(t *testing.T) { tc.request.Header = &pb.RequestHeader{Username: userReadOnly} } result := authApplier.Apply(ctx, tc.request, dummyApplyFunc) - require.Equal(t, result.Err == auth.ErrPermissionDenied, tc.adminPermissionNeeded, - "Admin permission needed: got %v, expect: %v", result.Err == auth.ErrPermissionDenied, tc.adminPermissionNeeded) + require.Equal(t, errors.Is(result.Err, auth.ErrPermissionDenied), tc.adminPermissionNeeded, + "Admin permission needed: got %v, expect: %v", errors.Is(result.Err, auth.ErrPermissionDenied), tc.adminPermissionNeeded) }) } } diff --git a/server/etcdserver/server_test.go b/server/etcdserver/server_test.go index 858aa32a076..e26d6412722 100644 --- a/server/etcdserver/server_test.go +++ b/server/etcdserver/server_test.go @@ -17,6 +17,7 @@ package etcdserver import ( "context" "encoding/json" + errorspkg "errors" "fmt" "math" "net/http" @@ -388,7 +389,7 @@ func TestApplyConfChangeError(t *testing.T) { cluster: cl, } _, err := srv.applyConfChange(tt.cc, nil, true) - if err != tt.werr { + if !errorspkg.Is(err, tt.werr) { t.Errorf("#%d: applyConfChange error = %v, want %v", i, err, tt.werr) } cc := raftpb.ConfChange{Type: tt.cc.Type, NodeID: raft.None, Context: tt.cc.Context} @@ -1533,7 +1534,7 @@ func TestWaitAppliedIndex(t *testing.T) { err := s.waitAppliedIndex() - if err != tc.ExpectedError { + if !errorspkg.Is(err, tc.ExpectedError) { t.Errorf("Unexpected error, want (%v), got (%v)", tc.ExpectedError, err) } }) diff --git a/server/lease/leasehttp/http.go b/server/lease/leasehttp/http.go index 5837ac40b17..9592b63cb97 100644 --- a/server/lease/leasehttp/http.go +++ b/server/lease/leasehttp/http.go @@ -75,7 +75,7 @@ func (h *leaseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } ttl, rerr := h.l.Renew(lease.LeaseID(lreq.ID)) if rerr != nil { - if rerr == lease.ErrLeaseNotFound { + if errors.Is(rerr, lease.ErrLeaseNotFound) { http.Error(w, rerr.Error(), http.StatusNotFound) return } diff --git a/server/lease/lessor_test.go b/server/lease/lessor_test.go index 0d32300abaf..f46e2b39949 100644 --- a/server/lease/lessor_test.go +++ b/server/lease/lessor_test.go @@ -16,6 +16,7 @@ package lease import ( "context" + "errors" "fmt" "os" "path/filepath" @@ -454,7 +455,7 @@ func TestLessorExpire(t *testing.T) { donec := make(chan struct{}, 1) go func() { // expired lease cannot be renewed - if _, err := le.Renew(l.ID); err != ErrLeaseNotFound { + if _, err := le.Renew(l.ID); !errors.Is(err, ErrLeaseNotFound) { t.Errorf("unexpected renew") } donec <- struct{}{} @@ -507,7 +508,7 @@ func TestLessorExpireAndDemote(t *testing.T) { donec := make(chan struct{}, 1) go func() { // expired lease cannot be renewed - if _, err := le.Renew(l.ID); err != ErrNotPrimary { + if _, err := le.Renew(l.ID); !errors.Is(err, ErrNotPrimary) { t.Errorf("unexpected renew: %v", err) } donec <- struct{}{} @@ -539,7 +540,7 @@ func TestLessorMaxTTL(t *testing.T) { defer le.Stop() _, err := le.Grant(1, MaxLeaseTTL+1) - if err != ErrLeaseTTLTooLarge { + if !errors.Is(err, ErrLeaseTTLTooLarge) { t.Fatalf("grant unexpectedly succeeded") } } diff --git a/server/proxy/grpcproxy/lease.go b/server/proxy/grpcproxy/lease.go index fdc936ca929..dc42dc5a0d8 100644 --- a/server/proxy/grpcproxy/lease.go +++ b/server/proxy/grpcproxy/lease.go @@ -16,6 +16,7 @@ package grpcproxy import ( "context" + "errors" "io" "sync" "sync/atomic" @@ -245,7 +246,7 @@ type leaseProxyStream struct { func (lps *leaseProxyStream) recvLoop() error { for { rr, err := lps.stream.Recv() - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } if err != nil { diff --git a/server/proxy/grpcproxy/maintenance.go b/server/proxy/grpcproxy/maintenance.go index 50ecf67ffa0..553b66c4b73 100644 --- a/server/proxy/grpcproxy/maintenance.go +++ b/server/proxy/grpcproxy/maintenance.go @@ -16,6 +16,7 @@ package grpcproxy import ( "context" + "errors" "io" pb "go.etcd.io/etcd/api/v3/etcdserverpb" @@ -50,7 +51,7 @@ func (mp *maintenanceProxy) Snapshot(sr *pb.SnapshotRequest, stream pb.Maintenan for { rr, err := sc.Recv() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } return err diff --git a/server/storage/mvcc/index_test.go b/server/storage/mvcc/index_test.go index 5973ecbe4be..64c5ecd407e 100644 --- a/server/storage/mvcc/index_test.go +++ b/server/storage/mvcc/index_test.go @@ -15,6 +15,7 @@ package mvcc import ( + "errors" "reflect" "testing" @@ -46,7 +47,7 @@ func TestIndexGet(t *testing.T) { } for i, tt := range tests { rev, created, ver, err := ti.Get([]byte("foo"), tt.rev) - if err != tt.werr { + if !errors.Is(err, tt.werr) { t.Errorf("#%d: err = %v, want %v", i, err, tt.werr) } if rev != tt.wrev { @@ -130,11 +131,11 @@ func TestIndexTombstone(t *testing.T) { } _, _, _, err = ti.Get([]byte("foo"), 2) - if err != ErrRevisionNotFound { + if !errors.Is(err, ErrRevisionNotFound) { t.Errorf("get error = %v, want ErrRevisionNotFound", err) } err = ti.Tombstone([]byte("foo"), Revision{Main: 3}) - if err != ErrRevisionNotFound { + if !errors.Is(err, ErrRevisionNotFound) { t.Errorf("tombstone error = %v, want %v", err, ErrRevisionNotFound) } } diff --git a/server/storage/mvcc/key_index_test.go b/server/storage/mvcc/key_index_test.go index 63436428cbd..273f06e3402 100644 --- a/server/storage/mvcc/key_index_test.go +++ b/server/storage/mvcc/key_index_test.go @@ -15,6 +15,7 @@ package mvcc import ( + "errors" "reflect" "testing" @@ -73,7 +74,7 @@ func TestKeyIndexGet(t *testing.T) { for i, tt := range tests { mod, creat, ver, err := ki.get(zaptest.NewLogger(t), tt.rev) - if err != tt.werr { + if !errors.Is(err, tt.werr) { t.Errorf("#%d: err = %v, want %v", i, err, tt.werr) } if mod != tt.wmod { @@ -213,7 +214,7 @@ func TestKeyIndexTombstone(t *testing.T) { } err = ki.tombstone(zaptest.NewLogger(t), 16, 0) - if err != ErrRevisionNotFound { + if !errors.Is(err, ErrRevisionNotFound) { t.Errorf("tombstone error = %v, want %v", err, ErrRevisionNotFound) } } diff --git a/server/storage/mvcc/kv_test.go b/server/storage/mvcc/kv_test.go index 9b8243c334c..0a3a2ad736f 100644 --- a/server/storage/mvcc/kv_test.go +++ b/server/storage/mvcc/kv_test.go @@ -16,6 +16,7 @@ package mvcc import ( "context" + "errors" "fmt" "os" "reflect" @@ -203,7 +204,7 @@ func testKVRangeBadRev(t *testing.T, f rangeFunc) { } for i, tt := range tests { _, err := f(s, []byte("foo"), []byte("foo3"), RangeOptions{Rev: tt.rev}) - if err != tt.werr { + if !errors.Is(err, tt.werr) { t.Errorf("#%d: error = %v, want %v", i, err, tt.werr) } } @@ -626,7 +627,7 @@ func TestKVCompactBad(t *testing.T) { } for i, tt := range tests { _, err := s.Compact(traceutil.TODO(), tt.rev) - if err != tt.werr { + if !errors.Is(err, tt.werr) { t.Errorf("#%d: compact error = %v, want %v", i, err, tt.werr) } } diff --git a/server/storage/mvcc/kvstore_test.go b/server/storage/mvcc/kvstore_test.go index 0523dcde983..ed14cdebd68 100644 --- a/server/storage/mvcc/kvstore_test.go +++ b/server/storage/mvcc/kvstore_test.go @@ -19,6 +19,7 @@ import ( "context" "crypto/rand" "encoding/binary" + "errors" "fmt" "math" mrand "math/rand" @@ -518,7 +519,7 @@ func TestRestoreContinueUnfinishedCompaction(t *testing.T) { // wait for scheduled compaction to be finished time.Sleep(100 * time.Millisecond) - if _, err := s.Range(context.TODO(), []byte("foo"), nil, RangeOptions{Rev: 1}); err != ErrCompacted { + if _, err := s.Range(context.TODO(), []byte("foo"), nil, RangeOptions{Rev: 1}); !errors.Is(err, ErrCompacted) { t.Errorf("range on compacted rev error = %v, want %v", err, ErrCompacted) } // check the key in backend is deleted diff --git a/server/storage/mvcc/watcher_test.go b/server/storage/mvcc/watcher_test.go index 41bbb510875..a53253a08c0 100644 --- a/server/storage/mvcc/watcher_test.go +++ b/server/storage/mvcc/watcher_test.go @@ -16,6 +16,7 @@ package mvcc import ( "bytes" + "errors" "fmt" "os" "reflect" @@ -108,7 +109,7 @@ func TestWatcherRequestsCustomID(t *testing.T) { for i, tcase := range tt { id, err := w.Watch(tcase.givenID, []byte("foo"), nil, 0) if tcase.expectedErr != nil || err != nil { - if err != tcase.expectedErr { + if !errors.Is(err, tcase.expectedErr) { t.Errorf("expected get error %q in test case %q, got %q", tcase.expectedErr, i, err) } } else if tcase.expectedID != id { @@ -201,10 +202,10 @@ func TestWatcherWatchWrongRange(t *testing.T) { w := s.NewWatchStream() defer w.Close() - if _, err := w.Watch(0, []byte("foa"), []byte("foa"), 1); err != ErrEmptyWatcherRange { + if _, err := w.Watch(0, []byte("foa"), []byte("foa"), 1); !errors.Is(err, ErrEmptyWatcherRange) { t.Fatalf("key == end range given; expected ErrEmptyWatcherRange, got %+v", err) } - if _, err := w.Watch(0, []byte("fob"), []byte("foa"), 1); err != ErrEmptyWatcherRange { + if _, err := w.Watch(0, []byte("fob"), []byte("foa"), 1); !errors.Is(err, ErrEmptyWatcherRange) { t.Fatalf("key > end range given; expected ErrEmptyWatcherRange, got %+v", err) } // watch request with 'WithFromKey' has empty-byte range end @@ -278,7 +279,7 @@ func TestWatchStreamCancelWatcherByID(t *testing.T) { for i, tt := range tests { gerr := w.Cancel(tt.cancelID) - if gerr != tt.werr { + if !errors.Is(gerr, tt.werr) { t.Errorf("#%d: err = %v, want %v", i, gerr, tt.werr) } } diff --git a/server/storage/schema/actions_test.go b/server/storage/schema/actions_test.go index 4e61a0dac9a..d3cb812c11e 100644 --- a/server/storage/schema/actions_test.go +++ b/server/storage/schema/actions_test.go @@ -15,6 +15,7 @@ package schema import ( + "errors" "fmt" "testing" "time" @@ -135,7 +136,7 @@ func TestActionListRevert(t *testing.T) { UnsafeCreateMetaBucket(tx) err := tc.actions.unsafeExecute(lg, tx) - if err != tc.expectError { + if !errors.Is(err, tc.expectError) { t.Errorf("Unexpected error or lack thereof, expected: %v, got: %v", tc.expectError, err) } assertBucketState(t, tx, Meta, tc.expectState) diff --git a/server/storage/schema/migration_test.go b/server/storage/schema/migration_test.go index fccf2029689..9ebe80dcb05 100644 --- a/server/storage/schema/migration_test.go +++ b/server/storage/schema/migration_test.go @@ -15,6 +15,7 @@ package schema import ( + "errors" "fmt" "testing" "time" @@ -178,7 +179,7 @@ func TestMigrationStepExecute(t *testing.T) { step := newMigrationStep(tc.currentVersion, tc.isUpgrade, tc.changes) err := step.unsafeExecute(lg, tx) - if err != tc.expectError { + if !errors.Is(err, tc.expectError) { t.Errorf("Unexpected error or lack thereof, expected: %v, got: %v", tc.expectError, err) } v := UnsafeReadStorageVersion(tx) diff --git a/server/storage/wal/decoder.go b/server/storage/wal/decoder.go index 0f47b72fd3e..01ffbd52bd9 100644 --- a/server/storage/wal/decoder.go +++ b/server/storage/wal/decoder.go @@ -16,6 +16,7 @@ package wal import ( "encoding/binary" + "errors" "fmt" "hash" "io" @@ -114,7 +115,7 @@ func (d *decoder) decodeRecord(rec *walpb.Record) error { if _, err = io.ReadFull(fileBufReader, data); err != nil { // ReadFull returns io.EOF only if no bytes were read // the decoder should treat this as an ErrUnexpectedEOF instead. - if err == io.EOF { + if errors.Is(err, io.EOF) { err = io.ErrUnexpectedEOF } return err diff --git a/server/storage/wal/repair_test.go b/server/storage/wal/repair_test.go index 38e3641bd7b..a1abdcac38d 100644 --- a/server/storage/wal/repair_test.go +++ b/server/storage/wal/repair_test.go @@ -15,6 +15,7 @@ package wal import ( + "errors" "fmt" "io" "os" @@ -202,7 +203,7 @@ func TestRepairFailDeleteDir(t *testing.T) { t.Fatal(err) } _, _, _, err = w.ReadAll() - if err != io.ErrUnexpectedEOF { + if !errors.Is(err, io.ErrUnexpectedEOF) { t.Fatalf("err = %v, want error %v", err, io.ErrUnexpectedEOF) } w.Close() diff --git a/server/storage/wal/wal_test.go b/server/storage/wal/wal_test.go index ed3a8893df5..c739ddf0a55 100644 --- a/server/storage/wal/wal_test.go +++ b/server/storage/wal/wal_test.go @@ -101,7 +101,7 @@ func TestCreateFailFromPollutedDir(t *testing.T) { os.WriteFile(filepath.Join(p, "test.wal"), []byte("data"), os.ModeTemporary) _, err := Create(zaptest.NewLogger(t), p, []byte("data")) - if err != os.ErrExist { + if !errors.Is(err, os.ErrExist) { t.Fatalf("expected %v, got %v", os.ErrExist, err) } } @@ -152,7 +152,7 @@ func TestNewForInitedDir(t *testing.T) { p := t.TempDir() os.Create(filepath.Join(p, walName(0, 0))) - if _, err := Create(zaptest.NewLogger(t), p, nil); err == nil || err != os.ErrExist { + if _, err := Create(zaptest.NewLogger(t), p, nil); err == nil || !errors.Is(err, os.ErrExist) { t.Errorf("err = %v, want %v", err, os.ErrExist) } } @@ -663,7 +663,7 @@ func TestOpenWithMaxIndex(t *testing.T) { defer w2.Close() _, _, _, err = w2.ReadAll() - if err != ErrSliceOutOfRange { + if !errors.Is(err, ErrSliceOutOfRange) { t.Fatalf("err = %v, want ErrSliceOutOfRange", err) } } @@ -964,7 +964,7 @@ func TestReadAllFail(t *testing.T) { f.Close() // try to read without opening the WAL _, _, _, err = f.ReadAll() - if err == nil || err != ErrDecoderNotFound { + if err == nil || !errors.Is(err, ErrDecoderNotFound) { t.Fatalf("err = %v, want ErrDecoderNotFound", err) } } diff --git a/tests/e2e/ctl_v3_member_test.go b/tests/e2e/ctl_v3_member_test.go index bd045e5f63b..08faf741902 100644 --- a/tests/e2e/ctl_v3_member_test.go +++ b/tests/e2e/ctl_v3_member_test.go @@ -17,6 +17,7 @@ package e2e import ( "context" "encoding/json" + "errors" "fmt" "io" "reflect" @@ -193,7 +194,7 @@ func getMemberList(cx ctlCtx, serializable bool) (etcdserverpb.MemberListRespons resp := etcdserverpb.MemberListResponse{} dec := json.NewDecoder(strings.NewReader(txt)) - if err := dec.Decode(&resp); err == io.EOF { + if err := dec.Decode(&resp); errors.Is(err, io.EOF) { return etcdserverpb.MemberListResponse{}, err } return resp, nil @@ -221,7 +222,7 @@ func memberListWithHexTest(cx ctlCtx) { } hexResp := etcdserverpb.MemberListResponse{} dec := json.NewDecoder(strings.NewReader(txt)) - if err := dec.Decode(&hexResp); err == io.EOF { + if err := dec.Decode(&hexResp); errors.Is(err, io.EOF) { cx.t.Fatalf("memberListWithHexTest error (%v)", err) } num := len(resp.Members) diff --git a/tests/e2e/ctl_v3_snapshot_test.go b/tests/e2e/ctl_v3_snapshot_test.go index bb3f1f06fe0..b9ef782ffcf 100644 --- a/tests/e2e/ctl_v3_snapshot_test.go +++ b/tests/e2e/ctl_v3_snapshot_test.go @@ -17,6 +17,7 @@ package e2e import ( "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -156,7 +157,7 @@ func getSnapshotStatus(cx ctlCtx, fpath string) (snapshot.Status, error) { resp := snapshot.Status{} dec := json.NewDecoder(strings.NewReader(txt)) - if err := dec.Decode(&resp); err == io.EOF { + if err := dec.Decode(&resp); errors.Is(err, io.EOF) { return snapshot.Status{}, err } return resp, nil diff --git a/tests/integration/clientv3/concurrency/example_mutex_test.go b/tests/integration/clientv3/concurrency/example_mutex_test.go index c3b593aed9b..eba8c543f2c 100644 --- a/tests/integration/clientv3/concurrency/example_mutex_test.go +++ b/tests/integration/clientv3/concurrency/example_mutex_test.go @@ -16,6 +16,7 @@ package concurrency_test import ( "context" + "errors" "fmt" "log" @@ -64,7 +65,7 @@ func ExampleMutex_TryLock() { if err = m2.TryLock(context.TODO()); err == nil { log.Fatal("should not acquire lock") } - if err == concurrency.ErrLocked { + if errors.Is(err, concurrency.ErrLocked) { fmt.Println("cannot acquire lock for s2, as already locked in another session") } diff --git a/tests/integration/clientv3/connectivity/black_hole_test.go b/tests/integration/clientv3/connectivity/black_hole_test.go index c0e16aefe1d..e1fc1c57b97 100644 --- a/tests/integration/clientv3/connectivity/black_hole_test.go +++ b/tests/integration/clientv3/connectivity/black_hole_test.go @@ -18,6 +18,7 @@ package connectivity_test import ( "context" + "errors" "testing" "time" @@ -113,7 +114,7 @@ func TestBalancerUnderBlackholeKeepAliveWatch(t *testing.T) { func TestBalancerUnderBlackholeNoKeepAlivePut(t *testing.T) { testBalancerUnderBlackholeNoKeepAlive(t, func(cli *clientv3.Client, ctx context.Context) error { _, err := cli.Put(ctx, "foo", "bar") - if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || err == rpctypes.ErrTimeout { + if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || errors.Is(err, rpctypes.ErrTimeout) { return errExpected } return err @@ -123,7 +124,7 @@ func TestBalancerUnderBlackholeNoKeepAlivePut(t *testing.T) { func TestBalancerUnderBlackholeNoKeepAliveDelete(t *testing.T) { testBalancerUnderBlackholeNoKeepAlive(t, func(cli *clientv3.Client, ctx context.Context) error { _, err := cli.Delete(ctx, "foo") - if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || err == rpctypes.ErrTimeout { + if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || errors.Is(err, rpctypes.ErrTimeout) { return errExpected } return err @@ -136,7 +137,7 @@ func TestBalancerUnderBlackholeNoKeepAliveTxn(t *testing.T) { If(clientv3.Compare(clientv3.Version("foo"), "=", 0)). Then(clientv3.OpPut("foo", "bar")). Else(clientv3.OpPut("foo", "baz")).Commit() - if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || err == rpctypes.ErrTimeout { + if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || errors.Is(err, rpctypes.ErrTimeout) { return errExpected } return err @@ -146,7 +147,7 @@ func TestBalancerUnderBlackholeNoKeepAliveTxn(t *testing.T) { func TestBalancerUnderBlackholeNoKeepAliveLinearizableGet(t *testing.T) { testBalancerUnderBlackholeNoKeepAlive(t, func(cli *clientv3.Client, ctx context.Context) error { _, err := cli.Get(ctx, "a") - if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || err == rpctypes.ErrTimeout { + if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || errors.Is(err, rpctypes.ErrTimeout) { return errExpected } return err @@ -207,7 +208,7 @@ func testBalancerUnderBlackholeNoKeepAlive(t *testing.T, op func(*clientv3.Clien cancel() if err == nil { break - } else if err == errExpected { + } else if errors.Is(err, errExpected) { t.Logf("#%d: current error %v", i, err) } else { t.Errorf("#%d: failed with error %v", i, err) diff --git a/tests/integration/clientv3/connectivity/network_partition_test.go b/tests/integration/clientv3/connectivity/network_partition_test.go index b72b7aea288..6c99c32d04c 100644 --- a/tests/integration/clientv3/connectivity/network_partition_test.go +++ b/tests/integration/clientv3/connectivity/network_partition_test.go @@ -35,7 +35,7 @@ var errExpected = errors.New("expected error") func isErrorExpected(err error) bool { return clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || - err == rpctypes.ErrTimeout || err == rpctypes.ErrTimeoutDueToLeaderFail + errors.Is(err, rpctypes.ErrTimeout) || errors.Is(err, rpctypes.ErrTimeoutDueToLeaderFail) } // TestBalancerUnderNetworkPartitionPut tests when one member becomes isolated, @@ -145,7 +145,7 @@ func testBalancerUnderNetworkPartition(t *testing.T, op func(*clientv3.Client, c if err == nil { break } - if err != errExpected { + if !errors.Is(err, errExpected) { t.Errorf("#%d: expected '%v', got '%v'", i, errExpected, err) } // give enough time for endpoint switch @@ -267,7 +267,7 @@ func testBalancerUnderNetworkPartitionWatch(t *testing.T, isolateLeader bool) { if len(ev.Events) != 0 { t.Fatal("expected no event") } - if err = ev.Err(); err != rpctypes.ErrNoLeader { + if err = ev.Err(); !errors.Is(err, rpctypes.ErrNoLeader) { t.Fatalf("expected %v, got %v", rpctypes.ErrNoLeader, err) } case <-time.After(integration2.RequestWaitTimeout): // enough time to detect leader lost @@ -313,7 +313,7 @@ func TestDropReadUnderNetworkPartition(t *testing.T) { ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) _, err = kvc.Get(ctx, "a") cancel() - if err != rpctypes.ErrLeaderChanged { + if !errors.Is(err, rpctypes.ErrLeaderChanged) { t.Fatalf("expected %v, got %v", rpctypes.ErrLeaderChanged, err) } @@ -322,7 +322,7 @@ func TestDropReadUnderNetworkPartition(t *testing.T) { _, err = kvc.Get(ctx, "a") cancel() if err != nil { - if err == rpctypes.ErrTimeout { + if errors.Is(err, rpctypes.ErrTimeout) { <-time.After(time.Second) i++ continue diff --git a/tests/integration/clientv3/connectivity/server_shutdown_test.go b/tests/integration/clientv3/connectivity/server_shutdown_test.go index a75efa0f8fe..3afc8eb4c01 100644 --- a/tests/integration/clientv3/connectivity/server_shutdown_test.go +++ b/tests/integration/clientv3/connectivity/server_shutdown_test.go @@ -17,6 +17,7 @@ package connectivity_test import ( "bytes" "context" + "errors" "fmt" "testing" "time" @@ -101,7 +102,7 @@ func TestBalancerUnderServerShutdownWatch(t *testing.T) { if err == nil { break } - if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || err == rpctypes.ErrTimeout || err == rpctypes.ErrTimeoutDueToLeaderFail { + if clientv3test.IsClientTimeout(err) || clientv3test.IsServerCtxTimeout(err) || errors.Is(err, rpctypes.ErrTimeout) || errors.Is(err, rpctypes.ErrTimeoutDueToLeaderFail) { continue } t.Fatal(err) diff --git a/tests/integration/clientv3/experimental/recipes/v3_double_barrier_test.go b/tests/integration/clientv3/experimental/recipes/v3_double_barrier_test.go index 120e4bed8af..f4fbfcb2457 100644 --- a/tests/integration/clientv3/experimental/recipes/v3_double_barrier_test.go +++ b/tests/integration/clientv3/experimental/recipes/v3_double_barrier_test.go @@ -16,6 +16,7 @@ package recipes_test import ( "context" + "errors" "sync" "testing" "time" @@ -149,7 +150,7 @@ func TestDoubleBarrierTooManyClients(t *testing.T) { // no any other client can enter the barrier. wgEntered.Wait() t.Log("Try to enter into double barrier") - if err = b.Enter(); err != recipe.ErrTooManyClients { + if err = b.Enter(); !errors.Is(err, recipe.ErrTooManyClients) { t.Errorf("Unexcepted error, expected: ErrTooManyClients, got: %v", err) } diff --git a/tests/integration/clientv3/experimental/recipes/v3_lock_test.go b/tests/integration/clientv3/experimental/recipes/v3_lock_test.go index 79f61662032..1fcbc46e144 100644 --- a/tests/integration/clientv3/experimental/recipes/v3_lock_test.go +++ b/tests/integration/clientv3/experimental/recipes/v3_lock_test.go @@ -16,6 +16,7 @@ package recipes_test import ( "context" + "errors" "fmt" "math/rand" "sync" @@ -139,7 +140,7 @@ func testMutexTryLock(t *testing.T, lockers int, chooseClient func() *clientv3.C case <-ctx.Done(): t.Errorf("Thread: %v, Context failed: %v", i, err) } - } else if err == concurrency.ErrLocked { + } else if errors.Is(err, concurrency.ErrLocked) { select { case notlockedC <- m: case <-ctx.Done(): diff --git a/tests/integration/clientv3/lease/leasing_test.go b/tests/integration/clientv3/lease/leasing_test.go index 2164e8f5b18..40113d0aa13 100644 --- a/tests/integration/clientv3/lease/leasing_test.go +++ b/tests/integration/clientv3/lease/leasing_test.go @@ -16,6 +16,7 @@ package lease_test import ( "context" + "errors" "fmt" "math/rand" "reflect" @@ -895,7 +896,7 @@ func TestLeasingTxnCancel(t *testing.T) { time.Sleep(100 * time.Millisecond) cancel() }() - if _, err := lkv2.Txn(ctx).Then(clientv3.OpPut("k", "v")).Commit(); err != context.Canceled { + if _, err := lkv2.Txn(ctx).Then(clientv3.OpPut("k", "v")).Commit(); !errors.Is(err, context.Canceled) { t.Fatalf("expected %v, got %v", context.Canceled, err) } } @@ -2017,7 +2018,7 @@ func TestLeasingSessionExpireCancel(t *testing.T) { select { case err := <-errc: - if err != ctx.Err() { + if !errors.Is(err, ctx.Err()) { t.Errorf("#%d: expected %v of server unavailable, got %v", i, ctx.Err(), err) } case <-time.After(5 * time.Second): @@ -2048,7 +2049,7 @@ func waitForExpireAck(t *testing.T, kv clientv3.KV) { ctx, cancel := context.WithTimeout(context.TODO(), time.Second) _, err := kv.Get(ctx, "abc") cancel() - if err == ctx.Err() { + if errors.Is(err, ctx.Err()) { return } else if err != nil { t.Logf("current error: %v", err) diff --git a/tests/integration/clientv3/maintenance_test.go b/tests/integration/clientv3/maintenance_test.go index 7dc912a3a2f..3de3d389cff 100644 --- a/tests/integration/clientv3/maintenance_test.go +++ b/tests/integration/clientv3/maintenance_test.go @@ -18,6 +18,7 @@ import ( "bytes" "context" "crypto/sha256" + "errors" "fmt" "io" "math" @@ -135,7 +136,7 @@ func TestMaintenanceMoveLeader(t *testing.T) { cli := clus.Client(targetIdx) _, err := cli.MoveLeader(context.Background(), target) - if err != rpctypes.ErrNotLeader { + if !errors.Is(err, rpctypes.ErrNotLeader) { t.Fatalf("error expected %v, got %v", rpctypes.ErrNotLeader, err) } @@ -186,7 +187,7 @@ func TestMaintenanceSnapshotCancel(t *testing.T) { cancel() _, err = io.Copy(io.Discard, rc1) - if err != context.Canceled { + if !errors.Is(err, context.Canceled) { t.Errorf("expected %v, got %v", context.Canceled, err) } } diff --git a/tests/integration/clientv3/ordering_kv_test.go b/tests/integration/clientv3/ordering_kv_test.go index c539199ff6a..1d667b44dac 100644 --- a/tests/integration/clientv3/ordering_kv_test.go +++ b/tests/integration/clientv3/ordering_kv_test.go @@ -89,7 +89,7 @@ func TestDetectKvOrderViolation(t *testing.T) { t.Logf("Quering m2 after restart") v, err = orderingKv.Get(ctx, "foo", clientv3.WithSerializable()) t.Logf("Quering m2 returned: v:%v err:%v ", v, err) - if err != errOrderViolation { + if !errors.Is(err, errOrderViolation) { t.Fatalf("expected %v, got err:%v v:%v", errOrderViolation, err, v) } } @@ -155,7 +155,7 @@ func TestDetectTxnOrderViolation(t *testing.T) { cli.SetEndpoints(clus.Members[2].GRPCURL) time.Sleep(2 * time.Second) // FIXME: Figure out how pause SetEndpoints sufficiently that this is not needed _, err = orderingKv.Get(ctx, "foo", clientv3.WithSerializable()) - if err != errOrderViolation { + if !errors.Is(err, errOrderViolation) { t.Fatalf("expected %v, got %v", errOrderViolation, err) } orderingTxn = orderingKv.Txn(ctx) @@ -164,7 +164,7 @@ func TestDetectTxnOrderViolation(t *testing.T) { ).Then( clientv3.OpGet("foo", clientv3.WithSerializable()), ).Commit() - if err != errOrderViolation { + if !errors.Is(err, errOrderViolation) { t.Fatalf("expected %v, got %v", errOrderViolation, err) } } diff --git a/tests/integration/clientv3/ordering_util_test.go b/tests/integration/clientv3/ordering_util_test.go index ebac39981a9..6313957bf3f 100644 --- a/tests/integration/clientv3/ordering_util_test.go +++ b/tests/integration/clientv3/ordering_util_test.go @@ -16,6 +16,7 @@ package clientv3test import ( "context" + "errors" "testing" "time" @@ -78,7 +79,7 @@ func TestEndpointSwitchResolvesViolation(t *testing.T) { cli.SetEndpoints(clus.Members[2].GRPCURL) time.Sleep(1 * time.Second) // give enough time for the operation _, err = orderingKv.Get(ctx, "foo", clientv3.WithSerializable()) - if err != ordering.ErrNoGreaterRev { + if !errors.Is(err, ordering.ErrNoGreaterRev) { t.Fatal("While speaking to partitioned leader, we should get ErrNoGreaterRev error") } @@ -156,7 +157,7 @@ func TestUnresolvableOrderViolation(t *testing.T) { time.Sleep(1 * time.Second) // give enough time for operation _, err = OrderingKv.Get(ctx, "foo", clientv3.WithSerializable()) - if err != ordering.ErrNoGreaterRev { + if !errors.Is(err, ordering.ErrNoGreaterRev) { t.Fatalf("expected %v, got %v", ordering.ErrNoGreaterRev, err) } } diff --git a/tests/integration/clientv3/txn_test.go b/tests/integration/clientv3/txn_test.go index 84a56146d99..221247d2f7a 100644 --- a/tests/integration/clientv3/txn_test.go +++ b/tests/integration/clientv3/txn_test.go @@ -16,6 +16,7 @@ package clientv3test import ( "context" + "errors" "fmt" "testing" "time" @@ -36,7 +37,7 @@ func TestTxnError(t *testing.T) { ctx := context.TODO() _, err := kv.Txn(ctx).Then(clientv3.OpPut("foo", "bar1"), clientv3.OpPut("foo", "bar2")).Commit() - if err != rpctypes.ErrDuplicateKey { + if !errors.Is(err, rpctypes.ErrDuplicateKey) { t.Fatalf("expected %v, got %v", rpctypes.ErrDuplicateKey, err) } @@ -45,7 +46,7 @@ func TestTxnError(t *testing.T) { ops[i] = clientv3.OpPut(fmt.Sprintf("foo%d", i), "") } _, err = kv.Txn(ctx).Then(ops...).Commit() - if err != rpctypes.ErrTooManyOps { + if !errors.Is(err, rpctypes.ErrTooManyOps) { t.Fatalf("expected %v, got %v", rpctypes.ErrTooManyOps, err) } } diff --git a/tests/integration/clientv3/user_test.go b/tests/integration/clientv3/user_test.go index 49b4c18ea45..7ed13e7ed44 100644 --- a/tests/integration/clientv3/user_test.go +++ b/tests/integration/clientv3/user_test.go @@ -16,6 +16,7 @@ package clientv3test import ( "context" + "errors" "testing" "time" @@ -41,17 +42,17 @@ func TestUserError(t *testing.T) { } _, err = authapi.UserAdd(context.TODO(), "foo", "bar") - if err != rpctypes.ErrUserAlreadyExist { + if !errors.Is(err, rpctypes.ErrUserAlreadyExist) { t.Fatalf("expected %v, got %v", rpctypes.ErrUserAlreadyExist, err) } _, err = authapi.UserDelete(context.TODO(), "not-exist-user") - if err != rpctypes.ErrUserNotFound { + if !errors.Is(err, rpctypes.ErrUserNotFound) { t.Fatalf("expected %v, got %v", rpctypes.ErrUserNotFound, err) } _, err = authapi.UserGrantRole(context.TODO(), "foo", "test-role-does-not-exist") - if err != rpctypes.ErrRoleNotFound { + if !errors.Is(err, rpctypes.ErrRoleNotFound) { t.Fatalf("expected %v, got %v", rpctypes.ErrRoleNotFound, err) } } @@ -116,7 +117,7 @@ func TestUserErrorAuth(t *testing.T) { authSetupRoot(t, authapi.Auth) // unauthenticated client - if _, err := authapi.UserAdd(context.TODO(), "foo", "bar"); err != rpctypes.ErrUserEmpty { + if _, err := authapi.UserAdd(context.TODO(), "foo", "bar"); !errors.Is(err, rpctypes.ErrUserEmpty) { t.Fatalf("expected %v, got %v", rpctypes.ErrUserEmpty, err) } @@ -127,11 +128,11 @@ func TestUserErrorAuth(t *testing.T) { DialOptions: []grpc.DialOption{grpc.WithBlock()}, } cfg.Username, cfg.Password = "wrong-id", "123" - if _, err := integration2.NewClient(t, cfg); err != rpctypes.ErrAuthFailed { + if _, err := integration2.NewClient(t, cfg); !errors.Is(err, rpctypes.ErrAuthFailed) { t.Fatalf("expected %v, got %v", rpctypes.ErrAuthFailed, err) } cfg.Username, cfg.Password = "root", "wrong-pass" - if _, err := integration2.NewClient(t, cfg); err != rpctypes.ErrAuthFailed { + if _, err := integration2.NewClient(t, cfg); !errors.Is(err, rpctypes.ErrAuthFailed) { t.Fatalf("expected %v, got %v", rpctypes.ErrAuthFailed, err) } diff --git a/tests/integration/v3_grpc_test.go b/tests/integration/v3_grpc_test.go index 2cc4ab66032..8efeb5d522d 100644 --- a/tests/integration/v3_grpc_test.go +++ b/tests/integration/v3_grpc_test.go @@ -17,6 +17,7 @@ package integration import ( "bytes" "context" + "errors" "fmt" "math/rand" "os" @@ -114,7 +115,7 @@ func TestV3PutRestart(t *testing.T) { defer cancel() reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")} _, err := kvc.Put(ctx, reqput) - if err != nil && err == ctx.Err() { + if err != nil && errors.Is(err, ctx.Err()) { t.Fatalf("expected grpc error, got local ctx error (%v)", err) } } @@ -1599,7 +1600,7 @@ func TestTLSGRPCRejectSecureClient(t *testing.T) { if client != nil || err == nil { client.Close() t.Fatalf("expected no client") - } else if err != context.DeadlineExceeded { + } else if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("unexpected error (%v)", err) } } @@ -1776,7 +1777,7 @@ func testTLSReload( // 5. expect dial time-out when loading expired certs select { case gerr := <-errc: - if gerr != context.DeadlineExceeded { + if !errors.Is(gerr, context.DeadlineExceeded) { t.Fatalf("expected %v, got %v", context.DeadlineExceeded, gerr) } case <-time.After(5 * time.Second): diff --git a/tests/integration/v3_tls_test.go b/tests/integration/v3_tls_test.go index a13ad5c0beb..fbdf2bb8b5e 100644 --- a/tests/integration/v3_tls_test.go +++ b/tests/integration/v3_tls_test.go @@ -17,6 +17,7 @@ package integration import ( "context" "crypto/tls" + "errors" "testing" "time" @@ -72,7 +73,7 @@ func testTLSCipherSuites(t *testing.T, valid bool) { if cli != nil { cli.Close() } - if !valid && cerr != context.DeadlineExceeded { + if !valid && !errors.Is(cerr, context.DeadlineExceeded) { t.Fatalf("expected %v with TLS handshake failure, got %v", context.DeadlineExceeded, cerr) } if valid && cerr != nil {