diff --git a/.golangci.yml b/.golangci.yml index b62a27c1..a01e3c66 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -52,7 +52,7 @@ issues: linters: - dupl - funlen - #fix: true + # fix: true linters: enable: @@ -136,6 +136,8 @@ linters: - reassign # Checks that package variables are not reassigned [fast: false, auto-fix: false] - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false] - rowserrcheck # checks whether Err of rows is checked successfully [fast: false, auto-fix: false] + - sloglint # Detects the wrong usage of `slog` that a user forgets to dispatch with `Send` or `Msg`. [fast: false, auto-fix: false] + - spancheck # spancheck is a linter that detects the usage of context.Context.Value method. [fast: false, auto-fix: false] - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false] - staticcheck # (megacheck): It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint. [fast: false, auto-fix: false] - stylecheck # Stylecheck is a replacement for golint [fast: false, auto-fix: false] diff --git a/Makefile b/Makefile index 9ba8ce7a..304a2c66 100644 --- a/Makefile +++ b/Makefile @@ -61,7 +61,7 @@ GOFMT=$(shell which gofmt) GOTEST=GOPATH=$(GOPATH) $(shell which gotest) GODOC=GOPATH=$(GOPATH) $(shell which godoc) GOLANGCILINT=$(BINUTIL)/golangci-lint -GOLANGCILINTVERSION=v1.55.2 +GOLANGCILINTVERSION=v1.56.2 # Directory containing the source code SRCDIR=./pkg @@ -147,7 +147,7 @@ dbuild: dockerdev # Get the test dependencies .PHONY: deps deps: ensuretarget - curl --silent --show-error --fail --location https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(BINUTIL) $(GOLANGCILINTVERSION) + curl --silent --show-error --fail --location "https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh" | sh -s -- -b $(BINUTIL) $(GOLANGCILINTVERSION) $(GO) install github.com/rakyll/gotest $(GO) install github.com/jstemmer/go-junit-report $(GO) install github.com/golang/mock/mockgen diff --git a/README.md b/README.md index 50dbaf47..89336b85 100644 --- a/README.md +++ b/README.md @@ -6,16 +6,16 @@ *Go Service Library* -This Open Source project contains a collection of high-quality GO (golang) packages. +This Open Source project contains a collection of high-quality [GO](https://go.dev/) (golang) packages. -The packages documentation is available at: [https://pkg.go.dev/github.com/Vonage/gosrvlib](https://pkg.go.dev/github.com/Vonage/gosrvlib) +Each package follows common conventions and they can be individually imported in any project. -This package collection forms the base structure for production-ready web-services. +This package collection forms the base structure for fully-fledged production-ready web-services. -A new service can be generated by using the command `make project CONFIG=project.cfg`. +A new Web service can be generated by using the command `make project CONFIG=project.cfg`. The new generated project name, description, etc..., can be set in the file specified via the CONFIG parameter. -Each package follows the same conventions and they can be individually imported in any project. +The packages documentation is available at: [https://pkg.go.dev/github.com/Vonage/gosrvlib/](https://pkg.go.dev/github.com/Vonage/gosrvlib) [![Go Reference](https://pkg.go.dev/badge/github.com/Vonage/gosrvlib.svg)](https://pkg.go.dev/github.com/Vonage/gosrvlib) [![check](https://github.com/Vonage/gosrvlib/actions/workflows/check.yaml/badge.svg)](https://github.com/Vonage/gosrvlib/actions/workflows/check.yaml) @@ -48,54 +48,26 @@ Each package follows the same conventions and they can be individually imported ----------------------------------------------------------------- -## Quick Start +## Developers' Quick Start -This project includes a *Makefile* that allows you to test and build the project in a Linux-compatible system with simple commands. -All the artifacts and reports produced using this *Makefile* are stored in the *target* folder. - -All the packages listed in the *resources/docker/Dockerfile.dev* file are required in order to build and test all the library options in the current environment. -Alternatively, everything can be built inside a [Docker](https://www.docker.com) container using the command "make dbuild". - -To see all available options: -```bash -make help -``` - -To build the project inside a Docker container (requires Docker): -```bash -make dbuild -``` - -An arbitrary make target can be executed inside a Docker container by specifying the "MAKETARGET" parameter: -```bash -MAKETARGET='deps mod qa example' make dbuild -``` -The list of make targets can be obtained by typing ```make``` +To quickly get started with this project, follow these steps: +1. Ensure you ahev installed the latest Go version and Python3 for some extra tests. +1. Clone the repository: `git clone https://github.com/Vonage/gosrvlib.git`. +2. Change into the project directory: `cd gosrvlib`. +3. Install the required dependencies and test everything: `DEVMODE=LOCAL make x`. -The base Docker building environment is defined in the following Dockerfile: -```bash -resources/docker/Dockerfile.dev -``` +Now you are ready to start developing with gosrvlib! -To download all dependencies: -```bash -make deps -``` -To update the mod file: -```bash -make mod -``` +This project includes a *Makefile* that allows you to test and build the project in a Linux-compatible system with simple commands. +All the artifacts and reports produced using this *Makefile* are stored in the *target* folder. -To execute all the default test builds and generate reports in the current environment: -```bash -make qa -``` +Alternatively, everything can be built inside a [Docker](https://www.docker.com) container using the command `make dbuild` that uses the environment defined at `*`resources/docker/Dockerfile.dev`. -To format the code (please use this command before submitting any pull request): +To see all available options: ```bash -make format +make help ``` ----------------------------------------------------------------- diff --git a/VERSION b/VERSION index dcec0344..94a8a2ef 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.81.1 +1.81.2 diff --git a/examples/service/.golangci.yml b/examples/service/.golangci.yml index 192b97c4..e9f70748 100644 --- a/examples/service/.golangci.yml +++ b/examples/service/.golangci.yml @@ -136,6 +136,8 @@ linters: - reassign # Checks that package variables are not reassigned [fast: false, auto-fix: false] - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false] - rowserrcheck # checks whether Err of rows is checked successfully [fast: false, auto-fix: false] + - sloglint # Detects the wrong usage of `slog` that a user forgets to dispatch with `Send` or `Msg`. [fast: false, auto-fix: false] + - spancheck # spancheck is a linter that detects the usage of context.Context.Value method [fast: false, auto-fix: false] - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false] - staticcheck # (megacheck): It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint. [fast: false, auto-fix: false] - stylecheck # Stylecheck is a replacement for golint [fast: false, auto-fix: false] diff --git a/examples/service/Makefile b/examples/service/Makefile index 6a9ab68e..2d49bd72 100644 --- a/examples/service/Makefile +++ b/examples/service/Makefile @@ -149,7 +149,7 @@ GOFMT=$(shell which gofmt) GOTEST=GOPATH=$(GOPATH) $(shell which gotest) GODOC=GOPATH=$(GOPATH) $(shell which godoc) GOLANGCILINT=$(BINUTIL)/golangci-lint -GOLANGCILINTVERSION=v1.55.2 +GOLANGCILINTVERSION=v1.56.2 # Current operating system and architecture as one string. GOOSARCH=$(shell go env GOOS GOARCH | tr -d \\n) @@ -397,7 +397,7 @@ endif # Get the test dependencies .PHONY: deps deps: ensuretarget - curl --silent --show-error --fail --location https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(BINUTIL) $(GOLANGCILINTVERSION) + curl --silent --show-error --fail --location "https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh" | sh -s -- -b $(BINUTIL) $(GOLANGCILINTVERSION) $(GO) install github.com/mikefarah/yq/v4@latest $(GO) install github.com/hairyhenderson/gomplate/v3/cmd/gomplate@latest $(GO) install github.com/rakyll/gotest diff --git a/examples/service/README.md b/examples/service/README.md index e69c8669..8bfb959a 100644 --- a/examples/service/README.md +++ b/examples/service/README.md @@ -89,43 +89,26 @@ sudo pip install --upgrade check-jsonschema -## Quick Start +## Developers' Quick Start -This project includes a Makefile that allows you to test and build the project in a Linux-compatible system with simple commands. -All the artifacts and reports produced using this Makefile are stored in the *target* folder. +To quickly get started with this project, follow these steps: -All the packages listed in the *resources/docker/Dockerfile.dev* file are required in order to build and test all the library options in the current environment. -Alternatively, everything can be built inside a [Docker](https://www.docker.com) container using the command "make dbuild". +1. Ensure you ahev installed the latest Go version and Python3 for some extra tests. +1. Clone the repository: `git clone https://github.com/gosrvlibexampleowner/gosrvlibexample.git`. +2. Change into the project directory: `cd gosrvlibexample`. +3. Install the required dependencies and test everything: `DEVMODE=LOCAL make x`. -To see all available options: -```bash -make help -``` - - -To download all dependencies: -```bash -make deps -``` +Now you are ready to start developing with /gosrvlibexample! -To update the mod file: -```bash -make mod -``` -To format the code (please use this command before submitting any pull request): -```bash -make format -``` +This project includes a *Makefile* that allows you to test and build the project in a Linux-compatible system with simple commands. +All the artifacts and reports produced using this *Makefile* are stored in the *target* folder. -To execute all the default test builds and generate reports in the current environment: -```bash -make qa -``` +Alternatively, everything can be built inside a [Docker](https://www.docker.com) container using the command `make dbuild` that uses the environment defined at `resources/docker/Dockerfile.dev`. -To build the executable file: +To see all available options: ```bash -make build +make help ``` diff --git a/examples/service/doc/src/development.tmpl b/examples/service/doc/src/development.tmpl index 7950c658..b0008ecf 100644 --- a/examples/service/doc/src/development.tmpl +++ b/examples/service/doc/src/development.tmpl @@ -33,43 +33,26 @@ sudo pip install --upgrade check-jsonschema -## Quick Start +## Developers' Quick Start -This project includes a Makefile that allows you to test and build the project in a Linux-compatible system with simple commands. -All the artifacts and reports produced using this Makefile are stored in the *target* folder. +To quickly get started with this project, follow these steps: -All the packages listed in the *resources/docker/Dockerfile.dev* file are required in order to build and test all the library options in the current environment. -Alternatively, everything can be built inside a [Docker](https://www.docker.com) container using the command "make dbuild". +1. Ensure you ahev installed the latest Go version and Python3 for some extra tests. +1. Clone the repository: `git clone https://github.com/gosrvlibexampleowner/gosrvlibexample.git`. +2. Change into the project directory: `cd gosrvlibexample`. +3. Install the required dependencies and test everything: `DEVMODE=LOCAL make x`. -To see all available options: -```bash -make help -``` - - -To download all dependencies: -```bash -make deps -``` +Now you are ready to start developing with /gosrvlibexample! -To update the mod file: -```bash -make mod -``` -To format the code (please use this command before submitting any pull request): -```bash -make format -``` +This project includes a *Makefile* that allows you to test and build the project in a Linux-compatible system with simple commands. +All the artifacts and reports produced using this *Makefile* are stored in the *target* folder. -To execute all the default test builds and generate reports in the current environment: -```bash -make qa -``` +Alternatively, everything can be built inside a [Docker](https://www.docker.com) container using the command `make dbuild` that uses the environment defined at `resources/docker/Dockerfile.dev`. -To build the executable file: +To see all available options: ```bash -make build +make help ``` diff --git a/examples/service/go.mod b/examples/service/go.mod index 73a52a39..55ac87ba 100644 --- a/examples/service/go.mod +++ b/examples/service/go.mod @@ -5,7 +5,7 @@ go 1.22 replace github.com/Vonage/gosrvlib => ../.. require ( - github.com/Vonage/gosrvlib v1.81.1 + github.com/Vonage/gosrvlib v1.81.2 github.com/golang/mock v1.6.0 github.com/jstemmer/go-junit-report v0.9.1 github.com/prometheus/client_golang v1.18.0 diff --git a/examples/service/go.sum b/examples/service/go.sum index 97736ad9..0c448ea1 100644 --- a/examples/service/go.sum +++ b/examples/service/go.sum @@ -284,8 +284,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.0 h1:SHN/umDLT github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.0/go.mod h1:l8gPU5RYGOFHJqWEpPMoRTP0VoaWQSkJdKo+hwWnnDA= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.0 h1:l5puwOHr7IxECuPMIuZG7UKOzAnF24v6t4l+Z5Moay4= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.0/go.mod h1:Oov79flWa/n7Ni+lQC3z+VM7PoRM47omRqbJU9B5Y7E= -github.com/aws/aws-sdk-go-v2/service/s3 v1.50.0 h1:jZAdMD1ioZdqirzzVVRhpHHWJmcGGCn8JqDYBs5nmYA= -github.com/aws/aws-sdk-go-v2/service/s3 v1.50.0/go.mod h1:1o/W6JFUuREj2ExoQ21vHJgO7wakvjhol91M9eknFgs= +github.com/aws/aws-sdk-go-v2/service/s3 v1.50.1 h1:bjpWJEXch7moIt3PX2r5XpGROsletl7enqG1Q3Te1Dc= +github.com/aws/aws-sdk-go-v2/service/s3 v1.50.1/go.mod h1:1o/W6JFUuREj2ExoQ21vHJgO7wakvjhol91M9eknFgs= github.com/aws/aws-sdk-go-v2/service/sqs v1.30.1 h1:YgHEUU4euy2VOUAzu08QSjtRwJLa9Nr1MD8qoW/b9RY= github.com/aws/aws-sdk-go-v2/service/sqs v1.30.1/go.mod h1:4phHwV34rLb+56VjTud2w7hBu5Q57YIKFIA8Httzljg= github.com/aws/aws-sdk-go-v2/service/sso v1.19.0 h1:u6OkVDxtBPnxPkZ9/63ynEe+8kHbtS5IfaC4PzVxzWM= diff --git a/examples/service/internal/cli/bind.go b/examples/service/internal/cli/bind.go index d9f38baa..e698e9db 100644 --- a/examples/service/internal/cli/bind.go +++ b/examples/service/internal/cli/bind.go @@ -22,7 +22,7 @@ import ( // bind is the entry point of the service, this is where the wiring of all components happens. func bind(cfg *appConfig, appInfo *jsendx.AppInfo, mtr instr.Metrics, wg *sync.WaitGroup, sc chan struct{}) bootstrap.BindFunc { - return func(ctx context.Context, l *zap.Logger, m metrics.Client) error { + return func(ctx context.Context, _ *zap.Logger, m metrics.Client) error { // We assume the service is disabled and override the service binder if required serviceBinder := httpserver.NopBinder() statusHandler := jsendx.DefaultStatusHandler(appInfo) diff --git a/examples/service/internal/cli/bind_test.go b/examples/service/internal/cli/bind_test.go index 67e34372..cb098e5a 100644 --- a/examples/service/internal/cli/bind_test.go +++ b/examples/service/internal/cli/bind_test.go @@ -95,6 +95,7 @@ func Test_bind(t *testing.T) { if tt.preBindAddr != "" { l, err := net.Listen("tcp", tt.preBindAddr) require.NoError(t, err) + defer func() { _ = l.Close() }() } @@ -126,10 +127,12 @@ func Test_bind(t *testing.T) { bootstrap.WithShutdownWaitGroup(wg), bootstrap.WithShutdownSignalChan(sc), } + err := bootstrap.Bootstrap(testBindFn, testBootstrapOpts...) if tt.wantErr { require.Error(t, err, "bind() error = %v, wantErr %v", err, tt.wantErr) } + if tt.wantTimeoutErr { require.ErrorIs(t, err, context.DeadlineExceeded, "bind() error = %v, wantErr %v", err, context.DeadlineExceeded) diff --git a/examples/service/internal/cli/cli.go b/examples/service/internal/cli/cli.go index 05583d08..4c8388d0 100644 --- a/examples/service/internal/cli/cli.go +++ b/examples/service/internal/cli/cli.go @@ -85,7 +85,7 @@ func New(version, release string, bootstrapFn bootstrapFunc) (*cobra.Command, er versionCmd := &cobra.Command{ Use: "version", Short: "Print this program version", - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { fmt.Println(version) //nolint:forbidigo }, } diff --git a/examples/service/internal/cli/cli_test.go b/examples/service/internal/cli/cli_test.go index 28b72da1..9e13b0ad 100644 --- a/examples/service/internal/cli/cli_test.go +++ b/examples/service/internal/cli/cli_test.go @@ -80,7 +80,7 @@ func TestNew(t *testing.T) { { name: "bootstrap with valid configuration", osArgs: []string{AppName, "-c", "../../resources/test/etc/gosrvlibexample/"}, - boostrapFunc: func(bindFn bootstrap.BindFunc, opts ...bootstrap.Option) error { + boostrapFunc: func(_ bootstrap.BindFunc, _ ...bootstrap.Option) error { return nil }, wantErr: false, @@ -92,6 +92,7 @@ func TestNew(t *testing.T) { t.Run(tt.name, func(t *testing.T) { oldOsArgs := os.Args defer func() { os.Args = oldOsArgs }() + os.Args = tt.osArgs bootstrapFunc := bootstrap.Bootstrap @@ -101,6 +102,7 @@ func TestNew(t *testing.T) { // execute the main function var out string + cmd, err := New("0.0.0-test", "0", bootstrapFunc) if err == nil { require.NotNil(t, cmd) diff --git a/go.mod b/go.mod index 88689eb6..065e35ee 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/DATA-DOG/go-sqlmock v1.5.2 github.com/aws/aws-sdk-go-v2 v1.25.0 github.com/aws/aws-sdk-go-v2/config v1.27.0 - github.com/aws/aws-sdk-go-v2/service/s3 v1.50.0 + github.com/aws/aws-sdk-go-v2/service/s3 v1.50.1 github.com/aws/aws-sdk-go-v2/service/sqs v1.30.1 github.com/confluentinc/confluent-kafka-go v1.9.2 github.com/dlmiddlecote/sqlstats v1.0.2 diff --git a/go.sum b/go.sum index e7eb1463..a3f38770 100644 --- a/go.sum +++ b/go.sum @@ -292,8 +292,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.0 h1:SHN/umDLT github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.0/go.mod h1:l8gPU5RYGOFHJqWEpPMoRTP0VoaWQSkJdKo+hwWnnDA= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.0 h1:l5puwOHr7IxECuPMIuZG7UKOzAnF24v6t4l+Z5Moay4= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.0/go.mod h1:Oov79flWa/n7Ni+lQC3z+VM7PoRM47omRqbJU9B5Y7E= -github.com/aws/aws-sdk-go-v2/service/s3 v1.50.0 h1:jZAdMD1ioZdqirzzVVRhpHHWJmcGGCn8JqDYBs5nmYA= -github.com/aws/aws-sdk-go-v2/service/s3 v1.50.0/go.mod h1:1o/W6JFUuREj2ExoQ21vHJgO7wakvjhol91M9eknFgs= +github.com/aws/aws-sdk-go-v2/service/s3 v1.50.1 h1:bjpWJEXch7moIt3PX2r5XpGROsletl7enqG1Q3Te1Dc= +github.com/aws/aws-sdk-go-v2/service/s3 v1.50.1/go.mod h1:1o/W6JFUuREj2ExoQ21vHJgO7wakvjhol91M9eknFgs= github.com/aws/aws-sdk-go-v2/service/sqs v1.30.1 h1:YgHEUU4euy2VOUAzu08QSjtRwJLa9Nr1MD8qoW/b9RY= github.com/aws/aws-sdk-go-v2/service/sqs v1.30.1/go.mod h1:4phHwV34rLb+56VjTud2w7hBu5Q57YIKFIA8Httzljg= github.com/aws/aws-sdk-go-v2/service/sso v1.19.0 h1:u6OkVDxtBPnxPkZ9/63ynEe+8kHbtS5IfaC4PzVxzWM= diff --git a/pkg/awsopt/awsopt_test.go b/pkg/awsopt/awsopt_test.go index bf0ee304..4bf70d0a 100644 --- a/pkg/awsopt/awsopt_test.go +++ b/pkg/awsopt/awsopt_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" ) -//nolint:paralleltest func Test_LoadDefaultConfig(t *testing.T) { region := "us-west-2" @@ -62,7 +61,6 @@ func Test_WithRegion(t *testing.T) { } } -//nolint:paralleltest func Test_WithRegionFromURL(t *testing.T) { tests := []struct { name string diff --git a/pkg/bootstrap/bootstrap_test.go b/pkg/bootstrap/bootstrap_test.go index 551242da..45602e16 100644 --- a/pkg/bootstrap/bootstrap_test.go +++ b/pkg/bootstrap/bootstrap_test.go @@ -2,7 +2,7 @@ package bootstrap import ( "context" - "fmt" + "errors" "sync" "syscall" "testing" @@ -45,7 +45,7 @@ func TestBootstrap(t *testing.T) { WithShutdownTimeout(1 * time.Millisecond), }, createLoggerFunc: func() (*zap.Logger, error) { - return nil, fmt.Errorf("log error") + return nil, errors.New("log error") }, wantErr: true, }, @@ -55,7 +55,7 @@ func TestBootstrap(t *testing.T) { WithShutdownTimeout(1 * time.Millisecond), }, createMetricsClientFunc: func() (metrics.Client, error) { - return nil, fmt.Errorf("metrics error") + return nil, errors.New("metrics error") }, wantErr: true, }, @@ -65,7 +65,7 @@ func TestBootstrap(t *testing.T) { WithShutdownTimeout(1 * time.Millisecond), }, bindFunc: func(context.Context, *zap.Logger, metrics.Client) error { - return fmt.Errorf("bind error") + return errors.New("bind error") }, wantErr: true, }, @@ -100,7 +100,6 @@ func TestBootstrap(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { // cannot run in parallel because signals are received by all parallel tests - var ctx context.Context ctx, logs := testutil.ContextWithLogObserver(zap.DebugLevel) diff --git a/pkg/bootstrap/config.go b/pkg/bootstrap/config.go index ea95946e..50514bbe 100644 --- a/pkg/bootstrap/config.go +++ b/pkg/bootstrap/config.go @@ -2,7 +2,7 @@ package bootstrap import ( "context" - "fmt" + "errors" "sync" "time" @@ -51,27 +51,27 @@ func defaultCreateMetricsClientFunc() (metrics.Client, error) { // validate the configuration. func (c *config) validate() error { if c.context == nil { - return fmt.Errorf("context is required") + return errors.New("context is required") } if c.createLoggerFunc == nil { - return fmt.Errorf("createLoggerFunc is required") + return errors.New("createLoggerFunc is required") } if c.createMetricsClientFunc == nil { - return fmt.Errorf("createMetricsClientFunc is required") + return errors.New("createMetricsClientFunc is required") } if c.shutdownTimeout <= 0 { - return fmt.Errorf("invalid shutdownTimeout") + return errors.New("invalid shutdownTimeout") } if c.shutdownWaitGroup == nil { - return fmt.Errorf("shutdownWaitGroup is required") + return errors.New("shutdownWaitGroup is required") } if c.shutdownSignalChan == nil { - return fmt.Errorf("shutdownSignalChan is required") + return errors.New("shutdownSignalChan is required") } return nil diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 8e81b43a..206308d5 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -5,11 +5,11 @@ package config import ( "encoding/base64" "encoding/json" + "errors" "fmt" "os" "path/filepath" "reflect" - "strings" "testing" "github.com/golang/mock/gomock" @@ -88,6 +88,7 @@ func Test_configureConfigSearchPath(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) + defer ctrl.Finish() tmv := NewMockViper(ctrl) @@ -143,7 +144,7 @@ func Test_loadLocalConfig(t *testing.T) { name: "fails with read config error", setupViper: func(ctrl *gomock.Controller) Viper { mock := mockViper(ctrl) - mock.EXPECT().ReadInConfig().Return(fmt.Errorf("read config error")) + mock.EXPECT().ReadInConfig().Return(errors.New("read config error")) return mock }, wantErr: true, @@ -153,7 +154,7 @@ func Test_loadLocalConfig(t *testing.T) { setupViper: func(ctrl *gomock.Controller) Viper { mock := mockViper(ctrl) mock.EXPECT().ReadInConfig() - mock.EXPECT().Unmarshal(gomock.Any()).Return(fmt.Errorf("unmarshal error")) + mock.EXPECT().Unmarshal(gomock.Any()).Return(errors.New("unmarshal error")) return mock }, wantErr: true, @@ -172,7 +173,7 @@ func Test_loadLocalConfig(t *testing.T) { { name: "succeed from empty file", configContent: []byte(`{}`), - setupViper: func(ctrl *gomock.Controller) Viper { + setupViper: func(_ *gomock.Controller) Viper { return viper.New() }, want: &remoteSourceConfig{ @@ -193,7 +194,7 @@ func Test_loadLocalConfig(t *testing.T) { "remoteConfigPath": "/config/path", "remoteConfigSecretKeyring": "super_secret" }`), - setupViper: func(ctrl *gomock.Controller) Viper { + setupViper: func(_ *gomock.Controller) Viper { return viper.New() }, want: &remoteSourceConfig{ @@ -223,6 +224,7 @@ func Test_loadLocalConfig(t *testing.T) { if tt.configContent != nil { configDir, err = os.MkdirTemp("", "test-loadLocalConfig-*") require.NoError(t, err, "failed creating temp config dir: %v", err) + defer func() { _ = os.RemoveAll(configDir) }() tmpFilePath := filepath.Join(configDir, "config.json") @@ -304,7 +306,7 @@ func Test_loadRemoteConfig(t *testing.T) { mock := NewMockViper(ctrl) mock.EXPECT().SetDefault(keyLogLevel, gomock.Any()) mock.EXPECT().SetConfigType(defaultConfigType) - mock.EXPECT().Unmarshal(gomock.Any()).Return(fmt.Errorf("unmarshal error")) + mock.EXPECT().Unmarshal(gomock.Any()).Return(errors.New("unmarshal error")) return mock }, wantErr: true, @@ -368,7 +370,7 @@ func Test_loadRemoteConfig(t *testing.T) { mock.EXPECT().Get(keyLogLevel).Return("DEBUG") return mock }, - setupRemoteViper: func(ctrl *gomock.Controller) Viper { + setupRemoteViper: func(_ *gomock.Controller) Viper { return viper.New() }, want: &testConfig{ @@ -444,7 +446,7 @@ func Test_loadFromEnvVarSource(t *testing.T) { } }, setupMocks: func(mv *MockViper) { - mv.EXPECT().ReadConfig(gomock.Any()).Return(fmt.Errorf("read config error")) + mv.EXPECT().ReadConfig(gomock.Any()).Return(errors.New("read config error")) }, wantErr: true, }, @@ -475,6 +477,7 @@ func Test_loadFromEnvVarSource(t *testing.T) { if tt.setupMocks != nil { tt.setupMocks(v) } + if err := loadFromEnvVarSource(v, tt.setupConfigSource(), "test"); (err != nil) != tt.wantErr { t.Errorf("loadFromEnvVarSource() error = %v, wantErr %v", err, tt.wantErr) } @@ -527,7 +530,7 @@ func Test_loadFromRemoteSource(t *testing.T) { }, setupMocks: func(mv *MockViper) { mv.EXPECT().AddRemoteProvider("remote", "remote:1234", "/config"). - Return(fmt.Errorf("provider error")) + Return(errors.New("provider error")) }, wantErr: true, }, @@ -543,7 +546,7 @@ func Test_loadFromRemoteSource(t *testing.T) { }, setupMocks: func(mv *MockViper) { mv.EXPECT().AddSecureRemoteProvider("remote", "remote:1234", "/config", "keyring"). - Return(fmt.Errorf("provider error")) + Return(errors.New("provider error")) }, wantErr: true, }, @@ -558,7 +561,7 @@ func Test_loadFromRemoteSource(t *testing.T) { }, setupMocks: func(mv *MockViper) { mv.EXPECT().AddRemoteProvider("remote", "remote:1234", "/config") - mv.EXPECT().ReadRemoteConfig().Return(fmt.Errorf("read remote error")) + mv.EXPECT().ReadRemoteConfig().Return(errors.New("read remote error")) }, wantErr: true, }, @@ -594,12 +597,14 @@ func Test_loadFromRemoteSource(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) + defer ctrl.Finish() v := NewMockViper(ctrl) if tt.setupMocks != nil { tt.setupMocks(v) } + if err := loadFromRemoteSource(v, tt.setupConfigSource(), "test"); (err != nil) != tt.wantErr { t.Errorf("loadFromRemoteSource() error = %v, wantErr %v", err, tt.wantErr) } @@ -607,7 +612,7 @@ func Test_loadFromRemoteSource(t *testing.T) { } } -//nolint:gocognit,paralleltest,maintidx +//nolint:gocognit,maintidx func Test_loadConfig(t *testing.T) { tests := []struct { name string @@ -843,7 +848,7 @@ func Test_loadConfig(t *testing.T) { name: "fails loading local config", setupLocalViper: func(ctrl *gomock.Controller) Viper { mock := mockViper(ctrl) - mock.EXPECT().ReadInConfig().Return(fmt.Errorf("read config error")) + mock.EXPECT().ReadInConfig().Return(errors.New("read config error")) return mock }, targetConfig: &testConfig{}, @@ -855,7 +860,7 @@ func Test_loadConfig(t *testing.T) { mock := NewMockViper(ctrl) mock.EXPECT().SetDefault(gomock.Any(), gomock.Any()).AnyTimes() mock.EXPECT().SetConfigType(defaultConfigType) - mock.EXPECT().Unmarshal(gomock.Any()).Return(fmt.Errorf("unmarshal error")) + mock.EXPECT().Unmarshal(gomock.Any()).Return(errors.New("unmarshal error")) return mock }, configContent: []byte(` @@ -901,7 +906,7 @@ func Test_loadConfig(t *testing.T) { } } `), - targetConfig: &testConfig{validateErr: fmt.Errorf("validate error")}, + targetConfig: &testConfig{validateErr: errors.New("validate error")}, wantErr: true, }, { @@ -1002,7 +1007,6 @@ func Test_loadConfig(t *testing.T) { }, } - //nolint:paralleltest for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { @@ -1010,10 +1014,13 @@ func Test_loadConfig(t *testing.T) { defer ctrl.Finish() var tmpConfigDir string + var err error + if tt.configContent != nil { tmpConfigDir, err = os.MkdirTemp("", "test-loadConfig-*") require.NoError(t, err, "failed creating temp config dir: %v", err) + defer func() { _ = os.RemoveAll(tmpConfigDir) }() tmpFilePath := filepath.Join(tmpConfigDir, "config.json") @@ -1035,7 +1042,7 @@ func Test_loadConfig(t *testing.T) { } if tt.envDataContent != nil { - envKey := strings.ToUpper(fmt.Sprintf("%s_REMOTECONFIGDATA", "test")) + envKey := "TEST_REMOTECONFIGDATA" t.Setenv(envKey, base64.StdEncoding.EncodeToString(tt.envDataContent)) } @@ -1048,10 +1055,12 @@ func Test_loadConfig(t *testing.T) { data, _ := json.Marshal(tt.targetConfig) return string(data) }() + wantCfgStr := func() string { data, _ := json.Marshal(tt.wantConfig) return string(data) }() + if cfgStr != wantCfgStr { t.Errorf("loadRemoteSourceConfig() got = %s, want = %s", cfgStr, wantCfgStr) } diff --git a/pkg/enumbitmap/enumbitmap_test.go b/pkg/enumbitmap/enumbitmap_test.go index ebf8add0..e73fe3c4 100644 --- a/pkg/enumbitmap/enumbitmap_test.go +++ b/pkg/enumbitmap/enumbitmap_test.go @@ -94,7 +94,9 @@ func Test_BitMapToStrings(t *testing.T) { if tt.enumFunc != nil { eis = tt.enumFunc(eis) } + got, err := BitMapToStrings(eis, tt.v) + require.Equal(t, tt.wantErr, err != nil, "error = %v, wantErr %v", err, tt.wantErr) require.Equal(t, tt.want, got, "got = %v, want %v", got, tt.want) }) diff --git a/pkg/enumdb/enumdb_test.go b/pkg/enumdb/enumdb_test.go index bb67971f..67d3dd63 100644 --- a/pkg/enumdb/enumdb_test.go +++ b/pkg/enumdb/enumdb_test.go @@ -1,7 +1,7 @@ package enumdb import ( - "fmt" + "errors" "testing" "github.com/DATA-DOG/go-sqlmock" @@ -27,7 +27,7 @@ func TestNew(t *testing.T) { name: "fails prepare statement", setupMock: func(m sqlmock.Sqlmock) { m.ExpectPrepare(query). - WillReturnError(fmt.Errorf("load error")) + WillReturnError(errors.New("load error")) }, wantErr: true, }, @@ -36,7 +36,7 @@ func TestNew(t *testing.T) { setupMock: func(m sqlmock.Sqlmock) { m.ExpectPrepare(query). ExpectQuery(). - WillReturnError(fmt.Errorf("query error")) + WillReturnError(errors.New("query error")) }, wantErr: true, }, @@ -60,7 +60,7 @@ func TestNew(t *testing.T) { rows := sqlmock. NewRows([]string{"id", "name"}). AddRow(7, "test_value"). - RowError(0, fmt.Errorf("row error")) + RowError(0, errors.New("row error")) m.ExpectPrepare(query). ExpectQuery(). @@ -94,9 +94,11 @@ func TestNew(t *testing.T) { mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) require.NoError(t, err, "Unexpected error while creating sqlmock", err) + defer func() { _ = mockDB.Close() }() mock.MatchExpectationsInOrder(false) + if tt.setupMock != nil { tt.setupMock(mock) } diff --git a/pkg/errtrace/example_trace_test.go b/pkg/errtrace/example_trace_test.go index c5081a00..24ef7831 100644 --- a/pkg/errtrace/example_trace_test.go +++ b/pkg/errtrace/example_trace_test.go @@ -1,6 +1,7 @@ package errtrace_test import ( + "errors" "fmt" "github.com/Vonage/gosrvlib/pkg/errtrace" @@ -8,7 +9,7 @@ import ( //nolint:testableexamples func ExampleTrace() { - err := fmt.Errorf("example error") + err := errors.New("example error") testErr := errtrace.Trace(err) fmt.Println(testErr) diff --git a/pkg/errtrace/trace_test.go b/pkg/errtrace/trace_test.go index db680b19..c7a57044 100644 --- a/pkg/errtrace/trace_test.go +++ b/pkg/errtrace/trace_test.go @@ -1,16 +1,16 @@ package errtrace import ( - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" ) -var errGlobalVarTest = Trace(fmt.Errorf("ERROR GLOBAL VAR")) +var errGlobalVarTest = Trace(errors.New("ERROR GLOBAL VAR")) func errorTest() error { - return Trace(fmt.Errorf("ERROR FUNC")) + return Trace(errors.New("ERROR FUNC")) } func TestTrace(t *testing.T) { @@ -20,7 +20,7 @@ func TestTrace(t *testing.T) { want := "/pkg/errtrace/trace_test.go, line: 13, function: github.com/Vonage/gosrvlib/pkg/errtrace.errorTest, error: ERROR FUNC" require.Contains(t, err.Error(), want, "unexpected output %v, want %v", err, want) - testErr := Trace(fmt.Errorf("ERROR VAR")) + testErr := Trace(errors.New("ERROR VAR")) want = "/pkg/errtrace/trace_test.go, line: 23, function: github.com/Vonage/gosrvlib/pkg/errtrace.TestTrace, error: ERROR VAR" require.Contains(t, testErr.Error(), want, "unexpected output %v, want %v", testErr, want) @@ -29,7 +29,7 @@ func TestTrace(t *testing.T) { require.Contains(t, errGlobalVarTest.Error(), want, "unexpected output %v, want %v", errGlobalVarTest, want) err = func() error { - return Trace(fmt.Errorf("ERROR LAMBDA FUNC")) + return Trace(errors.New("ERROR LAMBDA FUNC")) }() want = "/pkg/errtrace/trace_test.go, line: 32, function: github.com/Vonage/gosrvlib/pkg/errtrace.TestTrace.func1, error: ERROR LAMBDA FUNC" diff --git a/pkg/filter/filter.go b/pkg/filter/filter.go index 158508a8..419c1230 100644 --- a/pkg/filter/filter.go +++ b/pkg/filter/filter.go @@ -225,6 +225,7 @@ func (p *Processor) filterSliceValue(slice reflect.Value, offset uint, length in if n < length { // replace unselected elements by the ones that match slice.Index(n).Set(value) + n++ } } diff --git a/pkg/filter/filter_test.go b/pkg/filter/filter_test.go index 68018d5f..f8ca42a7 100644 --- a/pkg/filter/filter_test.go +++ b/pkg/filter/filter_test.go @@ -88,7 +88,7 @@ func TestNew(t *testing.T) { { name: "success", opts: []Option{ - func(v *Processor) error { + func(_ *Processor) error { return nil }, }, @@ -97,7 +97,7 @@ func TestNew(t *testing.T) { { name: "error - option error", opts: []Option{ - func(v *Processor) error { + func(_ *Processor) error { return errors.New("test error") }, }, diff --git a/pkg/filter/options.go b/pkg/filter/options.go index 9bfa4154..dfbb3c2c 100644 --- a/pkg/filter/options.go +++ b/pkg/filter/options.go @@ -2,7 +2,6 @@ package filter import ( "errors" - "fmt" ) // Option is the function that allows to set configuration options. @@ -43,7 +42,7 @@ func WithQueryFilterKey(key string) Option { func WithMaxRules(max uint) Option { return func(p *Processor) error { if max < 1 { - return fmt.Errorf("maxRules must be at least 1") + return errors.New("maxRules must be at least 1") } p.maxRules = max @@ -56,11 +55,11 @@ func WithMaxRules(max uint) Option { func WithMaxResults(max uint) Option { return func(p *Processor) error { if max < 1 { - return fmt.Errorf("maxResults must be at least 1") + return errors.New("maxResults must be at least 1") } if max > MaxResults { - return fmt.Errorf("maxResults must be less than MaxResults") + return errors.New("maxResults must be less than MaxResults") } p.maxResults = max diff --git a/pkg/healthcheck/checkoptions_test.go b/pkg/healthcheck/checkoptions_test.go index 1fd7bc2e..ae04e6c8 100644 --- a/pkg/healthcheck/checkoptions_test.go +++ b/pkg/healthcheck/checkoptions_test.go @@ -11,7 +11,7 @@ import ( func TestWithConfigureRequest(t *testing.T) { t.Parallel() - v := func(r *http.Request) {} + v := func(_ *http.Request) {} cfg := &checkConfig{} WithConfigureRequest(v)(cfg) require.Equal(t, reflect.ValueOf(v).Pointer(), reflect.ValueOf(cfg.configureRequest).Pointer()) diff --git a/pkg/healthcheck/checks_test.go b/pkg/healthcheck/checks_test.go index 5bf417af..6a067034 100644 --- a/pkg/healthcheck/checks_test.go +++ b/pkg/healthcheck/checks_test.go @@ -85,7 +85,7 @@ func TestCheckHttpStatus(t *testing.T) { checkWantStatus: http.StatusOK, checkOpts: []CheckOption{ WithConfigureRequest( - func(r *http.Request) {}, + func(_ *http.Request) {}, ), }, handlerMethod: http.MethodGet, @@ -104,10 +104,12 @@ func TestCheckHttpStatus(t *testing.T) { httputil.SendStatus(r.Context(), w, http.StatusMethodNotAllowed) return } + if tt.handlerMethod == r.Method { if tt.handlerDelay != 0 { time.Sleep(tt.handlerDelay) } + httputil.SendStatus(r.Context(), w, tt.handlerStatusCode) } }) @@ -118,7 +120,9 @@ func TestCheckHttpStatus(t *testing.T) { testHTTPClient := &http.Client{Timeout: 2 * time.Second} err := CheckHTTPStatus(testutil.Context(), testHTTPClient, tt.checkMethod, ts.URL+tt.checkExtraPath, tt.checkWantStatus, tt.checkTimeout, tt.checkOpts...) + t.Logf("check error: %v", err) + if tt.wantErr { require.Error(t, err, "CheckHTTPStatus() error = %v, wantErr %v", err, tt.wantErr) } else { diff --git a/pkg/healthcheck/handler_test.go b/pkg/healthcheck/handler_test.go index cf728ef1..e5efebe3 100644 --- a/pkg/healthcheck/handler_test.go +++ b/pkg/healthcheck/handler_test.go @@ -2,7 +2,7 @@ package healthcheck import ( "context" - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -30,7 +30,7 @@ func TestNewHandler(t *testing.T) { require.Equal(t, reflect.ValueOf(httputil.SendJSON).Pointer(), reflect.ValueOf(h1.writeResult).Pointer()) // With options - rw := func(ctx context.Context, w http.ResponseWriter, statusCode int, data any) {} + rw := func(_ context.Context, _ http.ResponseWriter, _ int, _ any) {} h2 := NewHandler(testChecks, WithResultWriter(rw)) require.Len(t, h2.checks, 2) require.Equal(t, 2, h2.checksCount) @@ -82,7 +82,7 @@ func TestHandler_ServeHTTP(t *testing.T) { name: "success mixed results", checks: []HealthCheck{ New("test_31", &testHealthChecker{delay: 100 * time.Millisecond, err: nil}), - New("test_32", &testHealthChecker{delay: 200 * time.Millisecond, err: fmt.Errorf("check error")}), + New("test_32", &testHealthChecker{delay: 200 * time.Millisecond, err: errors.New("check error")}), }, wantStatus: http.StatusServiceUnavailable, wantBody: `{"test_31":"OK","test_32":"check error"}`, @@ -101,7 +101,9 @@ func TestHandler_ServeHTTP(t *testing.T) { h := NewHandler(tt.checks, tt.opts...) st := time.Now() + h.ServeHTTP(rr, req) + el := time.Since(st) resp := rr.Result() diff --git a/pkg/healthcheck/options_test.go b/pkg/healthcheck/options_test.go index c9ca2d11..dd3e07e5 100644 --- a/pkg/healthcheck/options_test.go +++ b/pkg/healthcheck/options_test.go @@ -12,7 +12,7 @@ import ( func TestWithResultWriter(t *testing.T) { t.Parallel() - v := func(ctx context.Context, w http.ResponseWriter, statusCode int, data any) {} + v := func(_ context.Context, _ http.ResponseWriter, _ int, _ any) {} h := &Handler{} WithResultWriter(v)(h) require.Equal(t, reflect.ValueOf(v).Pointer(), reflect.ValueOf(h.writeResult).Pointer()) diff --git a/pkg/httpclient/client_test.go b/pkg/httpclient/client_test.go index 66f9ea84..b788265c 100644 --- a/pkg/httpclient/client_test.go +++ b/pkg/httpclient/client_test.go @@ -49,7 +49,7 @@ func TestClient_Do(t *testing.T) { body = append(body, []byte(bodyStr+`\n`)...) } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(body) })) @@ -147,6 +147,7 @@ func TestClient_Do(t *testing.T) { if tt.wantErr { require.Error(t, err) require.Contains(t, out, `"`+client.logPrefix+`error"`) + return } diff --git a/pkg/httpretrier/httpretrier_test.go b/pkg/httpretrier/httpretrier_test.go index a556227b..ba600663 100644 --- a/pkg/httpretrier/httpretrier_test.go +++ b/pkg/httpretrier/httpretrier_test.go @@ -4,7 +4,7 @@ package httpretrier import ( "bytes" "context" - "fmt" + "errors" "io" "net/http" "testing" @@ -30,7 +30,7 @@ func TestNew(t *testing.T) { { name: "succeeds with custom values", opts: []Option{ - WithRetryIfFn(func(r *http.Response, err error) bool { return true }), + WithRetryIfFn(func(_ *http.Response, _ error) bool { return true }), WithAttempts(5), WithDelay(601 * time.Millisecond), WithDelayFactor(1.3), @@ -62,12 +62,16 @@ func TestNew(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + c, err := New(http.DefaultClient, tt.opts...) + if tt.wantErr { require.Nil(t, c, "New() returned value should be nil") require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return } + require.NotNil(t, c, "New() returned value should not be nil") require.NoError(t, err, "New() unexpected error = %v", err) }) @@ -84,7 +88,7 @@ func Test_defaultRetryIf(t *testing.T) { }{ { name: "true with error", - err: fmt.Errorf("ERROR"), + err: errors.New("ERROR"), want: true, }, { @@ -98,7 +102,9 @@ func Test_defaultRetryIf(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + got := defaultRetryIf(nil, tt.err) + require.Equal(t, tt.want, got) }) } @@ -116,7 +122,7 @@ func TestRetryIfForWriteRequests(t *testing.T) { { name: "true with error", status: http.StatusOK, - err: fmt.Errorf("ERROR"), + err: errors.New("ERROR"), want: true, }, { @@ -173,7 +179,7 @@ func TestRetryIfForReadRequests(t *testing.T) { { name: "true with error", status: http.StatusOK, - err: fmt.Errorf("ERROR"), + err: errors.New("ERROR"), want: true, }, { @@ -317,7 +323,7 @@ func TestHTTPRetrier_Do(t *testing.T) { StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader([]byte{})), } - mock.EXPECT().Do(gomock.Any()).Return(nil, fmt.Errorf("network error")) + mock.EXPECT().Do(gomock.Any()).Return(nil, errors.New("network error")) mock.EXPECT().Do(gomock.Any()).Return(rErr, nil) mock.EXPECT().Do(gomock.Any()).Return(rOK, nil) }, @@ -331,7 +337,7 @@ func TestHTTPRetrier_Do(t *testing.T) { StatusCode: http.StatusInternalServerError, Body: io.NopCloser(bytes.NewReader([]byte{})), } - mock.EXPECT().Do(gomock.Any()).Return(nil, fmt.Errorf("network error")) + mock.EXPECT().Do(gomock.Any()).Return(nil, errors.New("network error")) mock.EXPECT().Do(gomock.Any()).Return(rErr, nil).Times(3) }, wantRemainingAttempts: 0, @@ -344,7 +350,7 @@ func TestHTTPRetrier_Do(t *testing.T) { StatusCode: http.StatusInternalServerError, Body: io.NopCloser(bytes.NewReader([]byte{})), } - mock.EXPECT().Do(gomock.Any()).DoAndReturn(func(r *http.Request) (*http.Response, error) { + mock.EXPECT().Do(gomock.Any()).DoAndReturn(func(_ *http.Request) (*http.Response, error) { time.Sleep(500 * time.Millisecond) return rErr, nil }) @@ -376,8 +382,10 @@ func TestHTTPRetrier_Do(t *testing.T) { } ctx := testutil.Context() + if tt.ctxTimeout > 0 { timeoutCtx, cancel := context.WithTimeout(testutil.Context(), tt.ctxTimeout) + defer cancel() ctx = timeoutCtx @@ -387,7 +395,7 @@ func TestHTTPRetrier_Do(t *testing.T) { require.NoError(t, err) if tt.requestBodyError { - r.GetBody = func() (io.ReadCloser, error) { return nil, fmt.Errorf("ERROR") } + r.GetBody = func() (io.ReadCloser, error) { return nil, errors.New("ERROR") } } opts := []Option{ @@ -405,6 +413,7 @@ func TestHTTPRetrier_Do(t *testing.T) { if resp != nil { _ = resp.Body.Close() } + require.Equal(t, tt.wantErr, err != nil, "Do() error = %v, wantErr %v", err, tt.wantErr) require.Equal(t, tt.wantRemainingAttempts, retrier.remainingAttempts, "Do() remainingAttempts = %v, wantRemainingAttempts %v", err, tt.wantErr) }) @@ -420,5 +429,6 @@ func TestHTTPRetrier_setTimer(t *testing.T) { time.Sleep(2 * time.Millisecond) c.setTimer(2 * time.Millisecond) + <-c.timer.C } diff --git a/pkg/httpretrier/options.go b/pkg/httpretrier/options.go index 61496f9f..a19775eb 100644 --- a/pkg/httpretrier/options.go +++ b/pkg/httpretrier/options.go @@ -1,7 +1,7 @@ package httpretrier import ( - "fmt" + "errors" "time" ) @@ -12,7 +12,7 @@ type Option func(c *HTTPRetrier) error func WithRetryIfFn(retryIfFn RetryIfFn) Option { return func(r *HTTPRetrier) error { if retryIfFn == nil { - return fmt.Errorf("the retry function is required") + return errors.New("the retry function is required") } r.retryIfFn = retryIfFn @@ -25,7 +25,7 @@ func WithRetryIfFn(retryIfFn RetryIfFn) Option { func WithAttempts(attempts uint) Option { return func(r *HTTPRetrier) error { if attempts < 1 { - return fmt.Errorf("the number of attempts must be at least 1") + return errors.New("the number of attempts must be at least 1") } r.attempts = attempts @@ -38,7 +38,7 @@ func WithAttempts(attempts uint) Option { func WithDelay(delay time.Duration) Option { return func(r *HTTPRetrier) error { if int64(delay) < 1 { - return fmt.Errorf("delay must be greater than zero") + return errors.New("delay must be greater than zero") } r.delay = delay @@ -53,7 +53,7 @@ func WithDelay(delay time.Duration) Option { func WithDelayFactor(delayFactor float64) Option { return func(r *HTTPRetrier) error { if delayFactor < 1 { - return fmt.Errorf("delay factor must be at least 1") + return errors.New("delay factor must be at least 1") } r.delayFactor = delayFactor @@ -67,7 +67,7 @@ func WithDelayFactor(delayFactor float64) Option { func WithJitter(jitter time.Duration) Option { return func(r *HTTPRetrier) error { if int64(jitter) < 1 { - return fmt.Errorf("jitter must be greater than zero") + return errors.New("jitter must be greater than zero") } r.jitter = jitter diff --git a/pkg/httpretrier/options_test.go b/pkg/httpretrier/options_test.go index 7a2dc05b..32ed4d10 100644 --- a/pkg/httpretrier/options_test.go +++ b/pkg/httpretrier/options_test.go @@ -15,7 +15,7 @@ func TestWithRetryIfFn(t *testing.T) { c := &HTTPRetrier{} - v := func(r *http.Response, err error) bool { return true } + v := func(_ *http.Response, _ error) bool { return true } err := WithRetryIfFn(v)(c) require.NoError(t, err) diff --git a/pkg/httpreverseproxy/client_test.go b/pkg/httpreverseproxy/client_test.go index f061effa..6f5463fd 100644 --- a/pkg/httpreverseproxy/client_test.go +++ b/pkg/httpreverseproxy/client_test.go @@ -62,6 +62,7 @@ func TestNew(t *testing.T) { if tt.wantErr { require.Nil(t, c, "New() returned client should be nil") require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return } @@ -108,7 +109,7 @@ func TestClient_ForwardRequest(t *testing.T) { libhttputil.SendStatus(r.Context(), w, http.StatusBadRequest) }) - targetMux.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) { + targetMux.HandleFunc("/error", func(_ http.ResponseWriter, _ *http.Request) { time.Sleep(1 + timeout) }) diff --git a/pkg/httpserver/config_test.go b/pkg/httpserver/config_test.go index e1567626..8552f2e4 100644 --- a/pkg/httpserver/config_test.go +++ b/pkg/httpserver/config_test.go @@ -152,7 +152,7 @@ func Test_setRouter(t *testing.T) { name: "should handle 405", method: http.MethodPost, setupRouter: func(r testRouter) { - fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fn := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, http.StatusText(http.StatusOK), http.StatusOK) }) r.Handler(http.MethodGet, "/not/allowed", fn) @@ -164,7 +164,7 @@ func Test_setRouter(t *testing.T) { name: "should handle panic in handler", method: http.MethodGet, setupRouter: func(r testRouter) { - fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fn := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { panic("panicking!") }) r.Handler(http.MethodGet, "/panic", fn) diff --git a/pkg/httpserver/deprecated_test.go b/pkg/httpserver/deprecated_test.go index 0ecf992f..ef46f962 100644 --- a/pkg/httpserver/deprecated_test.go +++ b/pkg/httpserver/deprecated_test.go @@ -10,7 +10,7 @@ import ( func TestWithInstrumentHandler(t *testing.T) { t.Parallel() - v := func(path string, handler http.HandlerFunc) http.Handler { return handler } + v := func(_ string, handler http.HandlerFunc) http.Handler { return handler } cfg := defaultConfig() err := WithInstrumentHandler(v)(cfg) require.NoError(t, err) diff --git a/pkg/httpserver/httpserver_test.go b/pkg/httpserver/httpserver_test.go index eed36e03..2a171335 100644 --- a/pkg/httpserver/httpserver_test.go +++ b/pkg/httpserver/httpserver_test.go @@ -5,6 +5,7 @@ package httpserver import ( "context" "encoding/json" + "errors" "fmt" "io" "net" @@ -82,13 +83,13 @@ func Test_defaultIPHandler(t *testing.T) { }{ { name: "success response", - ipFunc: func(ctx context.Context) (string, error) { return "0.0.0.0", nil }, + ipFunc: func(_ context.Context) (string, error) { return "0.0.0.0", nil }, wantIP: "0.0.0.0", wantErr: false, }, { name: "error response", - ipFunc: func(ctx context.Context) (string, error) { return "ERROR", fmt.Errorf("ERROR") }, + ipFunc: func(_ context.Context) (string, error) { return "ERROR", errors.New("ERROR") }, wantIP: "", wantErr: true, }, @@ -207,6 +208,7 @@ func (c *customMiddlewareBinder) middleware(ch chan struct{}) MiddlewareFn { return func(_ MiddlewareArgs, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ch <- struct{}{} + next.ServeHTTP(w, r) }) } @@ -323,7 +325,7 @@ func TestStart(t *testing.T) { WithRequestTimeout(1 * time.Minute), WithShutdownTimeout(1 * time.Millisecond), WithEnableAllDefaultRoutes(), - WithInstrumentHandler(func(path string, handler http.HandlerFunc) http.Handler { return handler }), + WithInstrumentHandler(func(_ string, handler http.HandlerFunc) http.Handler { return handler }), WithShutdownTimeout(1 * time.Second), }, setupBinder: func(b *MockBinder) { @@ -419,6 +421,7 @@ YlAqGKDZ+A+l if tt.failListenPort != 0 { l, err := net.Listen("tcp", fmt.Sprintf(":%d", tt.failListenPort)) require.NoError(t, err, "failed starting pre-listener") + defer func() { _ = l.Close() }() } @@ -434,11 +437,11 @@ YlAqGKDZ+A+l type mockListenerErr struct{} func (ls mockListenerErr) Accept() (net.Conn, error) { - return nil, fmt.Errorf("ERROR") + return nil, errors.New("ERROR") } func (ls mockListenerErr) Close() error { - return fmt.Errorf("ERROR") + return errors.New("ERROR") } func (ls mockListenerErr) Addr() net.Addr { diff --git a/pkg/httpserver/middleware_test.go b/pkg/httpserver/middleware_test.go index 42e2902e..4aaada8c 100644 --- a/pkg/httpserver/middleware_test.go +++ b/pkg/httpserver/middleware_test.go @@ -17,7 +17,7 @@ import ( func TestRequestInjectHandler(t *testing.T) { t.Parallel() - nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + nextHandler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := logging.FromContext(r.Context()) require.NotNil(t, l, "logger not found") diff --git a/pkg/httpserver/options.go b/pkg/httpserver/options.go index e7fb325b..3acd9059 100644 --- a/pkg/httpserver/options.go +++ b/pkg/httpserver/options.go @@ -2,6 +2,7 @@ package httpserver import ( "crypto/tls" + "errors" "fmt" "net/http" "sync" @@ -17,7 +18,7 @@ type Option func(*config) error func WithRouter(r *httprouter.Router) Option { return func(cfg *config) error { if r == nil { - return fmt.Errorf("router is required") + return errors.New("router is required") } cfg.router = r @@ -44,7 +45,7 @@ func WithServerAddr(addr string) Option { func WithRequestTimeout(timeout time.Duration) Option { return func(cfg *config) error { if timeout <= 0 { - return fmt.Errorf("invalid requestTimeout") + return errors.New("invalid requestTimeout") } cfg.requestTimeout = timeout @@ -57,7 +58,7 @@ func WithRequestTimeout(timeout time.Duration) Option { func WithServerReadHeaderTimeout(timeout time.Duration) Option { return func(cfg *config) error { if timeout <= 0 { - return fmt.Errorf("invalid serverReadHeaderTimeout") + return errors.New("invalid serverReadHeaderTimeout") } cfg.serverReadHeaderTimeout = timeout @@ -70,7 +71,7 @@ func WithServerReadHeaderTimeout(timeout time.Duration) Option { func WithServerReadTimeout(timeout time.Duration) Option { return func(cfg *config) error { if timeout <= 0 { - return fmt.Errorf("invalid serverReadTimeout") + return errors.New("invalid serverReadTimeout") } cfg.serverReadTimeout = timeout @@ -83,7 +84,7 @@ func WithServerReadTimeout(timeout time.Duration) Option { func WithServerWriteTimeout(timeout time.Duration) Option { return func(cfg *config) error { if timeout <= 0 { - return fmt.Errorf("invalid serverWriteTimeout") + return errors.New("invalid serverWriteTimeout") } cfg.serverWriteTimeout = timeout @@ -96,7 +97,7 @@ func WithServerWriteTimeout(timeout time.Duration) Option { func WithShutdownTimeout(timeout time.Duration) Option { return func(cfg *config) error { if timeout <= 0 { - return fmt.Errorf("invalid shutdownTimeout") + return errors.New("invalid shutdownTimeout") } cfg.shutdownTimeout = timeout @@ -109,7 +110,7 @@ func WithShutdownTimeout(timeout time.Duration) Option { func WithShutdownWaitGroup(wg *sync.WaitGroup) Option { return func(cfg *config) error { if wg == nil { - return fmt.Errorf("shutdownWaitGroup is required") + return errors.New("shutdownWaitGroup is required") } cfg.shutdownWaitGroup = wg @@ -123,7 +124,7 @@ func WithShutdownWaitGroup(wg *sync.WaitGroup) Option { func WithShutdownSignalChan(ch chan struct{}) Option { return func(cfg *config) error { if ch == nil { - return fmt.Errorf("shutdownSignalChan is required") + return errors.New("shutdownSignalChan is required") } cfg.shutdownSignalChan = ch @@ -169,7 +170,7 @@ func WithEnableAllDefaultRoutes() Option { func WithIndexHandlerFunc(handler IndexHandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("indexHandlerFunc is required") + return errors.New("indexHandlerFunc is required") } cfg.indexHandlerFunc = handler @@ -182,7 +183,7 @@ func WithIndexHandlerFunc(handler IndexHandlerFunc) Option { func WithIPHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("ipHandlerFunc is required") + return errors.New("ipHandlerFunc is required") } cfg.ipHandlerFunc = handler @@ -195,7 +196,7 @@ func WithIPHandlerFunc(handler http.HandlerFunc) Option { func WithMetricsHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("metricsHandlerFunc is required") + return errors.New("metricsHandlerFunc is required") } cfg.metricsHandlerFunc = handler @@ -208,7 +209,7 @@ func WithMetricsHandlerFunc(handler http.HandlerFunc) Option { func WithPingHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("pingHandlerFunc is required") + return errors.New("pingHandlerFunc is required") } cfg.pingHandlerFunc = handler @@ -221,7 +222,7 @@ func WithPingHandlerFunc(handler http.HandlerFunc) Option { func WithPProfHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("pprofHandlerFunc is required") + return errors.New("pprofHandlerFunc is required") } cfg.pprofHandlerFunc = handler @@ -234,7 +235,7 @@ func WithPProfHandlerFunc(handler http.HandlerFunc) Option { func WithStatusHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("statusHandlerFunc is required") + return errors.New("statusHandlerFunc is required") } cfg.statusHandlerFunc = handler @@ -247,7 +248,7 @@ func WithStatusHandlerFunc(handler http.HandlerFunc) Option { func WithTraceIDHeaderName(name string) Option { return func(cfg *config) error { if name == "" { - return fmt.Errorf("traceIDHeaderName is required") + return errors.New("traceIDHeaderName is required") } cfg.traceIDHeaderName = name @@ -277,7 +278,7 @@ func WithMiddlewareFn(fn ...MiddlewareFn) Option { func WithNotFoundHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("notFoundHandlerFunc is required") + return errors.New("notFoundHandlerFunc is required") } cfg.notFoundHandlerFunc = handler @@ -290,7 +291,7 @@ func WithNotFoundHandlerFunc(handler http.HandlerFunc) Option { func WithMethodNotAllowedHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("methodNotAllowedHandlerFunc is required") + return errors.New("methodNotAllowedHandlerFunc is required") } cfg.methodNotAllowedHandlerFunc = handler @@ -303,7 +304,7 @@ func WithMethodNotAllowedHandlerFunc(handler http.HandlerFunc) Option { func WithPanicHandlerFunc(handler http.HandlerFunc) Option { return func(cfg *config) error { if handler == nil { - return fmt.Errorf("panicHandlerFunc is required") + return errors.New("panicHandlerFunc is required") } cfg.panicHandlerFunc = handler diff --git a/pkg/httpserver/options_test.go b/pkg/httpserver/options_test.go index 1e196694..3bbfac27 100644 --- a/pkg/httpserver/options_test.go +++ b/pkg/httpserver/options_test.go @@ -231,8 +231,8 @@ func TestWithIndexHandlerFunc(t *testing.T) { err := WithIndexHandlerFunc(nil)(cfg) require.Error(t, err) - v := func(routes []Route) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + v := func(_ []Route) http.HandlerFunc { + return func(_ http.ResponseWriter, _ *http.Request) { // mock function } } diff --git a/pkg/httpserver/routes_test.go b/pkg/httpserver/routes_test.go index e9c572a3..5913633d 100644 --- a/pkg/httpserver/routes_test.go +++ b/pkg/httpserver/routes_test.go @@ -14,11 +14,11 @@ func Test_newDefaultRoutes(t *testing.T) { cfg := defaultConfig() cfg.defaultEnabledRoutes = allDefaultRoutes() - cfg.metricsHandlerFunc = func(w http.ResponseWriter, r *http.Request) {} - cfg.pingHandlerFunc = func(w http.ResponseWriter, r *http.Request) {} - cfg.pprofHandlerFunc = func(w http.ResponseWriter, r *http.Request) {} - cfg.statusHandlerFunc = func(w http.ResponseWriter, r *http.Request) {} - cfg.ipHandlerFunc = func(w http.ResponseWriter, r *http.Request) {} + cfg.metricsHandlerFunc = func(_ http.ResponseWriter, _ *http.Request) {} + cfg.pingHandlerFunc = func(_ http.ResponseWriter, _ *http.Request) {} + cfg.pprofHandlerFunc = func(_ http.ResponseWriter, _ *http.Request) {} + cfg.statusHandlerFunc = func(_ http.ResponseWriter, _ *http.Request) {} + cfg.ipHandlerFunc = func(_ http.ResponseWriter, _ *http.Request) {} cfg.disableDefaultRouteLogger[IndexRoute] = true cfg.disableDefaultRouteLogger[IPRoute] = true diff --git a/pkg/httputil/jsendx/deprecated_test.go b/pkg/httputil/jsendx/deprecated_test.go index 7f5f4c76..dbce1ebd 100644 --- a/pkg/httputil/jsendx/deprecated_test.go +++ b/pkg/httputil/jsendx/deprecated_test.go @@ -29,7 +29,7 @@ func TestNewRouter(t *testing.T) { name: "should handle 405", method: http.MethodPost, setupRouter: func(r *httprouter.Router) { - fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fn := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, http.StatusText(http.StatusOK), http.StatusOK) }) r.Handler(http.MethodGet, "/not/allowed", fn) @@ -41,7 +41,7 @@ func TestNewRouter(t *testing.T) { name: "should handle panic in handler", method: http.MethodGet, setupRouter: func(r *httprouter.Router) { - fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fn := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { panic("panicking!") }) r.Handler(http.MethodGet, "/panic", fn) @@ -56,7 +56,7 @@ func TestNewRouter(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - defaultInstrumentHandler := func(path string, handler http.HandlerFunc) http.Handler { return handler } + defaultInstrumentHandler := func(_ string, handler http.HandlerFunc) http.Handler { return handler } params := &AppInfo{ ProgramName: "test", diff --git a/pkg/httputil/jsendx/jsendx_test.go b/pkg/httputil/jsendx/jsendx_test.go index c02b270f..96bdb288 100644 --- a/pkg/httputil/jsendx/jsendx_test.go +++ b/pkg/httputil/jsendx/jsendx_test.go @@ -3,7 +3,7 @@ package jsendx import ( "context" "encoding/json" - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -53,7 +53,7 @@ func TestSend(t *testing.T) { mockWriter := NewMockTestHTTPResponseWriter(gomock.NewController(t)) mockWriter.EXPECT().Header().AnyTimes().Return(http.Header{}) mockWriter.EXPECT().WriteHeader(http.StatusOK) - mockWriter.EXPECT().Write(gomock.Any()).Return(0, fmt.Errorf("io error")) + mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("io error")) Send(testutil.Context(), mockWriter, http.StatusOK, params, "message") } @@ -215,13 +215,13 @@ func TestDefaultIPHandler(t *testing.T) { }{ { name: "success response", - ipFunc: func(ctx context.Context) (string, error) { return "0.0.0.0", nil }, + ipFunc: func(_ context.Context) (string, error) { return "0.0.0.0", nil }, wantIP: "0.0.0.0", wantErr: false, }, { name: "error response", - ipFunc: func(ctx context.Context) (string, error) { return "ERROR", fmt.Errorf("ERROR") }, + ipFunc: func(_ context.Context) (string, error) { return "ERROR", errors.New("ERROR") }, wantIP: "", wantErr: true, }, diff --git a/pkg/httputil/response_test.go b/pkg/httputil/response_test.go index ca36aef2..bcf41cd4 100644 --- a/pkg/httputil/response_test.go +++ b/pkg/httputil/response_test.go @@ -1,7 +1,7 @@ package httputil import ( - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -49,6 +49,7 @@ func TestStatus_MarshalJSON(t *testing.T) { t.Errorf("MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) return } + if !reflect.DeepEqual(got, tt.want) { t.Errorf("MarshalJSON() got = %v, want %v", string(got), string(tt.want)) } @@ -102,7 +103,7 @@ func TestSendText(t *testing.T) { mockWriter := NewMockTestHTTPResponseWriter(gomock.NewController(t)) mockWriter.EXPECT().Header().AnyTimes().Return(http.Header{}) mockWriter.EXPECT().WriteHeader(http.StatusOK) - mockWriter.EXPECT().Write(gomock.Any()).Return(0, fmt.Errorf("io error")) + mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("io error")) SendText(testutil.Context(), mockWriter, http.StatusOK, data) } @@ -132,7 +133,7 @@ func TestSendJSON(t *testing.T) { mockWriter := NewMockTestHTTPResponseWriter(gomock.NewController(t)) mockWriter.EXPECT().Header().AnyTimes().Return(http.Header{}) mockWriter.EXPECT().WriteHeader(http.StatusOK) - mockWriter.EXPECT().Write(gomock.Any()).Return(0, fmt.Errorf("io error")) + mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("io error")) SendJSON(testutil.Context(), mockWriter, http.StatusOK, data) } @@ -162,7 +163,7 @@ func TestSendXML(t *testing.T) { mockWriter := NewMockTestHTTPResponseWriter(gomock.NewController(t)) mockWriter.EXPECT().Header().AnyTimes().Return(http.Header{}) mockWriter.EXPECT().WriteHeader(http.StatusOK) - mockWriter.EXPECT().Write(gomock.Any()).Return(0, fmt.Errorf("io error")) - mockWriter.EXPECT().Write(gomock.Any()).Return(0, fmt.Errorf("io error")) + mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("io error")) + mockWriter.EXPECT().Write(gomock.Any()).Return(0, errors.New("io error")) SendXML(testutil.Context(), mockWriter, http.StatusOK, XMLHeader, data) } diff --git a/pkg/httputil/respwriter.go b/pkg/httputil/respwriter.go index e29d205d..5d627513 100644 --- a/pkg/httputil/respwriter.go +++ b/pkg/httputil/respwriter.go @@ -2,7 +2,7 @@ package httputil import ( "bufio" - "fmt" + "errors" "io" "net" "net/http" @@ -52,7 +52,7 @@ func (b *responseWriterWrapper) Flush() { func (b *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { hj, ok := b.ResponseWriter.(http.Hijacker) if !ok { - return nil, nil, fmt.Errorf("the Hijacker is not supported by the ResponseWriter") + return nil, nil, errors.New("the Hijacker is not supported by the ResponseWriter") } return hj.Hijack() @@ -62,7 +62,7 @@ func (b *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { func (b *responseWriterWrapper) Push(target string, opts *http.PushOptions) error { pusher, ok := b.ResponseWriter.(http.Pusher) if !ok { - return fmt.Errorf("the Pusher is not supported by the ResponseWriter") + return errors.New("the Pusher is not supported by the ResponseWriter") } return pusher.Push(target, opts) @@ -79,7 +79,7 @@ func (b *responseWriterWrapper) ReadFrom(r io.Reader) (int64, error) { rf, ok := b.ResponseWriter.(io.ReaderFrom) if !ok { - return 0, fmt.Errorf("the ReaderFrom is not supported by the ResponseWriter") + return 0, errors.New("the ReaderFrom is not supported by the ResponseWriter") } b.maybeWriteHeader() diff --git a/pkg/ipify/client_test.go b/pkg/ipify/client_test.go index e773e4f1..2bb70002 100644 --- a/pkg/ipify/client_test.go +++ b/pkg/ipify/client_test.go @@ -57,8 +57,10 @@ func TestNew(t *testing.T) { if tt.wantErr { require.Nil(t, c, "New() returned client should be nil") require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return } + require.NotNil(t, c, "New() returned client should not be nil") require.NoError(t, err, "New() unexpected error = %v", err) require.Equal(t, tt.wantTimeout, c.timeout, "New() unexpected timeout = %d got %d", tt.wantTimeout, c.timeout) @@ -80,7 +82,7 @@ func TestClient_GetPublicIP(t *testing.T) { }{ { name: "fails because status not OK", - getIPHandler: func(w http.ResponseWriter, r *http.Request) { + getIPHandler: func(w http.ResponseWriter, _ *http.Request) { httputil.SendStatus(testutil.Context(), w, http.StatusInternalServerError) }, wantIP: "", @@ -88,7 +90,7 @@ func TestClient_GetPublicIP(t *testing.T) { }, { name: "fails because of timeout", - getIPHandler: func(w http.ResponseWriter, r *http.Request) { + getIPHandler: func(w http.ResponseWriter, _ *http.Request) { time.Sleep(5 * time.Second) httputil.SendStatus(testutil.Context(), w, http.StatusOK) }, @@ -96,14 +98,14 @@ func TestClient_GetPublicIP(t *testing.T) { }, { name: "fails because of bad content", - getIPHandler: func(w http.ResponseWriter, r *http.Request) { + getIPHandler: func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Length", "1") }, wantErr: true, }, { name: "succeed with valid response", - getIPHandler: func(w http.ResponseWriter, r *http.Request) { + getIPHandler: func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) _, err := w.Write([]byte("0.0.0.0")) @@ -120,10 +122,12 @@ func TestClient_GetPublicIP(t *testing.T) { mux := testutil.RouterWithHandler(http.MethodGet, "/", tt.getIPHandler) ts := httptest.NewServer(mux) + defer ts.Close() opts := []Option{WithURL(ts.URL)} c, err := New(opts...) + require.NoError(t, err, "Client.GetPublicIP() create client unexpected error = %v", err) ip, err := c.GetPublicIP(testutil.Context()) diff --git a/pkg/jwt/jwt.go b/pkg/jwt/jwt.go index 781b9a08..fdf7f6cf 100644 --- a/pkg/jwt/jwt.go +++ b/pkg/jwt/jwt.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "net/http" "strings" "time" @@ -84,11 +83,11 @@ func defaultSigningMethod() SigningMethod { // New creates a new instance. func New(key []byte, userHashFn UserHashFn, opts ...Option) (*JWT, error) { if len(key) == 0 { - return nil, fmt.Errorf("empty JWT key") + return nil, errors.New("empty JWT key") } if userHashFn == nil { - return nil, fmt.Errorf("empty user hash function") + return nil, errors.New("empty user hash function") } c := defaultJWT() @@ -225,7 +224,7 @@ func (c *JWT) checkToken(r *http.Request) (*Claims, error) { _, err := jwt.ParseWithClaims( signedToken, claims, - func(token *jwt.Token) (any, error) { + func(_ *jwt.Token) (any, error) { return c.key, nil }, ) diff --git a/pkg/jwt/jwt_test.go b/pkg/jwt/jwt_test.go index d48f9bb8..6c7c9810 100644 --- a/pkg/jwt/jwt_test.go +++ b/pkg/jwt/jwt_test.go @@ -2,7 +2,7 @@ package jwt import ( "context" - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -28,23 +28,23 @@ func TestNew(t *testing.T) { { name: "success with default options", key: []byte("test-key-01"), - userHashFn: func(username string) ([]byte, error) { return []byte("hash-01"), nil }, + userHashFn: func(_ string) ([]byte, error) { return []byte("hash-01"), nil }, wantErr: false, }, { name: "success with custom options", key: []byte("test-key-02"), - userHashFn: func(username string) ([]byte, error) { return []byte("hash-02"), nil }, + userHashFn: func(_ string) ([]byte, error) { return []byte("hash-02"), nil }, opts: []Option{ WithExpirationTime(1 * time.Minute), WithRenewTime(10 * time.Second), - WithSendResponseFn(func(ctx context.Context, w http.ResponseWriter, statusCode int, data string) {}), + WithSendResponseFn(func(_ context.Context, _ http.ResponseWriter, _ int, _ string) {}), }, wantErr: false, }, { name: "failure with empty key", - userHashFn: func(username string) ([]byte, error) { return []byte("hash-01"), nil }, + userHashFn: func(_ string) ([]byte, error) { return []byte("hash-01"), nil }, wantErr: true, }, { @@ -63,8 +63,10 @@ func TestNew(t *testing.T) { if tt.wantErr { require.Nil(t, c, "New() returned value should be nil") require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return } + require.NotNil(t, c, "New() returned value should not be nil") require.NoError(t, err, "New() unexpected error = %v", err) }) @@ -163,6 +165,7 @@ func TestLoginHandler(t *testing.T) { body, _ := io.ReadAll(resp.Body) require.Equal(t, tt.status, resp.StatusCode) + if tt.status != http.StatusOK { require.Equal(t, tt.want, string(body)) } else { @@ -377,7 +380,7 @@ func TestIsAuthorized(t *testing.T) { // testUserHash assumes password = username. func testUserHash(username string) ([]byte, error) { if username == "" { - return nil, fmt.Errorf("invalid username") + return nil, errors.New("invalid username") } return bcrypt.GenerateFromPassword([]byte(username), bcrypt.MinCost) //nolint:wrapcheck @@ -386,11 +389,11 @@ func testUserHash(username string) ([]byte, error) { type testSigningMethodError struct{} func (c *testSigningMethodError) Verify(_, _ string, _ any) error { - return fmt.Errorf("VERIFY ERROR") + return errors.New("VERIFY ERROR") } func (c *testSigningMethodError) Sign(_ string, _ any) (string, error) { - return "", fmt.Errorf("SIGN ERROR") + return "", errors.New("SIGN ERROR") } func (c *testSigningMethodError) Alg() string { diff --git a/pkg/jwt/options_test.go b/pkg/jwt/options_test.go index ad8b8d27..e4cfea6b 100644 --- a/pkg/jwt/options_test.go +++ b/pkg/jwt/options_test.go @@ -39,7 +39,7 @@ func TestWithSendResponseFn(t *testing.T) { c := &JWT{} - v := func(ctx context.Context, w http.ResponseWriter, statusCode int, data string) {} + v := func(_ context.Context, _ http.ResponseWriter, _ int, _ string) {} WithSendResponseFn(v)(c) require.NotNil(t, v, c.sendResponseFn) diff --git a/pkg/kafka/consumer_test.go b/pkg/kafka/consumer_test.go index a055b0c3..74c1a607 100644 --- a/pkg/kafka/consumer_test.go +++ b/pkg/kafka/consumer_test.go @@ -2,7 +2,7 @@ package kafka import ( "context" - "fmt" + "errors" "testing" "time" @@ -78,7 +78,7 @@ func (m mockConsumerClient) Close() error { type mockConsumerClientError struct{} func (m mockConsumerClientError) ReadMessage(_ context.Context) (kafka.Message, error) { - return kafka.Message{}, fmt.Errorf("error Receive") + return kafka.Message{}, errors.New("error Receive") } func (m mockConsumerClientError) Config() kafka.ReaderConfig { @@ -86,7 +86,7 @@ func (m mockConsumerClientError) Config() kafka.ReaderConfig { } func (m mockConsumerClientError) Close() error { - return fmt.Errorf("error Close") + return errors.New("error Close") } func Test_Consumer_Receive(t *testing.T) { @@ -137,7 +137,7 @@ func Test_Consumer_HealthCheck(t *testing.T) { err = consumer.HealthCheck(ctx) require.Error(t, err) - consumer.checkFn = func(ctx context.Context, address string) error { + consumer.checkFn = func(_ context.Context, _ string) error { return nil } diff --git a/pkg/kafka/producer_test.go b/pkg/kafka/producer_test.go index 3a02160e..e21bae16 100644 --- a/pkg/kafka/producer_test.go +++ b/pkg/kafka/producer_test.go @@ -2,7 +2,7 @@ package kafka import ( "context" - "fmt" + "errors" "testing" "time" @@ -68,11 +68,11 @@ func (m mockProducerClient) Close() error { type mockProducerClientError struct{} func (m mockProducerClientError) WriteMessages(_ context.Context, _ ...kafka.Message) error { - return fmt.Errorf("error WriteMessages") + return errors.New("error WriteMessages") } func (m mockProducerClientError) Close() error { - return fmt.Errorf("error Close") + return errors.New("error Close") } func TestSendError(t *testing.T) { diff --git a/pkg/kafkacgo/consumer_test.go b/pkg/kafkacgo/consumer_test.go index 7e21aae4..d664ef2d 100644 --- a/pkg/kafkacgo/consumer_test.go +++ b/pkg/kafkacgo/consumer_test.go @@ -1,7 +1,7 @@ package kafkacgo import ( - "fmt" + "errors" "testing" "time" @@ -96,11 +96,11 @@ func (m mockConsumerClient) Close() error { type mockConsumerClientError struct{} func (m mockConsumerClientError) ReadMessage(_ time.Duration) (*kafka.Message, error) { - return nil, fmt.Errorf("error ReadMessage") + return nil, errors.New("error ReadMessage") } func (m mockConsumerClientError) Close() error { - return fmt.Errorf("error Close") + return errors.New("error Close") } func Test_Receive(t *testing.T) { diff --git a/pkg/kafkacgo/producer_test.go b/pkg/kafkacgo/producer_test.go index eab86350..31af147c 100644 --- a/pkg/kafkacgo/producer_test.go +++ b/pkg/kafkacgo/producer_test.go @@ -1,7 +1,7 @@ package kafkacgo import ( - "fmt" + "errors" "testing" "time" @@ -84,7 +84,7 @@ func (m mockProducerClient) Close() {} type mockProducerClientError struct{} func (m mockProducerClientError) Produce(_ *kafka.Message, _ chan kafka.Event) error { - return fmt.Errorf("error Produce") + return errors.New("error Produce") } func (m mockProducerClientError) Close() {} diff --git a/pkg/logging/format_test.go b/pkg/logging/format_test.go index c426f043..2915d17f 100644 --- a/pkg/logging/format_test.go +++ b/pkg/logging/format_test.go @@ -43,6 +43,7 @@ func TestParseFormat(t *testing.T) { if tt.wantErr { require.Error(t, err, "ParseFormat() error = %v, wantErr %v", err, tt.wantErr) } + require.Equal(t, tt.want, got, "ParseFormat() got = %v, want %v", got, tt.want) }) } diff --git a/pkg/logging/level_test.go b/pkg/logging/level_test.go index bde3b452..c131fecb 100644 --- a/pkg/logging/level_test.go +++ b/pkg/logging/level_test.go @@ -98,6 +98,7 @@ func TestParseLevel(t *testing.T) { if tt.wantErr { require.Error(t, err, "ParseLevel() error = %v, wantErr %v", err, tt.wantErr) } + require.Equal(t, tt.want, got, "ParseLevel() got = %v, want %v", got, tt.want) }) } diff --git a/pkg/logging/logging.go b/pkg/logging/logging.go index 1c3719e6..bb42c38a 100644 --- a/pkg/logging/logging.go +++ b/pkg/logging/logging.go @@ -4,6 +4,7 @@ package logging import ( "context" + "errors" "fmt" "io" "os" @@ -73,7 +74,7 @@ func NewLogger(opts ...Option) (*zap.Logger, error) { levelEncoder = zapcore.LowercaseLevelEncoder timeEncoder = zapcore.EpochNanosTimeEncoder default: - return nil, fmt.Errorf("invalid log format") + return nil, errors.New("invalid log format") } hostname, err := os.Hostname() diff --git a/pkg/logging/logging_test.go b/pkg/logging/logging_test.go index 92a6b7bc..d2b52959 100644 --- a/pkg/logging/logging_test.go +++ b/pkg/logging/logging_test.go @@ -6,7 +6,7 @@ import ( "bytes" "context" "encoding/json" - "fmt" + "errors" "net/url" "strings" "testing" @@ -66,6 +66,7 @@ func TestNewLogger(t *testing.T) { opts := tt.opts var loggedMetricLevel string + opts = append(opts, WithIncrementLogMetricsFunc(func(ll string) { loggedMetricLevel = ll })) @@ -295,7 +296,7 @@ func TestLogDifferences(t *testing.T) { type testCloseError struct{} func (c *testCloseError) Close() error { - return fmt.Errorf("close error") + return errors.New("close error") } type testCloseOK struct{} diff --git a/pkg/logging/options_test.go b/pkg/logging/options_test.go index 763a2e7a..30492884 100644 --- a/pkg/logging/options_test.go +++ b/pkg/logging/options_test.go @@ -42,7 +42,7 @@ func TestWithFields(t *testing.T) { func TestWithIncrementLogMetricsFunc(t *testing.T) { t.Parallel() - v := func(s string) { + v := func(_ string) { // mock function } cfg := &config{} @@ -74,7 +74,9 @@ func TestWithFormatStr(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + cfg := &config{} + if err := WithFormatStr(tt.testValue)(cfg); (err != nil) != tt.wantErr { t.Errorf("WithFormatStr() error = %v, wantErr %v", err, tt.wantErr) } @@ -105,7 +107,9 @@ func TestWithLevelStr(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + cfg := &config{} + if err := WithLevelStr(tt.testValue)(cfg); (err != nil) != tt.wantErr { t.Errorf("WithLevelStr() error = %v, wantErr %v", err, tt.wantErr) } diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index 9f3173bd..f0313d20 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -51,7 +51,7 @@ func (c *Default) InstrumentRoundTripper(next http.RoundTripper) http.RoundTripp // MetricsHandlerFunc returns an http handler function. func (c *Default) MetricsHandlerFunc() http.HandlerFunc { // Returns "OK" by default. - return func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`OK`)) } + return func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`OK`)) } } // IncLogLevelCounter is an empty function. diff --git a/pkg/metrics/metrics_test.go b/pkg/metrics/metrics_test.go index dcbb7e7e..d62ec7fd 100644 --- a/pkg/metrics/metrics_test.go +++ b/pkg/metrics/metrics_test.go @@ -51,7 +51,7 @@ func TestInstrumentRoundTripper(t *testing.T) { server := httptest.NewServer( http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { + func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`OK`)) }, diff --git a/pkg/metrics/prometheus/client_test.go b/pkg/metrics/prometheus/client_test.go index 4ed5c287..3054b447 100644 --- a/pkg/metrics/prometheus/client_test.go +++ b/pkg/metrics/prometheus/client_test.go @@ -2,7 +2,7 @@ package prometheus import ( "context" - "fmt" + "errors" "net/http" "net/http/httptest" "testing" @@ -42,7 +42,7 @@ func TestNew(t *testing.T) { }, { name: "fails with invalid option", - opts: []Option{func(c *Client) error { return fmt.Errorf("Error") }}, + opts: []Option{func(_ *Client) error { return errors.New("Error") }}, wantErr: true, }, { @@ -64,11 +64,14 @@ func TestNew(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + _, err := New(tt.opts...) + if tt.wantErr { require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) return } + require.NoError(t, err, "New() unexpected error = %v", err) }) } @@ -108,7 +111,7 @@ func TestInstrumentRoundTripper(t *testing.T) { server := httptest.NewServer( http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { + func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`OK`)) }, diff --git a/pkg/metrics/statsd/client.go b/pkg/metrics/statsd/client.go index 844a9c8e..fdfcddb5 100644 --- a/pkg/metrics/statsd/client.go +++ b/pkg/metrics/statsd/client.go @@ -134,7 +134,7 @@ func (c *Client) InstrumentRoundTripper(next http.RoundTripper) http.RoundTrippe // MetricsHandlerFunc returns an http handler function to serve the metrics endpoint. // This is not used for the StatsD implementation as the metrics are directly sent to the StatsD server. func (c *Client) MetricsHandlerFunc() http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { status := http.StatusNotImplemented http.Error(w, http.StatusText(status), status) } diff --git a/pkg/metrics/statsd/client_test.go b/pkg/metrics/statsd/client_test.go index 7e00808c..d8e0367a 100644 --- a/pkg/metrics/statsd/client_test.go +++ b/pkg/metrics/statsd/client_test.go @@ -56,11 +56,14 @@ func TestNew(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + _, err := New(tt.opts...) + if tt.wantErr { require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) return } + require.NoError(t, err, "New() unexpected error = %v", err) }) } @@ -78,10 +81,12 @@ TEST.inbound.test.POST.501.time:[0-9]+\|ms TEST.inbound.test.POST.out:1\|c` re := regexp.MustCompile(exp) got := string(p) + if !re.MatchString(got) { t.Errorf("expected: %v , got: %v", exp, got) } }) + require.NoError(t, err, "newTestStatsdServer() unexpected error = %v", err) defer srv.Close() @@ -119,10 +124,12 @@ TEST.outbound.GET.200.time:[0-9]+\|ms TEST.outbound.GET.out:1\|c` re := regexp.MustCompile(exp) got := string(p) + if !re.MatchString(got) { t.Errorf("expected: %v\n\ngot: %v", exp, got) } }) + require.NoError(t, err, "newTestStatsdServer() unexpected error = %v", err) defer srv.Close() @@ -138,7 +145,7 @@ TEST.outbound.GET.out:1\|c` server := httptest.NewServer( http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { + func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`OK`)) }, diff --git a/pkg/mysqllock/mysqllock_test.go b/pkg/mysqllock/mysqllock_test.go index cc1564da..eb0576f8 100644 --- a/pkg/mysqllock/mysqllock_test.go +++ b/pkg/mysqllock/mysqllock_test.go @@ -2,7 +2,7 @@ package mysqllock import ( "context" - "fmt" + "errors" "testing" "time" @@ -38,7 +38,7 @@ func TestDB_Acquire(t *testing.T) { name: "error executing get lock", setupMocks: func(mock sqlmock.Sqlmock) { mock.ExpectQuery(sqlGetLock). - WillReturnError(fmt.Errorf("database error")) + WillReturnError(errors.New("database error")) }, wantErr: true, }, @@ -65,7 +65,7 @@ func TestDB_Acquire(t *testing.T) { WillReturnRows(sqlmock.NewRows([]string{"result"}).AddRow(1)) mock.ExpectExec(sqlReleaseLock). - WillReturnError(fmt.Errorf("db error")) + WillReturnError(errors.New("db error")) }, wantErr: false, wantReleaseErr: true, @@ -85,6 +85,7 @@ func TestDB_Acquire(t *testing.T) { mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) require.NoError(t, err, "AcquireLock() Unexpected error while creating sqlmock", err) + defer func() { _ = mockDB.Close() }() if tt.closeConn { @@ -92,6 +93,7 @@ func TestDB_Acquire(t *testing.T) { } locker := New(mockDB) + require.NoError(t, err, "failed to create db conn") if tt.setupMocks != nil { @@ -99,6 +101,7 @@ func TestDB_Acquire(t *testing.T) { } release, err := locker.Acquire(testutil.Context(), "key", 2*time.Second) + var releaseErr error if release != nil { @@ -144,7 +147,7 @@ func Test_keepConnectionAlive(t *testing.T) { name: "error while executing keep alive query", setupMocks: func(mock sqlmock.Sqlmock) { mock.ExpectQuery(keepAliveSQLQuery). - WillReturnError(fmt.Errorf("can't execute keep alive query at this time")) + WillReturnError(errors.New("can't execute keep alive query at this time")) }, ctxFunc: func() (context.Context, context.CancelFunc) { return context.WithTimeout(context.Background(), intervalFullTime) diff --git a/pkg/periodic/periodic.go b/pkg/periodic/periodic.go index dfbb6e83..94cac8ea 100644 --- a/pkg/periodic/periodic.go +++ b/pkg/periodic/periodic.go @@ -3,7 +3,7 @@ package periodic import ( "context" - "fmt" + "errors" "math/rand" "time" ) @@ -28,20 +28,20 @@ type Periodic struct { func New(interval time.Duration, jitter time.Duration, timeout time.Duration, task TaskFn) (*Periodic, error) { intervalNs := int64(interval) if intervalNs < 1 { - return nil, fmt.Errorf("interval must be positive") + return nil, errors.New("interval must be positive") } jitterNs := int64(jitter) if jitterNs < 0 { - return nil, fmt.Errorf("jitter must be positive") + return nil, errors.New("jitter must be positive") } if int64(timeout) < 1 { - return nil, fmt.Errorf("timeout must be positive") + return nil, errors.New("timeout must be positive") } if task == nil { - return nil, fmt.Errorf("nil task") + return nil, errors.New("nil task") } return &Periodic{ diff --git a/pkg/periodic/periodic_test.go b/pkg/periodic/periodic_test.go index 6165a53c..7fe5b6a7 100644 --- a/pkg/periodic/periodic_test.go +++ b/pkg/periodic/periodic_test.go @@ -81,12 +81,16 @@ func TestNew(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + p, err := New(tt.interval, tt.jitter, tt.timeout, tt.task) + if tt.wantErr { require.Nil(t, p) require.Error(t, err) + return } + require.NotNil(t, p) require.NoError(t, err) }) diff --git a/pkg/retrier/example_retrier_test.go b/pkg/retrier/example_retrier_test.go index 6d5359b3..55038517 100644 --- a/pkg/retrier/example_retrier_test.go +++ b/pkg/retrier/example_retrier_test.go @@ -2,6 +2,7 @@ package retrier_test import ( "context" + "errors" "fmt" "log" "time" @@ -20,7 +21,7 @@ func ExampleRetrier_Run() { count++ - return fmt.Errorf("ERROR") + return errors.New("ERROR") } opts := []retrier.Option{ diff --git a/pkg/retrier/options.go b/pkg/retrier/options.go index 5475466d..acaba95f 100644 --- a/pkg/retrier/options.go +++ b/pkg/retrier/options.go @@ -1,7 +1,7 @@ package retrier import ( - "fmt" + "errors" "time" ) @@ -12,7 +12,7 @@ type Option func(c *Retrier) error func WithRetryIfFn(retryIfFn RetryIfFn) Option { return func(r *Retrier) error { if retryIfFn == nil { - return fmt.Errorf("the retry function is required") + return errors.New("the retry function is required") } r.retryIfFn = retryIfFn @@ -25,7 +25,7 @@ func WithRetryIfFn(retryIfFn RetryIfFn) Option { func WithAttempts(attempts uint) Option { return func(r *Retrier) error { if attempts < 1 { - return fmt.Errorf("the number of attempts must be at least 1") + return errors.New("the number of attempts must be at least 1") } r.attempts = attempts @@ -38,7 +38,7 @@ func WithAttempts(attempts uint) Option { func WithDelay(delay time.Duration) Option { return func(r *Retrier) error { if int64(delay) < 1 { - return fmt.Errorf("delay must be greater than zero") + return errors.New("delay must be greater than zero") } r.delay = delay @@ -53,7 +53,7 @@ func WithDelay(delay time.Duration) Option { func WithDelayFactor(delayFactor float64) Option { return func(r *Retrier) error { if delayFactor < 1 { - return fmt.Errorf("delay factor must be at least 1") + return errors.New("delay factor must be at least 1") } r.delayFactor = delayFactor @@ -67,7 +67,7 @@ func WithDelayFactor(delayFactor float64) Option { func WithJitter(jitter time.Duration) Option { return func(r *Retrier) error { if int64(jitter) < 1 { - return fmt.Errorf("jitter must be greater than zero") + return errors.New("jitter must be greater than zero") } r.jitter = jitter @@ -80,7 +80,7 @@ func WithJitter(jitter time.Duration) Option { func WithTimeout(timeout time.Duration) Option { return func(r *Retrier) error { if int64(timeout) < 1 { - return fmt.Errorf("timeout must be greater than zero") + return errors.New("timeout must be greater than zero") } r.timeout = timeout diff --git a/pkg/retrier/options_test.go b/pkg/retrier/options_test.go index e4a044a8..de3f0b03 100644 --- a/pkg/retrier/options_test.go +++ b/pkg/retrier/options_test.go @@ -12,7 +12,7 @@ func TestWithRetryIfFn(t *testing.T) { r := &Retrier{} - v := func(err error) bool { return true } + v := func(_ error) bool { return true } err := WithRetryIfFn(v)(r) require.NoError(t, err) diff --git a/pkg/retrier/retrier_test.go b/pkg/retrier/retrier_test.go index 90b35850..d9aee880 100644 --- a/pkg/retrier/retrier_test.go +++ b/pkg/retrier/retrier_test.go @@ -2,7 +2,7 @@ package retrier import ( "context" - "fmt" + "errors" "testing" "time" @@ -24,7 +24,7 @@ func TestNew(t *testing.T) { { name: "succeeds with custom values", opts: []Option{ - WithRetryIfFn(func(err error) bool { return true }), + WithRetryIfFn(func(_ error) bool { return true }), WithAttempts(5), WithDelay(601 * time.Millisecond), WithDelayFactor(1.3), @@ -44,12 +44,16 @@ func TestNew(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + r, err := New(tt.opts...) + if tt.wantErr { require.Nil(t, r) require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return } + require.NotNil(t, r, "New() returned value should not be nil") require.NoError(t, err) }) @@ -81,21 +85,21 @@ func TestRetrier_Run(t *testing.T) { return nil } count++ - return fmt.Errorf("ERROR") + return errors.New("ERROR") }, timeout: 1 * time.Second, wantRemainingAttempts: 1, }, { name: "fail all attempts", - task: func(_ context.Context) error { return fmt.Errorf("ERROR") }, + task: func(_ context.Context) error { return errors.New("ERROR") }, timeout: 1 * time.Second, wantRemainingAttempts: 0, wantErr: true, }, { name: "fail with main timeout", - task: func(ctx context.Context) error { <-ctx.Done(); return fmt.Errorf("ERROR") }, + task: func(ctx context.Context) error { <-ctx.Done(); return errors.New("ERROR") }, timeout: 1 * time.Millisecond, wantRemainingAttempts: 3, wantErr: true, @@ -140,7 +144,7 @@ func TestDefaultRetryIf(t *testing.T) { }{ { name: "true with error", - err: fmt.Errorf("ERROR"), + err: errors.New("ERROR"), want: true, }, { @@ -154,7 +158,9 @@ func TestDefaultRetryIf(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + got := DefaultRetryIf(tt.err) + require.Equal(t, tt.want, got) }) } @@ -169,5 +175,6 @@ func TestRetrier_setTimer(t *testing.T) { time.Sleep(2 * time.Millisecond) r.setTimer(2 * time.Millisecond) + <-r.timer.C } diff --git a/pkg/s3/client_test.go b/pkg/s3/client_test.go index 9cea0c09..eb2b2747 100644 --- a/pkg/s3/client_test.go +++ b/pkg/s3/client_test.go @@ -2,7 +2,7 @@ package s3 import ( "context" - "fmt" + "errors" "io" "strings" "testing" @@ -14,7 +14,6 @@ import ( "github.com/stretchr/testify/require" ) -//nolint:paralleltest func TestNew(t *testing.T) { o := awsopt.Options{} o.WithEndpoint("https://test.endpoint.invalid", true) @@ -74,7 +73,7 @@ func TestS3Client_DeleteObject(t *testing.T) { name: "success", key: "k1", bucket: "bucket", - mock: s3mock{delFn: func(ctx context.Context, params *s3.DeleteObjectInput, optFns ...func(*s3.Options)) (*s3.DeleteObjectOutput, error) { + mock: s3mock{delFn: func(_ context.Context, _ *s3.DeleteObjectInput, _ ...func(*s3.Options)) (*s3.DeleteObjectOutput, error) { return &s3.DeleteObjectOutput{}, nil }}, wantErr: false, @@ -83,8 +82,8 @@ func TestS3Client_DeleteObject(t *testing.T) { name: "error", key: "k1", bucket: "bucket", - mock: s3mock{delFn: func(ctx context.Context, params *s3.DeleteObjectInput, optFns ...func(*s3.Options)) (*s3.DeleteObjectOutput, error) { - return nil, fmt.Errorf("some err") + mock: s3mock{delFn: func(_ context.Context, _ *s3.DeleteObjectInput, _ ...func(*s3.Options)) (*s3.DeleteObjectOutput, error) { + return nil, errors.New("some err") }}, wantErr: true, }, @@ -128,7 +127,7 @@ func TestS3Client_GetObject(t *testing.T) { name: "success", key: "k1", bucket: "bucket", - mock: s3mock{getFn: func(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error) { + mock: s3mock{getFn: func(_ context.Context, _ *s3.GetObjectInput, _ ...func(*s3.Options)) (*s3.GetObjectOutput, error) { return &s3.GetObjectOutput{ Body: io.NopCloser(strings.NewReader("test str")), }, nil @@ -145,8 +144,8 @@ func TestS3Client_GetObject(t *testing.T) { name: "error", key: "k1", bucket: "bucket", - mock: s3mock{getFn: func(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error) { - return nil, fmt.Errorf("some err") + mock: s3mock{getFn: func(_ context.Context, _ *s3.GetObjectInput, _ ...func(*s3.Options)) (*s3.GetObjectOutput, error) { + return nil, errors.New("some err") }}, want: nil, wantErr: true, @@ -200,7 +199,7 @@ func TestS3Client_ListObject(t *testing.T) { name: "success - all", prefix: "", bucket: "bucket", - mock: s3mock{listFn: func(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error) { + mock: s3mock{listFn: func(_ context.Context, _ *s3.ListObjectsV2Input, _ ...func(*s3.Options)) (*s3.ListObjectsV2Output, error) { return &s3.ListObjectsV2Output{ Contents: []types.Object{ {Key: aws.String("key1")}, @@ -215,7 +214,7 @@ func TestS3Client_ListObject(t *testing.T) { name: "success - prefix", prefix: "ke", bucket: "bucket", - mock: s3mock{listFn: func(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error) { + mock: s3mock{listFn: func(_ context.Context, _ *s3.ListObjectsV2Input, _ ...func(*s3.Options)) (*s3.ListObjectsV2Output, error) { return &s3.ListObjectsV2Output{ Contents: []types.Object{ {Key: aws.String("key1")}, @@ -229,8 +228,8 @@ func TestS3Client_ListObject(t *testing.T) { name: "error", prefix: "k1", bucket: "bucket", - mock: s3mock{listFn: func(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error) { - return nil, fmt.Errorf("some err") + mock: s3mock{listFn: func(_ context.Context, _ *s3.ListObjectsV2Input, _ ...func(*s3.Options)) (*s3.ListObjectsV2Output, error) { + return nil, errors.New("some err") }}, want: nil, wantErr: true, @@ -276,7 +275,7 @@ func TestS3Client_PutObject(t *testing.T) { name: "success", key: "k1", bucket: "bucket", - mock: s3mock{putFn: func(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error) { + mock: s3mock{putFn: func(_ context.Context, _ *s3.PutObjectInput, _ ...func(*s3.Options)) (*s3.PutObjectOutput, error) { return &s3.PutObjectOutput{}, nil }}, wantErr: false, @@ -285,8 +284,8 @@ func TestS3Client_PutObject(t *testing.T) { name: "error", key: "k1", bucket: "bucket", - mock: s3mock{putFn: func(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error) { - return nil, fmt.Errorf("some err") + mock: s3mock{putFn: func(_ context.Context, _ *s3.PutObjectInput, _ ...func(*s3.Options)) (*s3.PutObjectOutput, error) { + return nil, errors.New("some err") }}, wantErr: true, }, diff --git a/pkg/s3/config_test.go b/pkg/s3/config_test.go index c303c239..3a56ee69 100644 --- a/pkg/s3/config_test.go +++ b/pkg/s3/config_test.go @@ -8,7 +8,6 @@ import ( "github.com/stretchr/testify/require" ) -//nolint:paralleltest func Test_loadConfig(t *testing.T) { region := "eu-central-1" diff --git a/pkg/slack/client_test.go b/pkg/slack/client_test.go index 8dd2128b..392be12c 100644 --- a/pkg/slack/client_test.go +++ b/pkg/slack/client_test.go @@ -61,6 +61,7 @@ func TestNew(t *testing.T) { if tt.wantErr { require.Nil(t, c, "New() returned client should be nil") require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return } @@ -204,7 +205,7 @@ func TestClient_Send(t *testing.T) { }{ { name: "fails because status not OK", - webhookHandler: func(w http.ResponseWriter, r *http.Request) { + webhookHandler: func(w http.ResponseWriter, _ *http.Request) { httputil.SendStatus(testutil.Context(), w, http.StatusInternalServerError) }, text: "text 1", @@ -216,7 +217,7 @@ func TestClient_Send(t *testing.T) { }, { name: "fails because of timeout", - webhookHandler: func(w http.ResponseWriter, r *http.Request) { + webhookHandler: func(w http.ResponseWriter, _ *http.Request) { time.Sleep(timeout + 1) httputil.SendStatus(testutil.Context(), w, http.StatusOK) }, @@ -229,7 +230,7 @@ func TestClient_Send(t *testing.T) { }, { name: "fails because bad address", - webhookHandler: func(w http.ResponseWriter, r *http.Request) { + webhookHandler: func(w http.ResponseWriter, _ *http.Request) { httputil.SendStatus(testutil.Context(), w, http.StatusOK) }, text: "text address", @@ -238,7 +239,7 @@ func TestClient_Send(t *testing.T) { }, { name: "fails because WriteHTTPRetrier error", - webhookHandler: func(w http.ResponseWriter, r *http.Request) { + webhookHandler: func(w http.ResponseWriter, _ *http.Request) { httputil.SendStatus(testutil.Context(), w, http.StatusOK) }, text: "text retrier", @@ -247,7 +248,7 @@ func TestClient_Send(t *testing.T) { }, { name: "succeed with valid response", - webhookHandler: func(w http.ResponseWriter, r *http.Request) { + webhookHandler: func(w http.ResponseWriter, _ *http.Request) { httputil.SendStatus(testutil.Context(), w, http.StatusOK) }, text: "text OK", diff --git a/pkg/sleuth/client.go b/pkg/sleuth/client.go index 640822aa..7799995b 100644 --- a/pkg/sleuth/client.go +++ b/pkg/sleuth/client.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -57,11 +58,11 @@ func New(addr, org, apiKey string, opts ...Option) (*Client, error) { } if org == "" { - return nil, fmt.Errorf("org is empty") + return nil, errors.New("org is empty") } if apiKey == "" { - return nil, fmt.Errorf("apiKey is empty") + return nil, errors.New("apiKey is empty") } valid, _ := validator.New( diff --git a/pkg/sleuth/client_test.go b/pkg/sleuth/client_test.go index 61a0a2e5..2af6cbb3 100644 --- a/pkg/sleuth/client_test.go +++ b/pkg/sleuth/client_test.go @@ -80,6 +80,7 @@ func TestNew(t *testing.T) { if tt.wantErr { require.Nil(t, c, "New() returned client should be nil") require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return } diff --git a/pkg/sleuth/sleuth_test.go b/pkg/sleuth/sleuth_test.go index 1f5b95ae..602b7bb7 100644 --- a/pkg/sleuth/sleuth_test.go +++ b/pkg/sleuth/sleuth_test.go @@ -3,7 +3,7 @@ package sleuth import ( "context" - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -19,12 +19,12 @@ import ( //go:noinline func newRequestWithContextPatch(_ context.Context, _, _ string, _ io.Reader) (*http.Request, error) { - return nil, fmt.Errorf("ERROR: newRequestWithContextPatch") + return nil, errors.New("ERROR: newRequestWithContextPatch") } //go:noinline func newHTTPRetrierPatch(httpretrier.HTTPClient, ...httpretrier.Option) (*httpretrier.HTTPRetrier, error) { - return nil, fmt.Errorf("ERROR: newHTTPRetrierPatch") + return nil, errors.New("ERROR: newHTTPRetrierPatch") } //nolint:gocognit,paralleltest @@ -40,7 +40,7 @@ func Test_sendRequest(t *testing.T) { { name: "failed to execute request - transport error", setupMocks: func(m *MockHTTPClient) { - m.EXPECT().Do(gomock.Any()).Return(nil, fmt.Errorf("transport error")).Times(1) + m.EXPECT().Do(gomock.Any()).Return(nil, errors.New("transport error")).Times(1) }, wantErr: true, }, @@ -52,6 +52,7 @@ func Test_sendRequest(t *testing.T) { return nil, err //nolint:wrapcheck } _ = patch.Patch() + return patch, nil }, wantErr: true, @@ -64,6 +65,7 @@ func Test_sendRequest(t *testing.T) { return nil, err //nolint:wrapcheck } _ = patch.Patch() + return patch, nil }, wantErr: true, @@ -72,6 +74,7 @@ func Test_sendRequest(t *testing.T) { name: "unexpected http error status code", createMockHandler: func(t *testing.T) http.HandlerFunc { t.Helper() + return func(w http.ResponseWriter, r *http.Request) { httputil.SendStatus(r.Context(), w, http.StatusInternalServerError) } @@ -82,6 +85,7 @@ func Test_sendRequest(t *testing.T) { name: "invalid response status < 200", createMockHandler: func(t *testing.T) http.HandlerFunc { t.Helper() + return func(w http.ResponseWriter, r *http.Request) { httputil.SendText(r.Context(), w, http.StatusSwitchingProtocols, "") } @@ -99,6 +103,7 @@ func Test_sendRequest(t *testing.T) { name: "success valid response", createMockHandler: func(t *testing.T) http.HandlerFunc { t.Helper() + return func(w http.ResponseWriter, r *http.Request) { httputil.SendText(r.Context(), w, http.StatusOK, "Success") } @@ -125,6 +130,7 @@ func Test_sendRequest(t *testing.T) { defer ts.Close() clientOpts := []Option{} + if tt.setupMocks != nil { mc := NewMockHTTPClient(ctrl) tt.setupMocks(mc) @@ -142,6 +148,7 @@ func Test_sendRequest(t *testing.T) { if tt.setupPatches != nil { patch, err := tt.setupPatches() require.NoError(t, err) + defer func() { _ = patch.Unpatch() }() diff --git a/pkg/sliceutil/stats.go b/pkg/sliceutil/stats.go index 0db4fc80..265c8002 100644 --- a/pkg/sliceutil/stats.go +++ b/pkg/sliceutil/stats.go @@ -1,7 +1,7 @@ package sliceutil import ( - "fmt" + "errors" "math" "slices" @@ -73,7 +73,7 @@ type DescStats[V typeutil.Number] struct { func Stats[S ~[]V, V typeutil.Number](s S) (*DescStats[V], error) { n := len(s) if n < 1 { - return nil, fmt.Errorf("input slice is empty") + return nil, errors.New("input slice is empty") } ds := &DescStats[V]{ @@ -127,6 +127,7 @@ func statsCenter[S ~[]V, V typeutil.Number](ds *DescStats[V], s, ord S, n int, n ds.Mode = ord[i] ds.ModeFreq = freq } + freq = 1 } } diff --git a/pkg/sqlconn/config.go b/pkg/sqlconn/config.go index 11bd13d1..a357bab8 100644 --- a/pkg/sqlconn/config.go +++ b/pkg/sqlconn/config.go @@ -2,7 +2,7 @@ package sqlconn import ( "database/sql" - "fmt" + "errors" "strings" "sync" "time" @@ -51,51 +51,51 @@ func defaultConfig(driver, dsn string) *config { //nolint:gocyclo,cyclop,gocognit func (c *config) validate() error { if strings.TrimSpace(c.driver) == "" { - return fmt.Errorf("database driver must be set") + return errors.New("database driver must be set") } if strings.TrimSpace(c.dsn) == "" { - return fmt.Errorf("database DSN must be set") + return errors.New("database DSN must be set") } if c.connectFunc == nil { - return fmt.Errorf("database connect function must be set") + return errors.New("database connect function must be set") } if c.checkConnectionFunc == nil { - return fmt.Errorf("check connection function must be set") + return errors.New("check connection function must be set") } if c.sqlOpenFunc == nil { - return fmt.Errorf("sql open function must be set") + return errors.New("sql open function must be set") } if c.connMaxIdleCount < 1 { - return fmt.Errorf("database pool max idle connections must be greater than 0") + return errors.New("database pool max idle connections must be greater than 0") } if c.connMaxIdleTime < 1*time.Second { - return fmt.Errorf("database connect retry interval must be at least 1 second") + return errors.New("database connect retry interval must be at least 1 second") } if c.connMaxLifetime < 1*time.Second { - return fmt.Errorf("database connection max lifetime must be at least 1 second") + return errors.New("database connection max lifetime must be at least 1 second") } if c.connMaxOpenCount < 1 { - return fmt.Errorf("database pool max open connections must be greater than 0") + return errors.New("database pool max open connections must be greater than 0") } if c.pingTimeout < 1*time.Second { - return fmt.Errorf("database ping timeout must be at least 1 second") + return errors.New("database ping timeout must be at least 1 second") } if c.shutdownWaitGroup == nil { - return fmt.Errorf("shutdownWaitGroup is required") + return errors.New("shutdownWaitGroup is required") } if c.shutdownSignalChan == nil { - return fmt.Errorf("shutdownSignalChan is required") + return errors.New("shutdownSignalChan is required") } return nil diff --git a/pkg/sqlconn/options_test.go b/pkg/sqlconn/options_test.go index 1e67a269..0f96ea51 100644 --- a/pkg/sqlconn/options_test.go +++ b/pkg/sqlconn/options_test.go @@ -14,7 +14,7 @@ import ( func TestWithConnectFunc(t *testing.T) { t.Parallel() - v := func(ctx context.Context, cfg *config) (*sql.DB, error) { + v := func(_ context.Context, _ *config) (*sql.DB, error) { // mock function return nil, nil //nolint:nilnil } @@ -26,7 +26,7 @@ func TestWithConnectFunc(t *testing.T) { func TestWithCheckConnectionFunc(t *testing.T) { t.Parallel() - v := func(ctx context.Context, db *sql.DB) error { + v := func(_ context.Context, _ *sql.DB) error { // mock function return nil } @@ -38,7 +38,7 @@ func TestWithCheckConnectionFunc(t *testing.T) { func TestWithSQLOpenFunc(t *testing.T) { t.Parallel() - v := func(a, b string) (*sql.DB, error) { + v := func(_, _ string) (*sql.DB, error) { // mock function return nil, nil //nolint:nilnil } diff --git a/pkg/sqlconn/sqlconn.go b/pkg/sqlconn/sqlconn.go index 24d95643..57b77df6 100644 --- a/pkg/sqlconn/sqlconn.go +++ b/pkg/sqlconn/sqlconn.go @@ -4,6 +4,7 @@ package sqlconn import ( "context" "database/sql" + "errors" "fmt" "strings" "sync" @@ -95,7 +96,7 @@ func (c *SQLConn) HealthCheck(ctx context.Context) error { defer c.dbLock.RUnlock() if c.db == nil { - return fmt.Errorf("database not unavailable") + return errors.New("database not unavailable") } ctx, cancel := context.WithTimeout(ctx, c.cfg.pingTimeout) diff --git a/pkg/sqlconn/sqlconn_test.go b/pkg/sqlconn/sqlconn_test.go index 76149c48..dd86f3ef 100644 --- a/pkg/sqlconn/sqlconn_test.go +++ b/pkg/sqlconn/sqlconn_test.go @@ -3,7 +3,7 @@ package sqlconn import ( "context" "database/sql" - "fmt" + "errors" "sync" "testing" "time" @@ -14,7 +14,7 @@ import ( ) func newMockConnectFunc(db *sql.DB, err error) ConnectFunc { - return func(ctx context.Context, cfg *config) (*sql.DB, error) { + return func(_ context.Context, _ *config) (*sql.DB, error) { return db, err } } @@ -45,14 +45,14 @@ func TestConnect(t *testing.T) { { name: "fail to open DB connection", connectDSN: "testsql://user:pass@tcp(db.host.invalid:1234)/testdb", - connectErr: fmt.Errorf("db open error"), + connectErr: errors.New("db open error"), wantErr: true, }, { name: "success with close error", connectDSN: "testsql://user:pass@tcp(db.host.invalid:1234)/testdb", configMockFunc: func(mock sqlmock.Sqlmock) { - mock.ExpectClose().WillReturnError(fmt.Errorf("close error")) + mock.ExpectClose().WillReturnError(errors.New("close error")) }, wantConn: true, }, @@ -91,6 +91,7 @@ func TestConnect(t *testing.T) { shutdownSG := make(chan struct{}) ctx, cancel := context.WithCancel(testutil.Context()) + defer func() { if tt.shutdownSig { close(shutdownSG) @@ -168,8 +169,8 @@ func TestSQLConn_HealthCheck(t *testing.T) { { name: "fail with check connection error", configOpts: []Option{ - WithCheckConnectionFunc(func(ctx context.Context, db *sql.DB) error { - return fmt.Errorf("check error") + WithCheckConnectionFunc(func(_ context.Context, _ *sql.DB) error { + return errors.New("check error") }), }, wantErr: true, @@ -177,7 +178,7 @@ func TestSQLConn_HealthCheck(t *testing.T) { { name: "success", configOpts: []Option{ - WithCheckConnectionFunc(func(ctx context.Context, db *sql.DB) error { + WithCheckConnectionFunc(func(_ context.Context, _ *sql.DB) error { return nil }), }, @@ -233,7 +234,7 @@ func Test_checkConnection(t *testing.T) { { name: "fail with ping error", configMockFunc: func(m sqlmock.Sqlmock) { - m.ExpectPing().WillReturnError(fmt.Errorf("ping error")) + m.ExpectPing().WillReturnError(errors.New("ping error")) }, wantErr: true, }, @@ -241,7 +242,7 @@ func Test_checkConnection(t *testing.T) { name: "fail with exec error", configMockFunc: func(m sqlmock.Sqlmock) { m.ExpectPing() - m.ExpectQuery("SELECT 1").WillReturnError(fmt.Errorf("exec error")) + m.ExpectQuery("SELECT 1").WillReturnError(errors.New("exec error")) }, wantErr: true, }, @@ -291,9 +292,9 @@ func Test_connectWithBackoff(t *testing.T) { }{ { name: "fail with sql error", - setupConfig: func(c *config, db *sql.DB) { - c.sqlOpenFunc = func(driverName, dataSourceName string) (*sql.DB, error) { - return nil, fmt.Errorf("open error") + setupConfig: func(c *config, _ *sql.DB) { + c.sqlOpenFunc = func(_, _ string) (*sql.DB, error) { + return nil, errors.New("open error") } }, wantErr: true, @@ -301,11 +302,11 @@ func Test_connectWithBackoff(t *testing.T) { { name: "fail with connection check error", setupConfig: func(c *config, db *sql.DB) { - c.sqlOpenFunc = func(driverName, dataSourceName string) (*sql.DB, error) { + c.sqlOpenFunc = func(_, _ string) (*sql.DB, error) { return db, nil } - c.checkConnectionFunc = func(ctx context.Context, db *sql.DB) error { - return fmt.Errorf("check error") + c.checkConnectionFunc = func(_ context.Context, _ *sql.DB) error { + return errors.New("check error") } }, wantErr: true, @@ -313,10 +314,10 @@ func Test_connectWithBackoff(t *testing.T) { { name: "succeed", setupConfig: func(c *config, db *sql.DB) { - c.sqlOpenFunc = func(driverName, dataSourceName string) (*sql.DB, error) { + c.sqlOpenFunc = func(_, _ string) (*sql.DB, error) { return db, nil } - c.checkConnectionFunc = func(ctx context.Context, db *sql.DB) error { + c.checkConnectionFunc = func(_ context.Context, _ *sql.DB) error { return nil } }, @@ -348,6 +349,7 @@ func Test_connectWithBackoff(t *testing.T) { require.Equal(t, db, got, "connectWithBackoff() got = %v, want %v", got, db) return } + require.Nil(t, got, "connectWithBackoff() expected nil DB") }) } @@ -400,9 +402,11 @@ func Test_parseConnectionURL(t *testing.T) { t.Errorf("parseConnectionURL() error = %v, wantErr %v", err, tt.wantErr) return } + if gotDriver != tt.wantDriver { t.Errorf("parseConnectionURL() gotDriver = %v, want %v", gotDriver, tt.wantDriver) } + if gotDSN != tt.wantDSN { t.Errorf("parseConnectionURL() gotDSN = %v, want %v", gotDSN, tt.wantDSN) } diff --git a/pkg/sqltransaction/sqltransaction_test.go b/pkg/sqltransaction/sqltransaction_test.go index bb428b12..ac546fce 100644 --- a/pkg/sqltransaction/sqltransaction_test.go +++ b/pkg/sqltransaction/sqltransaction_test.go @@ -3,7 +3,7 @@ package sqltransaction import ( "context" "database/sql" - "fmt" + "errors" "testing" "github.com/DATA-DOG/go-sqlmock" @@ -26,7 +26,7 @@ func Test_Exec(t *testing.T) { mock.ExpectBegin() mock.ExpectCommit() }, - run: func(ctx context.Context, tx *sql.Tx) error { + run: func(_ context.Context, _ *sql.Tx) error { return nil }, wantErr: false, @@ -37,17 +37,17 @@ func Test_Exec(t *testing.T) { mock.ExpectBegin() mock.ExpectRollback() }, - run: func(ctx context.Context, tx *sql.Tx) error { - return fmt.Errorf("db error") + run: func(_ context.Context, _ *sql.Tx) error { + return errors.New("db error") }, wantErr: true, }, { name: "begin error", setupMocks: func(mock sqlmock.Sqlmock) { - mock.ExpectBegin().WillReturnError(fmt.Errorf("begin error")) + mock.ExpectBegin().WillReturnError(errors.New("begin error")) }, - run: func(ctx context.Context, tx *sql.Tx) error { + run: func(_ context.Context, _ *sql.Tx) error { return nil }, wantErr: true, @@ -56,9 +56,9 @@ func Test_Exec(t *testing.T) { name: "commit error", setupMocks: func(mock sqlmock.Sqlmock) { mock.ExpectBegin() - mock.ExpectCommit().WillReturnError(fmt.Errorf("commit error")) + mock.ExpectCommit().WillReturnError(errors.New("commit error")) }, - run: func(ctx context.Context, tx *sql.Tx) error { + run: func(_ context.Context, _ *sql.Tx) error { return nil }, wantErr: true, @@ -67,10 +67,10 @@ func Test_Exec(t *testing.T) { name: "rollback error", setupMocks: func(mock sqlmock.Sqlmock) { mock.ExpectBegin() - mock.ExpectRollback().WillReturnError(fmt.Errorf("rollback error")) + mock.ExpectRollback().WillReturnError(errors.New("rollback error")) }, - run: func(ctx context.Context, tx *sql.Tx) error { - return fmt.Errorf("db error") + run: func(_ context.Context, _ *sql.Tx) error { + return errors.New("db error") }, wantErr: true, }, @@ -83,6 +83,7 @@ func Test_Exec(t *testing.T) { mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) require.NoError(t, err) + defer func() { _ = mockDB.Close() }() if tt.setupMocks != nil { @@ -138,13 +139,14 @@ func Test_ExecWithOptions(t *testing.T) { mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) require.NoError(t, err) + defer func() { _ = mockDB.Close() }() mock.ExpectBegin() mock.ExpectCommit() db := &dbMock{DB: mockDB} - err = ExecWithOptions(testutil.Context(), db, func(ctx context.Context, tx *sql.Tx) error { return nil }, tt.options) + err = ExecWithOptions(testutil.Context(), db, func(_ context.Context, _ *sql.Tx) error { return nil }, tt.options) require.NoError(t, err) require.Equal(t, tt.options, db.givenOptions) }) diff --git a/pkg/sqlutil/sqlutil.go b/pkg/sqlutil/sqlutil.go index 3c084ed0..d6a0d70f 100644 --- a/pkg/sqlutil/sqlutil.go +++ b/pkg/sqlutil/sqlutil.go @@ -2,7 +2,7 @@ package sqlutil import ( - "fmt" + "errors" "strings" ) @@ -39,11 +39,11 @@ func defaultSQLUtil() *SQLUtil { func (c *SQLUtil) validate() error { if c.quoteIDFunc == nil { - return fmt.Errorf("the QuoteID function must be set") + return errors.New("the QuoteID function must be set") } if c.quoteValueFunc == nil { - return fmt.Errorf("the QuoteValue function must be set") + return errors.New("the QuoteValue function must be set") } return nil diff --git a/pkg/sqlxtransaction/sqlxtransaction_test.go b/pkg/sqlxtransaction/sqlxtransaction_test.go index c5f070ac..39646cd9 100644 --- a/pkg/sqlxtransaction/sqlxtransaction_test.go +++ b/pkg/sqlxtransaction/sqlxtransaction_test.go @@ -3,7 +3,7 @@ package sqlxtransaction import ( "context" "database/sql" - "fmt" + "errors" "testing" "github.com/DATA-DOG/go-sqlmock" @@ -27,7 +27,7 @@ func Test_Exec(t *testing.T) { mock.ExpectBegin() mock.ExpectCommit() }, - run: func(ctx context.Context, tx *sqlx.Tx) error { + run: func(_ context.Context, _ *sqlx.Tx) error { return nil }, wantErr: false, @@ -38,17 +38,17 @@ func Test_Exec(t *testing.T) { mock.ExpectBegin() mock.ExpectRollback() }, - run: func(ctx context.Context, tx *sqlx.Tx) error { - return fmt.Errorf("db error") + run: func(_ context.Context, _ *sqlx.Tx) error { + return errors.New("db error") }, wantErr: true, }, { name: "begin error", setupMocks: func(mock sqlmock.Sqlmock) { - mock.ExpectBegin().WillReturnError(fmt.Errorf("begin error")) + mock.ExpectBegin().WillReturnError(errors.New("begin error")) }, - run: func(ctx context.Context, tx *sqlx.Tx) error { + run: func(_ context.Context, _ *sqlx.Tx) error { return nil }, wantErr: true, @@ -57,9 +57,9 @@ func Test_Exec(t *testing.T) { name: "commit error", setupMocks: func(mock sqlmock.Sqlmock) { mock.ExpectBegin() - mock.ExpectCommit().WillReturnError(fmt.Errorf("commit error")) + mock.ExpectCommit().WillReturnError(errors.New("commit error")) }, - run: func(ctx context.Context, tx *sqlx.Tx) error { + run: func(_ context.Context, _ *sqlx.Tx) error { return nil }, wantErr: true, @@ -68,10 +68,10 @@ func Test_Exec(t *testing.T) { name: "rollback error", setupMocks: func(mock sqlmock.Sqlmock) { mock.ExpectBegin() - mock.ExpectRollback().WillReturnError(fmt.Errorf("rollback error")) + mock.ExpectRollback().WillReturnError(errors.New("rollback error")) }, - run: func(ctx context.Context, tx *sqlx.Tx) error { - return fmt.Errorf("db error") + run: func(_ context.Context, _ *sqlx.Tx) error { + return errors.New("db error") }, wantErr: true, }, @@ -83,7 +83,9 @@ func Test_Exec(t *testing.T) { t.Parallel() mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) + require.NoError(t, err) + defer func() { _ = mockDB.Close() }() db := sqlx.NewDb(mockDB, "sqlmock") @@ -141,13 +143,14 @@ func Test_ExecWithOptions(t *testing.T) { mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) require.NoError(t, err) + defer func() { _ = mockDB.Close() }() mock.ExpectBegin() mock.ExpectCommit() db := &dbMock{DB: sqlx.NewDb(mockDB, "sqlmock")} - err = ExecWithOptions(testutil.Context(), db, func(ctx context.Context, tx *sqlx.Tx) error { return nil }, tt.options) + err = ExecWithOptions(testutil.Context(), db, func(_ context.Context, _ *sqlx.Tx) error { return nil }, tt.options) require.NoError(t, err) require.Equal(t, tt.options, db.givenOptions) }) diff --git a/pkg/sqs/client.go b/pkg/sqs/client.go index ca0d58f9..be063cde 100644 --- a/pkg/sqs/client.go +++ b/pkg/sqs/client.go @@ -2,6 +2,7 @@ package sqs import ( "context" + "errors" "fmt" "regexp" "strings" @@ -64,7 +65,7 @@ func New(ctx context.Context, queueURL, msgGroupID string, opts ...Option) (*Cli if strings.HasSuffix(queueURL, fifoSuffix) { re := regexp.MustCompile(regexMessageGroupID) if !re.MatchString(msgGroupID) { - return nil, fmt.Errorf("a valid msgGroupID is required for FIFO queue") + return nil, errors.New("a valid msgGroupID is required for FIFO queue") } awsMsgGroupID = aws.String(msgGroupID) diff --git a/pkg/sqs/client_test.go b/pkg/sqs/client_test.go index 25c37822..cbe783f4 100644 --- a/pkg/sqs/client_test.go +++ b/pkg/sqs/client_test.go @@ -2,7 +2,7 @@ package sqs import ( "context" - "fmt" + "errors" "testing" "github.com/Vonage/gosrvlib/pkg/awsopt" @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/require" ) -//nolint:paralleltest func TestNew(t *testing.T) { var ( wt int32 = 13 @@ -123,15 +122,15 @@ func TestSend(t *testing.T) { }{ { name: "success", - mock: sqsmock{sendFn: func(ctx context.Context, params *sqs.SendMessageInput, optFns ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { + mock: sqsmock{sendFn: func(_ context.Context, _ *sqs.SendMessageInput, _ ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { return &sqs.SendMessageOutput{}, nil }}, wantErr: false, }, { name: "error", - mock: sqsmock{sendFn: func(ctx context.Context, params *sqs.SendMessageInput, optFns ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { - return nil, fmt.Errorf("some err") + mock: sqsmock{sendFn: func(_ context.Context, _ *sqs.SendMessageInput, _ ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { + return nil, errors.New("some err") }}, wantErr: true, }, @@ -172,7 +171,7 @@ func TestReceive(t *testing.T) { }{ { name: "success", - mock: sqsmock{receiveFn: func(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { + mock: sqsmock{receiveFn: func(_ context.Context, _ *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { return &sqs.ReceiveMessageOutput{ Messages: []types.Message{ { @@ -190,7 +189,7 @@ func TestReceive(t *testing.T) { }, { name: "empty", - mock: sqsmock{receiveFn: func(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { + mock: sqsmock{receiveFn: func(_ context.Context, _ *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { return &sqs.ReceiveMessageOutput{}, nil }}, want: nil, @@ -198,8 +197,8 @@ func TestReceive(t *testing.T) { }, { name: "error", - mock: sqsmock{receiveFn: func(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { - return nil, fmt.Errorf("some err") + mock: sqsmock{receiveFn: func(_ context.Context, _ *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { + return nil, errors.New("some err") }}, want: nil, wantErr: true, @@ -243,7 +242,7 @@ func TestDelete(t *testing.T) { { name: "success", receiptHandle: "123456", - mock: sqsmock{deleteFn: func(ctx context.Context, params *sqs.DeleteMessageInput, optFns ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) { + mock: sqsmock{deleteFn: func(_ context.Context, _ *sqs.DeleteMessageInput, _ ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) { return &sqs.DeleteMessageOutput{}, nil }}, wantErr: false, @@ -251,7 +250,7 @@ func TestDelete(t *testing.T) { { name: "empty", receiptHandle: "", - mock: sqsmock{deleteFn: func(ctx context.Context, params *sqs.DeleteMessageInput, optFns ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) { + mock: sqsmock{deleteFn: func(_ context.Context, _ *sqs.DeleteMessageInput, _ ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) { return &sqs.DeleteMessageOutput{}, nil }}, wantErr: false, @@ -259,8 +258,8 @@ func TestDelete(t *testing.T) { { name: "error", receiptHandle: "7890", - mock: sqsmock{deleteFn: func(ctx context.Context, params *sqs.DeleteMessageInput, optFns ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) { - return nil, fmt.Errorf("some err") + mock: sqsmock{deleteFn: func(_ context.Context, _ *sqs.DeleteMessageInput, _ ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) { + return nil, errors.New("some err") }}, wantErr: true, }, @@ -298,7 +297,7 @@ func TestSendData(t *testing.T) { require.NoError(t, err) require.NotNil(t, cli) - cli.sqs = sqsmock{sendFn: func(ctx context.Context, params *sqs.SendMessageInput, optFns ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { + cli.sqs = sqsmock{sendFn: func(_ context.Context, _ *sqs.SendMessageInput, _ ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { return &sqs.SendMessageOutput{}, nil }} @@ -331,7 +330,7 @@ func TestReceiveData(t *testing.T) { }{ { name: "success", - mock: sqsmock{receiveFn: func(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { + mock: sqsmock{receiveFn: func(_ context.Context, _ *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { return &sqs.ReceiveMessageOutput{ Messages: []types.Message{ { @@ -347,7 +346,7 @@ func TestReceiveData(t *testing.T) { }, { name: "empty", - mock: sqsmock{receiveFn: func(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { + mock: sqsmock{receiveFn: func(_ context.Context, _ *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { return &sqs.ReceiveMessageOutput{}, nil }}, want: "", @@ -355,15 +354,15 @@ func TestReceiveData(t *testing.T) { }, { name: "error", - mock: sqsmock{receiveFn: func(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { - return nil, fmt.Errorf("error") + mock: sqsmock{receiveFn: func(_ context.Context, _ *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { + return nil, errors.New("error") }}, want: "", wantErr: true, }, { name: "invalid message", - mock: sqsmock{receiveFn: func(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { + mock: sqsmock{receiveFn: func(_ context.Context, _ *sqs.ReceiveMessageInput, _ ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { return &sqs.ReceiveMessageOutput{ Messages: []types.Message{ { @@ -397,6 +396,7 @@ func TestReceiveData(t *testing.T) { if tt.wantErr { require.Error(t, err) require.Equal(t, tt.want, got) + return } @@ -420,7 +420,7 @@ func TestHealthCheck(t *testing.T) { }{ { name: "success", - mock: sqsmock{getQueueAttributesFn: func(ctx context.Context, params *sqs.GetQueueAttributesInput, optFns ...func(*sqs.Options)) (*sqs.GetQueueAttributesOutput, error) { + mock: sqsmock{getQueueAttributesFn: func(_ context.Context, _ *sqs.GetQueueAttributesInput, _ ...func(*sqs.Options)) (*sqs.GetQueueAttributesOutput, error) { return &sqs.GetQueueAttributesOutput{ Attributes: map[string]string{string(types.QueueAttributeNameLastModifiedTimestamp): "2022-01-02 03:04:05"}, }, nil @@ -429,15 +429,15 @@ func TestHealthCheck(t *testing.T) { }, { name: "no queue", - mock: sqsmock{getQueueAttributesFn: func(ctx context.Context, params *sqs.GetQueueAttributesInput, optFns ...func(*sqs.Options)) (*sqs.GetQueueAttributesOutput, error) { + mock: sqsmock{getQueueAttributesFn: func(_ context.Context, _ *sqs.GetQueueAttributesInput, _ ...func(*sqs.Options)) (*sqs.GetQueueAttributesOutput, error) { return &sqs.GetQueueAttributesOutput{}, nil }}, wantErr: true, }, { name: "error", - mock: sqsmock{getQueueAttributesFn: func(ctx context.Context, params *sqs.GetQueueAttributesInput, optFns ...func(*sqs.Options)) (*sqs.GetQueueAttributesOutput, error) { - return &sqs.GetQueueAttributesOutput{}, fmt.Errorf("error") + mock: sqsmock{getQueueAttributesFn: func(_ context.Context, _ *sqs.GetQueueAttributesInput, _ ...func(*sqs.Options)) (*sqs.GetQueueAttributesOutput, error) { + return &sqs.GetQueueAttributesOutput{}, errors.New("error") }}, wantErr: true, }, diff --git a/pkg/sqs/config.go b/pkg/sqs/config.go index 99b05649..7328eb3c 100644 --- a/pkg/sqs/config.go +++ b/pkg/sqs/config.go @@ -2,6 +2,7 @@ package sqs import ( "context" + "errors" "fmt" "github.com/Vonage/gosrvlib/pkg/awsopt" @@ -35,11 +36,11 @@ func loadConfig(ctx context.Context, opts ...Option) (*cfg, error) { } if c.waitTimeSeconds < 0 || c.waitTimeSeconds > 20 { - return nil, fmt.Errorf("waitTimeSeconds must be between 0 and 20 seconds") + return nil, errors.New("waitTimeSeconds must be between 0 and 20 seconds") } if c.visibilityTimeout < 0 || c.visibilityTimeout > 43200 { - return nil, fmt.Errorf("visibilityTimeout must be between 0 and 43200 seconds") + return nil, errors.New("visibilityTimeout must be between 0 and 43200 seconds") } awsConfig, err := c.awsOpts.LoadDefaultConfig(ctx) diff --git a/pkg/sqs/config_test.go b/pkg/sqs/config_test.go index 52b3c92e..49fc0d9d 100644 --- a/pkg/sqs/config_test.go +++ b/pkg/sqs/config_test.go @@ -8,7 +8,6 @@ import ( "github.com/stretchr/testify/require" ) -//nolint:paralleltest func Test_loadConfig(t *testing.T) { var ( wt int32 = 13 diff --git a/pkg/testutil/output.go b/pkg/testutil/output.go index e9daa5f8..fe22ce0c 100644 --- a/pkg/testutil/output.go +++ b/pkg/testutil/output.go @@ -41,8 +41,9 @@ func CaptureOutput(t *testing.T, fn func()) string { wg.Done() _, err := io.Copy(&buf, reader) - require.NoError(t, err, "Unexpected error (io.Copy)") - out <- buf.String() + if err == nil { + out <- buf.String() + } }() wg.Wait() diff --git a/pkg/typeutil/encode_test.go b/pkg/typeutil/encode_test.go index 821270ac..18debe1f 100644 --- a/pkg/typeutil/encode_test.go +++ b/pkg/typeutil/encode_test.go @@ -2,7 +2,7 @@ package typeutil import ( "bytes" - "fmt" + "errors" "io" "testing" @@ -12,7 +12,7 @@ import ( type mockWriter struct{} func (w *mockWriter) Write(_ []byte) (int, error) { - return 0, fmt.Errorf("write error") + return 0, errors.New("write error") } func Test_base64Encoder(t *testing.T) { @@ -51,7 +51,7 @@ func (w *mockWriteCloserCloseError) Write(_ []byte) (int, error) { } func (w *mockWriteCloserCloseError) Close() error { - return fmt.Errorf("close error") + return errors.New("close error") } func Test_gobEncode(t *testing.T) { diff --git a/pkg/typeutil/typeutil_test.go b/pkg/typeutil/typeutil_test.go index db7b9d47..382202fc 100644 --- a/pkg/typeutil/typeutil_test.go +++ b/pkg/typeutil/typeutil_test.go @@ -25,6 +25,7 @@ func TestIsNil(t *testing.T) { t.Run("nil chan", func(t *testing.T) { t.Parallel() + var nilChan chan int got := IsNil(nilChan) @@ -33,6 +34,7 @@ func TestIsNil(t *testing.T) { t.Run("nil func", func(t *testing.T) { t.Parallel() + var nilFunc func() got := IsNil(nilFunc) @@ -41,6 +43,7 @@ func TestIsNil(t *testing.T) { t.Run("nil interface", func(t *testing.T) { t.Parallel() + var nilInterface *any got := IsNil(nilInterface) @@ -49,6 +52,7 @@ func TestIsNil(t *testing.T) { t.Run("nil map", func(t *testing.T) { t.Parallel() + var nilMap map[int]int got := IsNil(nilMap) @@ -57,6 +61,7 @@ func TestIsNil(t *testing.T) { t.Run("nil slice", func(t *testing.T) { t.Parallel() + var nilSlice []int got := IsNil(nilSlice) @@ -65,6 +70,7 @@ func TestIsNil(t *testing.T) { t.Run("nil pointer", func(t *testing.T) { t.Parallel() + var nilPointer *int got := IsNil(nilPointer) @@ -93,6 +99,7 @@ func TestIsZero(t *testing.T) { t.Run("nil chan", func(t *testing.T) { t.Parallel() + var nilChan chan int got := IsZero(nilChan) @@ -101,6 +108,7 @@ func TestIsZero(t *testing.T) { t.Run("nil func", func(t *testing.T) { t.Parallel() + var nilFunc func() got := IsZero(nilFunc) @@ -109,6 +117,7 @@ func TestIsZero(t *testing.T) { t.Run("nil interface", func(t *testing.T) { t.Parallel() + var nilInterface *any got := IsZero(nilInterface) @@ -117,6 +126,7 @@ func TestIsZero(t *testing.T) { t.Run("nil map", func(t *testing.T) { t.Parallel() + var nilMap map[int]int got := IsZero(nilMap) @@ -125,6 +135,7 @@ func TestIsZero(t *testing.T) { t.Run("nil slice", func(t *testing.T) { t.Parallel() + var nilSlice []int got := IsZero(nilSlice) @@ -133,6 +144,7 @@ func TestIsZero(t *testing.T) { t.Run("nil pointer", func(t *testing.T) { t.Parallel() + var nilPointer *int got := IsZero(nilPointer) diff --git a/pkg/validator/custom_test.go b/pkg/validator/custom_test.go index 9af93a67..55e2e43f 100644 --- a/pkg/validator/custom_test.go +++ b/pkg/validator/custom_test.go @@ -165,10 +165,14 @@ func TestCustomTags(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + s := tt.fobj(getTestCustomTagData()) err := v.ValidateStruct(s) + require.Equal(t, tt.wantErr, err != nil, "error = %v, wantErr %v", err, tt.wantErr) + errs := multierr.Errors(err) + require.Len(t, errs, tt.wantErrCount, "errors: %+v", errs) }) } diff --git a/pkg/validator/options.go b/pkg/validator/options.go index 003b70f9..09b081ca 100644 --- a/pkg/validator/options.go +++ b/pkg/validator/options.go @@ -24,6 +24,7 @@ func WithFieldNameTag(tag string) Option { if name == "-" { return "" } + return name }) diff --git a/pkg/validator/options_test.go b/pkg/validator/options_test.go index 07eef184..7e392d99 100644 --- a/pkg/validator/options_test.go +++ b/pkg/validator/options_test.go @@ -31,8 +31,10 @@ func TestWithFieldNameTag(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + v := &Validator{v: vt.New()} err := WithFieldNameTag(tt.tag)(v) + require.NoError(t, err) }) } @@ -66,8 +68,10 @@ func TestWithCustomValidationTags(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + v := &Validator{v: vt.New()} err := WithCustomValidationTags(tt.arg)(v) + if tt.wantErr { require.Error(t, err, "error = %v, wantErr %v", err, tt.wantErr) } else { @@ -138,8 +142,10 @@ func TestWithErrorTemplates(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() + v := &Validator{v: vt.New()} err := WithErrorTemplates(tt.arg)(v) + if tt.wantErr { require.Error(t, err, "error = %v, wantErr %v", err, tt.wantErr) } else { diff --git a/pkg/validator/validator_test.go b/pkg/validator/validator_test.go index f79ce7dc..51e65008 100644 --- a/pkg/validator/validator_test.go +++ b/pkg/validator/validator_test.go @@ -72,6 +72,7 @@ func TestNew(t *testing.T) { if tt.wantErr { require.Nil(t, got, "New() returned Validator should be nil") require.Error(t, err, "New() error = %v, wantErr %v", err, tt.wantErr) + return }