From 5309e03891f007be4b10c293c92cbe80dbf08490 Mon Sep 17 00:00:00 2001 From: SystemGlitch Date: Mon, 19 Feb 2024 16:55:50 +0100 Subject: [PATCH] Add testifylint --- .golangci.yml | 2 + auth/authenticator_test.go | 19 ++-- auth/basic_test.go | 35 +++---- auth/jwt_controller_test.go | 53 ++++------ auth/jwt_test.go | 147 +++++++++------------------ component_test.go | 5 +- config/config_test.go | 57 ++++------- database/database_test.go | 31 +++--- database/factory_test.go | 13 +-- database/paginator_test.go | 17 ++-- database/timeout_test.go | 18 ++-- middleware/compress/compress_test.go | 7 +- middleware/parse/parse_test.go | 15 ++- middleware_test.go | 17 ++-- parameterizable_test.go | 14 +-- response_test.go | 69 +++++-------- router_test.go | 7 +- server_test.go | 145 +++++++++----------------- static_test.go | 13 +-- status_handler_test.go | 21 ++-- util/errors/error_test.go | 33 +++--- util/fsutil/fsutil_test.go | 46 ++++----- util/fsutil/osfs/osfs_test.go | 33 ++---- util/session/session_test.go | 61 ++++------- util/testutil/logger_test.go | 3 +- util/testutil/testutil_test.go | 55 +++++----- util/typeutil/typeutil_test.go | 31 +++--- util/typeutil/undefined_test.go | 18 ++-- util/walk/walk_test.go | 50 ++++----- websocket/websocket_test.go | 64 ++++-------- 30 files changed, 415 insertions(+), 684 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index bc37b4c3..93061b86 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -30,6 +30,7 @@ linters: - gosimple - ineffassign - staticcheck + - testifylint disable-all: false fast: false @@ -39,6 +40,7 @@ issues: max-same-issues: 0 exclude: - should have a package comment + - for error assertions use require exclude-rules: - path: _test\.go linters: diff --git a/auth/authenticator_test.go b/auth/authenticator_test.go index 2fb5a15b..5e278c86 100644 --- a/auth/authenticator_test.go +++ b/auth/authenticator_test.go @@ -7,6 +7,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" "gorm.io/gorm/utils/tests" @@ -96,7 +97,7 @@ func TestAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) request = server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().SetBasicAuth(user.Email, "incorrect password") @@ -106,10 +107,8 @@ func TestAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.invalid-credentials")}, body) }) @@ -127,7 +126,7 @@ func TestAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) request.Route = &goyave.Route{Meta: map[string]any{}} resp = server.TestMiddleware(authenticator, request, func(response *goyave.Response, request *goyave.Request) { @@ -135,7 +134,7 @@ func TestAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("MiddlewareUnauthorizer", func(t *testing.T) { @@ -152,10 +151,8 @@ func TestAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"custom error key": server.Lang.GetDefault().Get("auth.invalid-credentials")}, body) }) } diff --git a/auth/basic_test.go b/auth/basic_test.go index c26a788c..0ffde162 100644 --- a/auth/basic_test.go +++ b/auth/basic_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/util/testutil" @@ -26,7 +27,7 @@ func TestBasicAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("wrong_password", func(t *testing.T) { @@ -42,10 +43,8 @@ func TestBasicAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.invalid-credentials")}, body) }) @@ -63,7 +62,7 @@ func TestBasicAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("optional_wrong_password", func(t *testing.T) { @@ -79,10 +78,8 @@ func TestBasicAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.invalid-credentials")}, body) }) @@ -97,7 +94,7 @@ func TestBasicAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("error_no_table", func(t *testing.T) { @@ -133,7 +130,7 @@ func TestBasicAuthenticator(t *testing.T) { request.Route = &goyave.Route{Meta: map[string]any{MetaAuth: true}} err := authenticator.Authenticate(request, &TestUserPromoted{}) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, server.Lang.GetDefault().Get("auth.no-credentials-provided"), err.Error()) }) } @@ -153,7 +150,7 @@ func TestConfigBasicAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("wrong_password", func(t *testing.T) { @@ -170,10 +167,8 @@ func TestConfigBasicAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.invalid-credentials")}, body) }) @@ -190,10 +185,8 @@ func TestConfigBasicAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.no-credentials-provided")}, body) }) } diff --git a/auth/jwt_controller_test.go b/auth/jwt_controller_test.go index b12799b8..85641806 100644 --- a/auth/jwt_controller_test.go +++ b/auth/jwt_controller_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/slog" @@ -32,18 +33,14 @@ func TestJWTController(t *testing.T) { "password": "secret", } body, err := json.Marshal(data) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := httptest.NewRequest(http.MethodPost, "/login", bytes.NewReader(body)) request.Header.Set("Content-Type", "application/json") resp := server.TestRequest(request) assert.Equal(t, http.StatusOK, resp.StatusCode) respBody, err := testutil.ReadJSONBody[map[string]any](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.NotEmpty(t, respBody["token"]) }) @@ -61,18 +58,14 @@ func TestJWTController(t *testing.T) { "password": "wrong password", } body, err := json.Marshal(data) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := httptest.NewRequest(http.MethodPost, "/login", bytes.NewReader(body)) request.Header.Set("Content-Type", "application/json") resp := server.TestRequest(request) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) respBody, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.invalid-credentials")}, respBody) }) @@ -96,14 +89,12 @@ func TestJWTController(t *testing.T) { "password": "secret", } body, err := json.Marshal(data) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := httptest.NewRequest(http.MethodPost, "/login", bytes.NewReader(body)) request.Header.Set("Content-Type", "application/json") resp := server.TestRequest(request) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) assert.NotEmpty(t, buf.String()) }) @@ -127,14 +118,12 @@ func TestJWTController(t *testing.T) { "password": "secret", } body, err := json.Marshal(data) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := httptest.NewRequest(http.MethodPost, "/login", bytes.NewReader(body)) request.Header.Set("Content-Type", "application/json") resp := server.TestRequest(request) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) assert.NotEmpty(t, buf.String()) }) @@ -155,18 +144,14 @@ func TestJWTController(t *testing.T) { "pass": "secret", } body, err := json.Marshal(data) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := httptest.NewRequest(http.MethodPost, "/login", bytes.NewReader(body)) request.Header.Set("Content-Type", "application/json") resp := server.TestRequest(request) assert.Equal(t, http.StatusOK, resp.StatusCode) respBody, err := testutil.ReadJSONBody[map[string]any](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.NotEmpty(t, respBody["token"]) }) @@ -181,18 +166,14 @@ func TestJWTController(t *testing.T) { data := map[string]any{} body, err := json.Marshal(data) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := httptest.NewRequest(http.MethodPost, "/login", bytes.NewReader(body)) request.Header.Set("Content-Type", "application/json") resp := server.TestRequest(request) assert.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode) respBody, err := testutil.ReadJSONBody[map[string]*validation.ErrorResponse](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) if assert.Contains(t, respBody, "error") && assert.NotNil(t, respBody["error"]) { assert.Contains(t, respBody["error"].Body.Fields, "username") assert.Contains(t, respBody["error"].Body.Fields, "password") diff --git a/auth/jwt_test.go b/auth/jwt_test.go index ff2bdade..b048b0a2 100644 --- a/auth/jwt_test.go +++ b/auth/jwt_test.go @@ -7,6 +7,7 @@ import ( "github.com/golang-jwt/jwt" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/util/fsutil/osfs" @@ -31,18 +32,16 @@ func TestJWTService(t *testing.T) { expiry := time.Duration(20) * time.Second tokenString, err := service.GenerateToken("johndoe") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) parsedToken, err := jwt.Parse(tokenString, func(_ *jwt.Token) (any, error) { return []byte(server.Config().GetString("auth.jwt.secret")), nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, parsedToken.Valid) assert.Equal(t, jwt.SigningMethodHS256, parsedToken.Method) - assert.NoError(t, parsedToken.Claims.Valid()) + require.NoError(t, parsedToken.Claims.Valid()) claims, ok := parsedToken.Claims.(jwt.MapClaims) if assert.True(t, ok) { assert.Equal(t, "johndoe", claims["sub"]) @@ -65,18 +64,16 @@ func TestJWTService(t *testing.T) { "customClaim": "customValue", } tokenString, err := service.GenerateTokenWithClaims(srcClaims, jwt.SigningMethodHS256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) parsedToken, err := jwt.Parse(tokenString, func(_ *jwt.Token) (any, error) { return []byte(server.Config().GetString("auth.jwt.secret")), nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, parsedToken.Valid) assert.Equal(t, jwt.SigningMethodHS256, parsedToken.Method) - assert.NoError(t, parsedToken.Claims.Valid()) + require.NoError(t, parsedToken.Claims.Valid()) claims, ok := parsedToken.Claims.(jwt.MapClaims) if assert.True(t, ok) { assert.Equal(t, "johndoe", claims["sub"]) @@ -102,18 +99,16 @@ func TestJWTService(t *testing.T) { "customClaim": "customValue", } tokenString, err := service.GenerateTokenWithClaims(srcClaims, jwt.SigningMethodRS256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) parsedToken, err := jwt.Parse(tokenString, func(_ *jwt.Token) (any, error) { return service.GetKey("auth.jwt.rsa.public") }) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, parsedToken.Valid) assert.Equal(t, jwt.SigningMethodRS256, parsedToken.Method) - assert.NoError(t, parsedToken.Claims.Valid()) + require.NoError(t, parsedToken.Claims.Valid()) claims, ok := parsedToken.Claims.(jwt.MapClaims) if assert.True(t, ok) { assert.Equal(t, "johndoe", claims["sub"]) @@ -139,18 +134,16 @@ func TestJWTService(t *testing.T) { "customClaim": "customValue", } tokenString, err := service.GenerateTokenWithClaims(srcClaims, jwt.SigningMethodES256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) parsedToken, err := jwt.Parse(tokenString, func(_ *jwt.Token) (any, error) { return service.GetKey("auth.jwt.ecdsa.public") }) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, parsedToken.Valid) assert.Equal(t, jwt.SigningMethodES256, parsedToken.Method) - assert.NoError(t, parsedToken.Claims.Valid()) + require.NoError(t, parsedToken.Claims.Valid()) claims, ok := parsedToken.Claims.(jwt.MapClaims) if assert.True(t, ok) { assert.Equal(t, "johndoe", claims["sub"]) @@ -166,7 +159,7 @@ func TestJWTService(t *testing.T) { server.Config().Set("auth.jwt.expiry", 20) _, err := service.GenerateTokenWithClaims(nil, jwt.SigningMethodPS256) - assert.Error(t, err) + require.Error(t, err) }) } @@ -181,9 +174,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateToken(user.Email) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -196,7 +187,7 @@ func TestJWTAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("success_rsa", func(t *testing.T) { @@ -210,9 +201,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateTokenWithClaims(jwt.MapClaims{"sub": user.Email}, jwt.SigningMethodRS256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -225,7 +214,7 @@ func TestJWTAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("success_ecdsa", func(t *testing.T) { @@ -239,9 +228,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateTokenWithClaims(jwt.MapClaims{"sub": user.Email}, jwt.SigningMethodES256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -254,7 +241,7 @@ func TestJWTAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("invalid_token", func(t *testing.T) { @@ -272,10 +259,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.jwt-invalid")}, body) }) @@ -291,9 +276,7 @@ func TestJWTAuthenticator(t *testing.T) { "sub": user.Email, "nbf": time.Now().Add(time.Hour).Unix(), }, jwt.SigningMethodHS256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -305,10 +288,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.jwt-not-valid-yet")}, body) }) @@ -324,9 +305,7 @@ func TestJWTAuthenticator(t *testing.T) { "sub": user.Email, "exp": time.Now().Add(-time.Hour).Unix(), }, jwt.SigningMethodHS256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -338,10 +317,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.jwt-expired")}, body) }) @@ -354,9 +331,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateToken("notjohndoe@example.org") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -368,10 +343,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.invalid-credentials")}, body) }) @@ -388,9 +361,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateToken("johndoe@example.org") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) authenticator := Middleware[*TestUser](&JWTAuthenticator{}) authenticator.Init(server.Server) @@ -413,9 +384,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateTokenWithClaims(jwt.MapClaims{"sub": "johndoe@example.org"}, jwt.SigningMethodRS256) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -427,10 +396,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.jwt-invalid")}, body) }) @@ -442,9 +409,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateToken("johndoe@example.org") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -456,10 +421,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.jwt-invalid")}, body) }) @@ -471,9 +434,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateToken("johndoe@example.org") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -485,10 +446,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.jwt-invalid")}, body) }) @@ -500,9 +459,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateToken("johndoe@example.org") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -527,10 +484,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.no-credentials-provided")}, body) }) @@ -543,9 +498,7 @@ func TestJWTAuthenticator(t *testing.T) { service := NewJWTService(server.Config(), &osfs.FS{}) token, err := service.GenerateToken(user.Email) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) request := server.NewTestRequest(http.MethodGet, "/protected", nil) request.Request().Header.Set("Authorization", "Bearer "+token) @@ -557,7 +510,7 @@ func TestJWTAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) t.Run("optional_invalid_token", func(t *testing.T) { @@ -575,10 +528,8 @@ func TestJWTAuthenticator(t *testing.T) { }) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](resp.Body) - _ = resp.Body.Close() - if !assert.NoError(t, err) { - return - } + assert.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, map[string]string{"error": server.Lang.GetDefault().Get("auth.jwt-invalid")}, body) }) @@ -594,6 +545,6 @@ func TestJWTAuthenticator(t *testing.T) { response.Status(http.StatusOK) }) assert.Equal(t, http.StatusOK, resp.StatusCode) - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }) } diff --git a/component_test.go b/component_test.go index 0f86c6ab..b97f8491 100644 --- a/component_test.go +++ b/component_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5/config" _ "goyave.dev/goyave/v5/database/dialect/sqlite" @@ -15,9 +16,7 @@ func TestComponent(t *testing.T) { cfg.Set("database.name", "test_component.db") cfg.Set("database.options", "mode=memory") server, err := New(Options{Config: cfg}) - if err != nil { - panic(err) - } + require.NoError(t, err) defer func() { assert.NoError(t, server.CloseDB()) }() diff --git a/config/config_test.go b/config/config_test.go index 93fbfefb..97cd8679 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConfigError(t *testing.T) { @@ -44,9 +45,7 @@ func TestLoad(t *testing.T) { // Should use automatically generated path (based on GOYAVE_ENV) t.Setenv("GOYAVE_ENV", "test") cfg, err := Load() - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.NotNil(t, cfg) @@ -72,7 +71,7 @@ func TestLoad(t *testing.T) { t.Setenv("GOYAVE_ENV", "test_invalid") cfg, err := Load() assert.Nil(t, cfg) - assert.Error(t, err) + require.Error(t, err) }) t.Run("Load Default", func(t *testing.T) { @@ -84,14 +83,12 @@ func TestLoad(t *testing.T) { t.Setenv("GOYAVE_ENV", "nonexisting") cfg, err := Load() assert.Nil(t, cfg) - assert.Error(t, err) + require.Error(t, err) }) t.Run("LoadFrom", func(t *testing.T) { cfg, err := LoadFrom("../resources/custom_config.json") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.NotNil(t, cfg) @@ -115,9 +112,7 @@ func TestLoad(t *testing.T) { t.Run("LoadJSON", func(t *testing.T) { cfg, err := LoadJSON(`{"custom-entry": "value"}`) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.NotNil(t, cfg) @@ -142,27 +137,27 @@ func TestLoad(t *testing.T) { t.Run("LoadJSON Invalid", func(t *testing.T) { cfg, err := LoadJSON(`{"unclosed":`) assert.Nil(t, cfg) - assert.Error(t, err) + require.Error(t, err) }) t.Run("Load Override Entry With Category", func(t *testing.T) { cfg, err := LoadJSON(`{"app": {"name": {}}}`) assert.Nil(t, cfg) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "Config error: \n\t- cannot override entry \"name\" with a category", err.Error()) }) t.Run("Load Override Category With Entry", func(t *testing.T) { cfg, err := LoadJSON(`{"app": "value"}`) assert.Nil(t, cfg) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "Config error: \n\t- cannot override category \"app\" with an entry", err.Error()) }) t.Run("Validation", func(t *testing.T) { cfg, err := LoadJSON(`{"app": {"name": 123}}`) assert.Nil(t, cfg) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "Config error: \n\t- \"app.name\" type must be string", err.Error()) }) @@ -212,33 +207,31 @@ func TestLoad(t *testing.T) { }` cfg, err := loader.loadJSON(json) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", cfg.Get("envString")) assert.Equal(t, 123, cfg.Get("envInt")) - assert.Equal(t, 123.456, cfg.Get("envFloat")) + assert.InEpsilon(t, 123.456, cfg.Get("envFloat"), 0) assert.Equal(t, true, cfg.Get("envBool")) // Invalid int t.Setenv("TEST_ENV_INT", "hello") cfg, err = loader.loadJSON(json) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, cfg) t.Setenv("TEST_ENV_INT", "123") // Invalid float t.Setenv("TEST_ENV_FLOAT", "hello") cfg, err = loader.loadJSON(json) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, cfg) t.Setenv("TEST_ENV_FLOAT", "123.456") // Invalid bool t.Setenv("TEST_ENV_BOOL", "hello") cfg, err = loader.loadJSON(json) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, cfg) t.Setenv("TEST_ENV_BOOL", "TRUE") }) @@ -262,7 +255,7 @@ func TestLoad(t *testing.T) { }` cfg, err := loader.loadJSON(json) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, cfg) }) @@ -286,7 +279,7 @@ func TestLoad(t *testing.T) { }` cfg, err := loader.loadJSON(json) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, cfg) }) @@ -304,9 +297,7 @@ func TestLoad(t *testing.T) { } }` cfg, err := LoadJSON(json) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.NotNil(t, cfg) @@ -356,9 +347,7 @@ func TestLoad(t *testing.T) { // With partial existence cfg, err = LoadJSON(`{"app": {"subcategory": {"subentry": 456}}}`) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.NotNil(t, cfg) @@ -475,9 +464,7 @@ func TestConfig(t *testing.T) { }` cfg, err := loader.loadJSON(cfgJSON) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) t.Run("Get", func(t *testing.T) { v := cfg.Get("testCategory.int") @@ -517,7 +504,7 @@ func TestConfig(t *testing.T) { t.Run("GetBool", func(t *testing.T) { v := cfg.GetBool("testCategory.bool") - assert.Equal(t, true, v) + assert.True(t, v) assert.Panics(t, func() { cfg.GetBool("testCategory.string") @@ -526,7 +513,7 @@ func TestConfig(t *testing.T) { t.Run("GetFloat", func(t *testing.T) { v := cfg.GetFloat("testCategory.float") - assert.Equal(t, 123.456, v) + assert.InEpsilon(t, 123.456, v, 0) assert.Panics(t, func() { cfg.GetFloat("testCategory.string") diff --git a/database/database_test.go b/database/database_test.go index adea7e86..fc14fa5c 100644 --- a/database/database_test.go +++ b/database/database_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/utils/tests" @@ -65,10 +66,8 @@ func TestNewDatabase(t *testing.T) { slogger := slog.New(slog.NewHandler(true, &bytes.Buffer{})) db, err := New(cfg, func() *slog.Logger { return slogger }) - assert.NoError(t, err) - if !assert.NotNil(t, db) { - return - } + require.NoError(t, err) + require.NotNil(t, db) if assert.NotNil(t, db.Config.Logger) { // Logging is enabled when app.debug is true @@ -126,10 +125,8 @@ func TestNewDatabase(t *testing.T) { logger := slog.New(slog.NewHandler(false, &bytes.Buffer{})) db, err := New(cfg, func() *slog.Logger { return logger }) - assert.NoError(t, err) - if !assert.NotNil(t, db) { - return - } + require.NoError(t, err) + require.NotNil(t, db) if assert.NotNil(t, db.Config.Logger) { // Logging is disable when app.debug is false @@ -165,10 +162,8 @@ func TestNewDatabase(t *testing.T) { dialector := &DummyDialector{} db, err := NewFromDialector(cfg, nil, dialector) - assert.NoError(t, err) - if !assert.NotNil(t, db) { - return - } + require.NoError(t, err) + require.NotNil(t, db) dbConfig := db.Config // Can't check log level (gorm logger unexported) @@ -198,7 +193,7 @@ func TestNewDatabase(t *testing.T) { cfg.Set("database.connection", "none") db, err := New(cfg, nil) assert.Nil(t, db) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "Cannot create DB connection. Database is set to \"none\" in the config", err.Error()) }) @@ -207,7 +202,7 @@ func TestNewDatabase(t *testing.T) { cfg.Set("database.connection", "notadriver") db, err := New(cfg, nil) assert.Nil(t, db) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "DB Connection \"notadriver\" not supported, forgotten import?", err.Error()) }) @@ -219,14 +214,12 @@ func TestNewDatabase(t *testing.T) { cfg.Set("database.options", "mode=memory") db, err := New(cfg, nil) - assert.NoError(t, err) - if !assert.NotNil(t, db) { - return - } + require.NoError(t, err) + require.NotNil(t, db) dbNames := []string{} res := db.Table("pragma_database_list").Select("name").Find(&dbNames) - assert.NoError(t, res.Error) + require.NoError(t, res.Error) assert.Equal(t, []string{"main"}, dbNames) }) } diff --git a/database/factory_test.go b/database/factory_test.go index ed244baf..37f9dc80 100644 --- a/database/factory_test.go +++ b/database/factory_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "goyave.dev/goyave/v5/config" ) @@ -74,21 +75,15 @@ func TestFactory(t *testing.T) { cfg.Set("database.name", "factory_test.db") cfg.Set("database.options", "mode=memory") db, err := New(cfg, nil) - if !assert.NoError(t, err) { - return - } - if !assert.NoError(t, db.AutoMigrate(&TestUser{})) { - return - } + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&TestUser{})) factory := NewFactory(userGenerator) records := factory.Save(db, 3) results := []*TestUser{} res := db.Find(&results) - if !assert.NoError(t, res.Error) { - return - } + require.NoError(t, res.Error) assert.Equal(t, records, results) }) } diff --git a/database/paginator_test.go b/database/paginator_test.go index 45c172c1..231ec5df 100644 --- a/database/paginator_test.go +++ b/database/paginator_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" "goyave.dev/goyave/v5/config" @@ -71,7 +72,7 @@ func TestPaginator(t *testing.T) { assert.Equal(t, &articles, p.Records) err := p.UpdatePageInfo() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(11), p.Total) assert.Equal(t, int64(3), p.MaxPage) @@ -89,7 +90,7 @@ func TestPaginator(t *testing.T) { assert.Equal(t, &articles, p.Records) err := p.Find() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(11), p.Total) assert.Equal(t, int64(3), p.MaxPage) @@ -116,7 +117,7 @@ func TestPaginator(t *testing.T) { p := NewPaginator(db, 2, 5, &articles) err = p.Find() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(0), p.Total) assert.Equal(t, int64(1), p.MaxPage) @@ -132,7 +133,7 @@ func TestPaginator(t *testing.T) { p := NewPaginator(db, 2, 5, &articles) err := p.Find() // updatePageInfo is called because the page info is not called yet - assert.Error(t, err) + require.Error(t, err) assert.False(t, p.loadedPageInfo) }) @@ -145,7 +146,7 @@ func TestPaginator(t *testing.T) { p.loadedPageInfo = true // Let's assume the page info has already been loaded err := p.Find() - assert.Error(t, err) + require.Error(t, err) assert.False(t, p.loadedPageInfo) // Page info invalidated }) @@ -157,7 +158,7 @@ func TestPaginator(t *testing.T) { p := NewPaginator(db, 1, 5, &articles) err := p.Find() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), p.Total) assert.Equal(t, int64(1), p.MaxPage) @@ -183,7 +184,7 @@ func TestPaginator(t *testing.T) { assert.Equal(t, p, p.Raw(query, queryVars, countQuery, queryVars)) err := p.Find() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), p.Total) assert.Equal(t, int64(1), p.MaxPage) @@ -200,7 +201,7 @@ func TestPaginator(t *testing.T) { p = NewPaginator(db, 2, 5, &articles) p.Raw(query, queryVars, countQuery, queryVars) err = p.Find() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), p.Total) assert.Equal(t, int64(1), p.MaxPage) assert.True(t, p.loadedPageInfo) diff --git a/database/timeout_test.go b/database/timeout_test.go index 88894429..233dbfc9 100644 --- a/database/timeout_test.go +++ b/database/timeout_test.go @@ -9,6 +9,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" "goyave.dev/goyave/v5/config" @@ -84,9 +85,8 @@ func TestTimeoutPlugin(t *testing.T) { users := []*TestUser{} res := db.Select("*").Where("email IN (?)", args).Find(&users) - if assert.Error(t, res.Error) { - assert.Equal(t, "context deadline exceeded", res.Error.Error()) - } + require.Error(t, res.Error) + assert.Equal(t, "context deadline exceeded", res.Error.Error()) }) t.Run("re-use_statement", func(t *testing.T) { @@ -94,11 +94,9 @@ func TestTimeoutPlugin(t *testing.T) { users := []*TestUser{} db = db.Select("*").Where("email", "johndoe@example.org").Find(&users) - if !assert.NoError(t, db.Error) { - return - } + require.NoError(t, db.Error) db = db.Select("*").Where("email", "johndoe@example.org").Find(&users) - assert.NoError(t, db.Error) + require.NoError(t, db.Error) }) t.Run("dont_override_predefined_context", func(t *testing.T) { @@ -115,7 +113,7 @@ func TestTimeoutPlugin(t *testing.T) { // The context is replaced with a longer timeout so the query can be completed. res := db.WithContext(ctx).Select("*").Where("email IN (?)", args).Find(&users) - assert.NoError(t, res.Error) + require.NoError(t, res.Error) }) t.Run("disabled", func(t *testing.T) { @@ -142,7 +140,7 @@ func TestTimeoutPlugin(t *testing.T) { users := []*TestUser{} res := db.Select("*").Where("email IN (?)", args).Find(&users) - assert.NoError(t, res.Error) + require.NoError(t, res.Error) }) t.Run("transaction_many_queries", func(t *testing.T) { @@ -192,6 +190,6 @@ func TestTimeoutPlugin(t *testing.T) { } return nil }) - assert.NoError(t, err) + require.NoError(t, err) }) } diff --git a/middleware/compress/compress_test.go b/middleware/compress/compress_test.go index 8e860b99..a7674e39 100644 --- a/middleware/compress/compress_test.go +++ b/middleware/compress/compress_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/util/fsutil/osfs" @@ -63,7 +64,7 @@ func TestCompressMiddleware(t *testing.T) { assert.NoError(t, result.Body.Close()) assert.Equal(t, "hello world", string(body)) // Not compressed assert.NotEqual(t, "gzip", result.Header.Get("Content-Encoding")) - assert.Equal(t, result.Header.Get("Content-Length"), "1234") + assert.Equal(t, "1234", result.Header.Get("Content-Length")) assert.Equal(t, http.StatusOK, result.StatusCode) }) @@ -136,7 +137,7 @@ func TestCompressMiddleware(t *testing.T) { assert.NoError(t, result.Body.Close()) assert.Equal(t, "hello world", string(body)) // Not compressed assert.NotEqual(t, "gzip", result.Header.Get("Content-Encoding")) - assert.Equal(t, result.Header.Get("Content-Length"), "1234") + assert.Equal(t, "1234", result.Header.Get("Content-Length")) assert.Equal(t, http.StatusOK, result.StatusCode) }) @@ -210,6 +211,6 @@ func TestCompressWriter(t *testing.T) { assert.True(t, closeableWriter.preWritten) - assert.NoError(t, writer.Close()) + require.NoError(t, writer.Close()) assert.True(t, closeableWriter.closed) } diff --git a/middleware/parse/parse_test.go b/middleware/parse/parse_test.go index 2b00649e..67d0fd83 100644 --- a/middleware/parse/parse_test.go +++ b/middleware/parse/parse_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/util/fsutil" @@ -22,15 +23,15 @@ func TestParseMiddleware(t *testing.T) { t.Run("Max Upload Size", func(t *testing.T) { m := &Middleware{} m.Init(server.Server) - assert.Equal(t, 10.0, m.getMaxUploadSize()) // Default + assert.InEpsilon(t, 10.0, m.getMaxUploadSize(), 0) // Default m.MaxUploadSize = 2.3 - assert.Equal(t, 2.3, m.getMaxUploadSize()) + assert.InEpsilon(t, 2.3, m.getMaxUploadSize(), 0) m = &Middleware{ MaxUploadSize: 2.3, } m.Init(server.Server) - assert.Equal(t, 2.3, m.getMaxUploadSize()) + assert.InEpsilon(t, 2.3, m.getMaxUploadSize(), 0) }) t.Run("Parse Query", func(t *testing.T) { @@ -112,15 +113,13 @@ func TestParseMiddleware(t *testing.T) { t.Run("Multipart", func(t *testing.T) { body := &bytes.Buffer{} writer := multipart.NewWriter(body) - assert.NoError(t, testutil.WriteMultipartFile(writer, &osfs.FS{}, "../../resources/img/logo/goyave_16.png", "profile_picture", "goyave_16.png")) - assert.NoError(t, writer.WriteField("email", "johndoe@example.org")) + require.NoError(t, testutil.WriteMultipartFile(writer, &osfs.FS{}, "../../resources/img/logo/goyave_16.png", "profile_picture", "goyave_16.png")) + require.NoError(t, writer.WriteField("email", "johndoe@example.org")) request := testutil.NewTestRequest(http.MethodPost, "/parse", body) request.Header().Set("Content-Type", writer.FormDataContentType()) - if !assert.NoError(t, writer.Close()) { - return - } + require.NoError(t, writer.Close()) result := server.TestMiddleware(&Middleware{}, request, func(resp *goyave.Response, req *goyave.Request) { data, ok := req.Data.(map[string]any) diff --git a/middleware_test.go b/middleware_test.go index a271085c..420ae9aa 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -13,6 +13,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/cors" "goyave.dev/goyave/v5/slog" @@ -206,9 +207,7 @@ func TestRecoveryMiddleware(t *testing.T) { func TestLanguageMiddleware(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if err != nil { - panic(err) - } + require.NoError(t, err) middleware := &languageMiddleware{} middleware.Init(server) @@ -529,9 +528,7 @@ func TestValidateMiddleware(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) assert.Equal(t, c.expectPass, pass) if c.expectPass { assert.Equal(t, "OK", string(body)) @@ -668,17 +665,15 @@ func TestCORSMiddleware(t *testing.T) { response := NewResponse(nil, request, recorder) handler(response, request) - assert.NoError(t, (&Router{}).finalize(response, request)) + require.NoError(t, (&Router{}).finalize(response, request)) resp := recorder.Result() assert.Equal(t, c.expectedStatusCode, resp.StatusCode) assert.Equal(t, c.expectedHeaders, resp.Header) defer func() { - _ = resp.Body.Close() + assert.NoError(t, resp.Body.Close()) }() body, err := io.ReadAll(resp.Body) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, c.expectedBody, string(body)) }) } diff --git a/parameterizable_test.go b/parameterizable_test.go index 99bca031..f1b3eda5 100644 --- a/parameterizable_test.go +++ b/parameterizable_test.go @@ -65,39 +65,39 @@ func (suite *ParameterizableTestSuite) TestBraceIndices() { p := ¶meterizable{} str := "/product/{id:[0-9]+}" idxs, err := p.braceIndices(str) - suite.Nil(err) + suite.Require().NoError(err) suite.Equal([]int{9, 19}, idxs) str = "/product/{id}" idxs, err = p.braceIndices(str) - suite.Nil(err) + suite.Require().NoError(err) suite.Equal([]int{9, 12}, idxs) str = "/product/{id:[0-9]+}/{name}" // Multiple params idxs, err = p.braceIndices(str) - suite.Nil(err) + suite.Require().NoError(err) suite.Equal([]int{9, 19, 21, 26}, idxs) str = "/product/{id}/{name:[\\w]+}" idxs, err = p.braceIndices(str) - suite.Nil(err) + suite.Require().NoError(err) suite.Equal([]int{9, 12, 14, 25}, idxs) str = "/product/{}" // Empty param, expect error idxs, err = p.braceIndices(str) - suite.NotNil(err) + suite.Require().Error(err) suite.Equal("empty route parameter in \"/product/{}\"", err.Error()) suite.Nil(idxs) str = "/product/{id:{[0-9]+}" // Unbalanced idxs, err = p.braceIndices(str) - suite.NotNil(err) + suite.Require().Error(err) suite.Equal("unbalanced braces in \"/product/{id:{[0-9]+}\"", err.Error()) suite.Nil(idxs) str = "/product/{id:}[0-9]+}" // Unbalanced idxs, err = p.braceIndices(str) - suite.NotNil(err) + suite.Require().Error(err) suite.Equal("unbalanced braces in \"/product/{id:}[0-9]+}\"", err.Error()) suite.Nil(idxs) } diff --git a/response_test.go b/response_test.go index a85888c7..d356b0a2 100644 --- a/response_test.go +++ b/response_test.go @@ -4,7 +4,6 @@ import ( "bufio" "bytes" "encoding/json" - "errors" "fmt" "io" "net" @@ -15,6 +14,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gorm.io/gorm" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/slog" @@ -87,7 +87,7 @@ func TestResponse(t *testing.T) { // Header not written res := recorder.Result() - assert.NoError(t, res.Body.Close()) + require.NoError(t, res.Body.Close()) assert.Equal(t, http.StatusOK, res.StatusCode) }) @@ -96,7 +96,7 @@ func TestResponse(t *testing.T) { resp.WriteHeader(http.StatusNoContent) res := recorder.Result() - assert.NoError(t, res.Body.Close()) + require.NoError(t, res.Body.Close()) assert.Equal(t, http.StatusNoContent, resp.status) assert.True(t, resp.wroteHeader) assert.True(t, resp.IsHeaderWritten()) @@ -113,7 +113,7 @@ func TestResponse(t *testing.T) { resp.WriteHeader(http.StatusOK) res := recorder.Result() - assert.NoError(t, res.Body.Close()) + require.NoError(t, res.Body.Close()) assert.Equal(t, http.StatusOK, res.StatusCode) assert.Equal(t, "value", res.Header.Get("X-Test")) }) @@ -141,9 +141,7 @@ func TestResponse(t *testing.T) { body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) // utf-8 BOM + text content assert.Equal(t, append([]byte{0xef, 0xbb, 0xbf}, []byte("utf-8 with BOM content")...), body) @@ -168,9 +166,7 @@ func TestResponse(t *testing.T) { body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) // utf-8 BOM + text content assert.Equal(t, append([]byte{0xef, 0xbb, 0xbf}, []byte("utf-8 with BOM content")...), body) @@ -188,10 +184,8 @@ func TestResponse(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } assert.NoError(t, res.Body.Close()) + require.NoError(t, err) assert.Equal(t, http.StatusOK, res.StatusCode) assert.Equal(t, "application/json; charset=utf-8", res.Header.Get("Content-Type")) assert.Equal(t, "{\"hello\":\"world\"}\n", string(body)) @@ -210,10 +204,8 @@ func TestResponse(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } assert.NoError(t, res.Body.Close()) + require.NoError(t, err) assert.Equal(t, http.StatusOK, res.StatusCode) assert.Equal(t, "hello world", string(body)) }) @@ -226,11 +218,9 @@ func TestResponse(t *testing.T) { }) res := recorder.Result() - assert.NoError(t, res.Body.Close()) + require.NoError(t, res.Body.Close()) cookies := res.Cookies() - if !assert.Equal(t, 1, len(cookies)) { - return - } + require.Len(t, cookies, 1) assert.Equal(t, "cookie-name", cookies[0].Name) assert.Equal(t, "test", cookies[0].Value) }) @@ -241,10 +231,8 @@ func TestResponse(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } assert.NoError(t, res.Body.Close()) + require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.status) // Ensures PreWrite has been called assert.Equal(t, http.StatusOK, res.StatusCode) assert.Equal(t, "hello world", string(body)) @@ -258,10 +246,7 @@ func TestResponse(t *testing.T) { assert.False(t, resp.Hijacked()) c, b, err := resp.Hijack() - if !assert.NoError(t, err) { - return - } - assert.Nil(t, err) + require.NoError(t, err) assert.NotNil(t, c) assert.NotNil(t, b) assert.True(t, resp.hijacked) @@ -271,7 +256,7 @@ func TestResponse(t *testing.T) { resp, _ := newTestReponse() c, b, err := resp.Hijack() - assert.True(t, errors.Is(err, ErrNotHijackable)) + require.ErrorIs(t, err, ErrNotHijackable) assert.Nil(t, c) assert.Nil(t, b) }) @@ -284,20 +269,20 @@ func TestResponse(t *testing.T) { resp.responseWriter = &hijackableRecorder{recorder} _, _, err := resp.Hijack() - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) resp.Error(fmt.Errorf("test error")) res := recorder.Result() + defer func() { + assert.NoError(t, res.Body.Close()) + }() assert.Equal(t, http.StatusInternalServerError, resp.status) body, err := io.ReadAll(res.Body) - assert.Nil(t, err) + require.NoError(t, err) // The connection was hijacked so errors shouldn't be written to the response assert.Empty(t, body) - assert.NoError(t, res.Body.Close()) }) }) @@ -315,7 +300,7 @@ func TestResponse(t *testing.T) { resp.PreWrite([]byte{1, 2, 3}) assert.Equal(t, []byte{1, 2, 3}, newWriter.prewritten) - assert.NoError(t, resp.close()) + require.NoError(t, resp.close()) assert.True(t, newWriter.closed) }) @@ -409,10 +394,8 @@ func TestResponse(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } assert.NoError(t, res.Body.Close()) + require.NoError(t, err) assert.Equal(t, http.StatusInternalServerError, resp.status) assert.Equal(t, http.StatusInternalServerError, res.StatusCode) assert.Equal(t, "application/json; charset=utf-8", res.Header.Get("Content-Type")) @@ -440,10 +423,8 @@ func TestResponse(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } assert.NoError(t, res.Body.Close()) + require.NoError(t, err) assert.Equal(t, http.StatusForbidden, resp.status) assert.Equal(t, http.StatusForbidden, res.StatusCode) assert.Equal(t, "application/json; charset=utf-8", res.Header.Get("Content-Type")) @@ -475,10 +456,8 @@ func TestResponse(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } assert.NoError(t, res.Body.Close()) + require.NoError(t, err) assert.Equal(t, http.StatusForbidden, resp.status) assert.Equal(t, http.StatusForbidden, res.StatusCode) assert.Equal(t, "forbidden", string(body)) @@ -507,10 +486,8 @@ func TestResponse(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } assert.NoError(t, res.Body.Close()) + require.NoError(t, err) assert.Equal(t, http.StatusInternalServerError, resp.status) assert.Equal(t, http.StatusInternalServerError, res.StatusCode) assert.Equal(t, "application/json; charset=utf-8", res.Header.Get("Content-Type")) diff --git a/router_test.go b/router_test.go index ec6c3ff7..81ead3cc 100644 --- a/router_test.go +++ b/router_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/cors" "goyave.dev/goyave/v5/util/fsutil" @@ -280,7 +281,7 @@ func TestRouter(t *testing.T) { t.Run("Static", func(t *testing.T) { router := prepareRouterTest() f, err := fs.Sub(&osfs.FS{}, "resources") - assert.NoError(t, err) + require.NoError(t, err) route := router.Static(fsutil.NewEmbed(f.(fs.ReadDirFS)), "/uri", false) assert.Equal(t, []string{http.MethodGet, http.MethodHead}, route.methods) assert.Equal(t, []string{"resource"}, route.parameters) @@ -428,9 +429,7 @@ func TestRouter(t *testing.T) { body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, c.expectedBody, string(body)) }) } diff --git a/server_test.go b/server_test.go index f6fcfa8d..681c6829 100644 --- a/server_test.go +++ b/server_test.go @@ -20,6 +20,7 @@ import ( "embed" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm/utils/tests" "goyave.dev/goyave/v5/config" @@ -63,9 +64,7 @@ func TestServer(t *testing.T) { BaseContext: func(_ net.Listener) context.Context { return context.Background() }, ConnContext: func(ctx context.Context, _ net.Conn) context.Context { return ctx }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "test", s.Config().GetString("app.name")) assert.Nil(t, s.db) @@ -87,7 +86,7 @@ func TestServer(t *testing.T) { assert.NotNil(t, s.server.BaseContext) assert.Equal(t, "http://127.0.0.1:8080", s.BaseURL()) assert.Equal(t, "http://127.0.0.1:8080", s.ProxyBaseURL()) - assert.Nil(t, s.CloseDB()) + assert.NoError(t, s.CloseDB()) }) t.Run("New_invalid_config", func(t *testing.T) { @@ -121,7 +120,7 @@ func TestServer(t *testing.T) { logger := slog.New(slog.NewHandler(false, &bytes.Buffer{})) langEmbed, err := fsutil.NewEmbed(resources).Sub("resources/lang") - assert.NoError(t, err) + require.NoError(t, err) opts := Options{ Config: cfg, Logger: logger, @@ -129,11 +128,9 @@ func TestServer(t *testing.T) { } server, err := New(opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer func() { - assert.NoError(t, server.CloseDB()) + require.NoError(t, server.CloseDB()) }() assert.Equal(t, "test_with_config", server.Config().GetString("app.name")) @@ -143,7 +140,7 @@ func TestServer(t *testing.T) { assert.Equal(t, "load UK", server.Lang.Get("en-UK", "test-load")) assert.NotNil(t, server.DB()) - assert.Nil(t, server.CloseDB()) + assert.NoError(t, server.CloseDB()) }) t.Run("NewWithConfig_db_error", func(t *testing.T) { @@ -151,9 +148,7 @@ func TestServer(t *testing.T) { cfg.Set("database.connection", "not_a_driver") server, err := New(Options{Config: cfg}) - if !assert.Error(t, err) { - return - } + require.Error(t, err) assert.Nil(t, server) }) @@ -213,9 +208,7 @@ func TestServer(t *testing.T) { cfg := config.LoadDefault() cfg.Set("app.name", "test") server, err := New(Options{Config: cfg}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) service := &DummyService{} server.RegisterService(service) @@ -238,9 +231,7 @@ func TestServer(t *testing.T) { t.Run("Accessors", func(t *testing.T) { cfg := config.LoadDefault() server, err := New(Options{Config: cfg}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "127.0.0.1:8080", server.Host()) assert.Equal(t, 8080, server.Port()) @@ -258,9 +249,7 @@ func TestServer(t *testing.T) { t.Run("RegisterRoutes", func(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) server.RegisterRoutes(func(_ *Server, router *Router) { router.Get("/", func(_ *Response, _ *Request) {}).Name("base") @@ -275,9 +264,7 @@ func TestServer(t *testing.T) { cfg.Set("database.name", "sqlite3_server_transaction_test.db") cfg.Set("database.options", "mode=memory") server, err := New(Options{Config: cfg}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer func() { assert.NoError(t, server.CloseDB()) }() @@ -300,11 +287,9 @@ func TestServer(t *testing.T) { t.Run("ReplaceDB", func(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - assert.Nil(t, server.ReplaceDB(tests.DummyDialector{})) + assert.NoError(t, server.ReplaceDB(tests.DummyDialector{})) assert.NotNil(t, server.db) }) @@ -312,9 +297,7 @@ func TestServer(t *testing.T) { cfg := config.LoadDefault() cfg.Set("server.port", 8888) server, err := New(Options{Config: cfg}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) startupHookExecuted := false shutdownHookExecuted := false @@ -328,14 +311,12 @@ func TestServer(t *testing.T) { assert.True(t, server.IsReady()) res, err := http.Get("http://localhost:8888") - if !assert.NoError(t, err) { - return - } + defer func() { + assert.NoError(t, res.Body.Close()) + }() + assert.NoError(t, err) respBody, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } - _ = res.Body.Close() + assert.NoError(t, err) assert.Equal(t, []byte("hello world"), respBody) // Stop the server, goroutine should return @@ -356,7 +337,7 @@ func TestServer(t *testing.T) { go func() { err := server.Start() - assert.Nil(t, err) + assert.NoError(t, err) wg.Done() }() @@ -371,9 +352,7 @@ func TestServer(t *testing.T) { cfg := config.LoadDefault() cfg.Set("server.port", 0) server, err := New(Options{Config: cfg}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) startupHookExecuted := false wg := sync.WaitGroup{} @@ -387,14 +366,12 @@ func TestServer(t *testing.T) { assert.NotEqual(t, 0, s.Port()) res, err := http.Get(s.BaseURL()) - if !assert.NoError(t, err) { - return - } + defer func() { + assert.NoError(t, res.Body.Close()) + }() + assert.NoError(t, err) respBody, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } - _ = res.Body.Close() + assert.NoError(t, err) assert.Equal(t, []byte("hello world"), respBody) // Stop the server, goroutine should return @@ -410,7 +387,7 @@ func TestServer(t *testing.T) { go func() { err := server.Start() - assert.Nil(t, err) + assert.NoError(t, err) wg.Done() }() @@ -422,9 +399,7 @@ func TestServer(t *testing.T) { t.Run("Start_already_running", func(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) atomic.StoreUint32(&server.state, 2) // Simulate the server already running err = server.Start() if assert.Error(t, err) { @@ -436,9 +411,7 @@ func TestServer(t *testing.T) { t.Run("Start_stopped", func(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) atomic.StoreUint32(&server.state, 3) // Simulate stopped server err = server.Start() if assert.Error(t, err) { @@ -450,54 +423,44 @@ func TestServer(t *testing.T) { t.Run("Stop_not_started", func(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) server.Stop() // Nothing happens }) t.Run("StartupHooks", func(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) server.RegisterStartupHook(func(_ *Server) {}) assert.Len(t, server.startupHooks, 1) server.ClearStartupHooks() - assert.Len(t, server.startupHooks, 0) + assert.Empty(t, server.startupHooks) }) t.Run("ShutdownHooks", func(t *testing.T) { server, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) server.RegisterShutdownHook(func(_ *Server) {}) assert.Len(t, server.shutdownHooks, 1) server.ClearShutdownHooks() - assert.Len(t, server.shutdownHooks, 0) + assert.Empty(t, server.shutdownHooks) }) t.Run("SignalHook", func(t *testing.T) { cfg := config.LoadDefault() cfg.Set("server.port", 8889) server, err := New(Options{Config: cfg}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) server.RegisterSignalHook() proc, err := os.FindProcess(os.Getpid()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) wg := sync.WaitGroup{} wg.Add(2) @@ -516,7 +479,7 @@ func TestServer(t *testing.T) { go func() { err := server.Start() - assert.Nil(t, err) + assert.NoError(t, err) wg.Done() }() @@ -539,9 +502,7 @@ func TestServer(t *testing.T) { return context.WithValue(ctx, connContextKey{}, "conn-ctx-value") }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) startupHookExecuted := true wg := sync.WaitGroup{} @@ -554,14 +515,12 @@ func TestServer(t *testing.T) { assert.True(t, server.IsReady()) res, err := http.Get(s.BaseURL()) - if !assert.NoError(t, err) { - return - } + defer func() { + assert.NoError(t, res.Body.Close()) + }() + assert.NoError(t, err) respBody, err := io.ReadAll(res.Body) - if !assert.NoError(t, err) { - return - } - _ = res.Body.Close() + assert.NoError(t, err) assert.Equal(t, []byte(fmt.Sprintf("%v|%v", "base-ctx-value", "conn-ctx-value")), respBody) // Stop the server, goroutine should return @@ -579,7 +538,7 @@ func TestServer(t *testing.T) { go func() { err := server.Start() - assert.Nil(t, err) + assert.NoError(t, err) wg.Done() }() @@ -598,9 +557,7 @@ func TestServer(t *testing.T) { return nil }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Panics(t, func() { _ = server.Start() @@ -618,9 +575,7 @@ func TestServer(t *testing.T) { return ctx }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) err = server.Start() if assert.Error(t, err) { @@ -636,9 +591,7 @@ func TestNoServerFromContext(t *testing.T) { func TestErrLogWriter(t *testing.T) { s, err := New(Options{Config: config.LoadDefault()}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) buf := bytes.NewBuffer(make([]byte, 0, 1024)) s.Logger = slog.New(slog.NewHandler(false, buf)) @@ -649,7 +602,7 @@ func TestErrLogWriter(t *testing.T) { message := "error message" n, err := w.Write([]byte(message)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, len(message), n) assert.Regexp(t, regexp.MustCompile( diff --git a/static_test.go b/static_test.go index 6455bade..b8ce6a64 100644 --- a/static_test.go +++ b/static_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/util/fsutil" "goyave.dev/goyave/v5/util/fsutil/osfs" @@ -39,7 +40,7 @@ func TestCleanStaticPath(t *testing.T) { c := c t.Run(c.want, func(t *testing.T) { f, err := fs.Sub(&osfs.FS{}, c.directory) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.want, cleanStaticPath(fsutil.NewEmbed(f.(fs.ReadDirFS)), c.file)) }) } @@ -91,9 +92,7 @@ func TestStaticHandler(t *testing.T) { cfg := config.LoadDefault() srv, err := New(Options{Config: cfg}) - if err != nil { - panic(err) - } + require.NoError(t, err) request := NewRequest(httptest.NewRequest(http.MethodGet, c.uri, nil)) request.RouteParams = map[string]string{"resource": c.uri} @@ -102,16 +101,14 @@ func TestStaticHandler(t *testing.T) { response := NewResponse(srv, request, recorder) f, err := fs.Sub(&osfs.FS{}, c.directory) - assert.NoError(t, err) + require.NoError(t, err) handler := staticHandler(fsutil.NewEmbed(f.(fs.ReadDirFS)), c.download) handler(response, request) result := recorder.Result() body, err := io.ReadAll(result.Body) assert.NoError(t, result.Body.Close()) - if err != nil { - panic(err) - } + require.NoError(t, err) c.expected(t, response, result, body) }) } diff --git a/status_handler_test.go b/status_handler_test.go index a2e4708e..1710d698 100644 --- a/status_handler_test.go +++ b/status_handler_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/slog" "goyave.dev/goyave/v5/util/errors" @@ -38,9 +39,7 @@ func TestPanicStatusHandler(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{\"error\":\"Internal Server Error\"}\n", string(body)) }) @@ -58,9 +57,7 @@ func TestPanicStatusHandler(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{\"error\":\"test error\"}\n", string(body)) @@ -81,9 +78,7 @@ func TestPanicStatusHandler(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{\"error\":null}\n", string(body)) @@ -105,9 +100,7 @@ func TestErrorStatusHandler(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{\"error\":\"Not Found\"}\n", string(body)) } @@ -134,9 +127,7 @@ func TestValidationStatusHandler(t *testing.T) { res := recorder.Result() body, err := io.ReadAll(res.Body) assert.NoError(t, res.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{\"error\":{\"body\":{\"fields\":{\"field\":{\"errors\":[\"The field is required\"]}},\"errors\":[\"The body is required\"]},\"query\":{\"fields\":{\"query\":{\"errors\":[\"The query is required\"]}}}}}\n", string(body)) } diff --git a/util/errors/error_test.go b/util/errors/error_test.go index 4f8315ad..c953650f 100644 --- a/util/errors/error_test.go +++ b/util/errors/error_test.go @@ -8,6 +8,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestErrors(t *testing.T) { @@ -66,8 +67,8 @@ func TestErrors(t *testing.T) { }) t.Run("New_nil", func(t *testing.T) { - assert.Nil(t, New(nil)) - assert.Nil(t, NewSkip(nil, 3)) + assert.NoError(t, New(nil)) + assert.NoError(t, NewSkip(nil, 3)) }) t.Run("NewSkip_already_Error", func(t *testing.T) { @@ -115,22 +116,22 @@ func TestErrors(t *testing.T) { err *Error desc string }{ - {desc: "empty_slice", err: emptySliceErr, expected: regexp.MustCompile("^goyave.dev/goyave/util/errors.Error: the Error doesn't wrap any reason \\(empty reasons slice\\)\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:108\n")}, - {desc: "nil_error_slice", err: New([]error{nil}).(*Error), expected: regexp.MustCompile("^goyave.dev/goyave/util/errors.Error: the Error doesn't wrap any reason \\(empty reasons slice\\)\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:119\n")}, - {desc: "nil_any_slice", err: New([]any{nil}).(*Error), expected: regexp.MustCompile("^goyave.dev/goyave/util/errors.Error: the Error doesn't wrap any reason \\(empty reasons slice\\)\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:120\n")}, - {desc: "single", err: New("err1").(*Error), expected: regexp.MustCompile("^err1\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:121\n")}, + {desc: "empty_slice", err: emptySliceErr, expected: regexp.MustCompile("^goyave.dev/goyave/util/errors.Error: the Error doesn't wrap any reason \\(empty reasons slice\\)\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:109\n")}, + {desc: "nil_error_slice", err: New([]error{nil}).(*Error), expected: regexp.MustCompile("^goyave.dev/goyave/util/errors.Error: the Error doesn't wrap any reason \\(empty reasons slice\\)\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:120\n")}, + {desc: "nil_any_slice", err: New([]any{nil}).(*Error), expected: regexp.MustCompile("^goyave.dev/goyave/util/errors.Error: the Error doesn't wrap any reason \\(empty reasons slice\\)\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:121\n")}, + {desc: "single", err: New("err1").(*Error), expected: regexp.MustCompile("^err1\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:122\n")}, { desc: "many_any", err: New([]any{fmt.Errorf("err1"), "err2", nil, map[string]any{"key": "value"}, suberror}).(*Error), // nil should be excluded - expected: regexp.MustCompile("^err1\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:124\n([\\d\\S\\n\\t]*?)\n\nerr2\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:124\n([\\d\\S\\n\\t]*?)\n\nmap\\[key:value\\]\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:124\n([\\d\\S\\n\\t]*?)\n\nsuberror\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:111\n([\\d\\S\\n\\t]*?)$"), + expected: regexp.MustCompile("^err1\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:125\n([\\d\\S\\n\\t]*?)\n\nerr2\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:125\n([\\d\\S\\n\\t]*?)\n\nmap\\[key:value\\]\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:125\n([\\d\\S\\n\\t]*?)\n\nsuberror\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:112\n([\\d\\S\\n\\t]*?)$"), }, { desc: "many_errors", err: New([]error{fmt.Errorf("err1"), nil, suberror}).(*Error), // nil should be excluded - expected: regexp.MustCompile("^err1\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:129\n([\\d\\S\\n\\t]*?)\n\nsuberror\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:111\n([\\d\\S\\n\\t]*?)$"), + expected: regexp.MustCompile("^err1\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:130\n([\\d\\S\\n\\t]*?)\n\nsuberror\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:112\n([\\d\\S\\n\\t]*?)$"), }, - {desc: "single_already_error", err: New([]error{suberror}).(*Error), expected: regexp.MustCompile("^suberror\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:111\n")}, - {desc: "contains_nil", err: &Error{reasons: []error{nil, nil}, callers: suberror.(*Error).callers}, expected: regexp.MustCompile("^\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:111\n([\\d\\S\\n\\t]*?)\n\n\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:111\n([\\d\\S\\n\\t]*?)$")}, // Should never happen but we want extra safety + {desc: "single_already_error", err: New([]error{suberror}).(*Error), expected: regexp.MustCompile("^suberror\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:112\n")}, + {desc: "contains_nil", err: &Error{reasons: []error{nil, nil}, callers: suberror.(*Error).callers}, expected: regexp.MustCompile("^\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:112\n([\\d\\S\\n\\t]*?)\n\n\ngoyave\\.dev/goyave/v5/util/errors\\.TestErrors\\.func8\n\t(.*?)/goyave/util/errors/error_test\\.go:112\n([\\d\\S\\n\\t]*?)$")}, // Should never happen but we want extra safety } for _, c := range cases { @@ -148,7 +149,7 @@ func TestErrors(t *testing.T) { expected *regexp.Regexp desc string }{ - {desc: "OK", err: New("").(*Error), expected: regexp.MustCompile("/goyave/util/errors/error_test.go:151$")}, + {desc: "OK", err: New("").(*Error), expected: regexp.MustCompile("/goyave/util/errors/error_test.go:152$")}, {desc: "unknown", err: NewSkip("", 5).(*Error), expected: regexp.MustCompile(`^\[unknown file line\]$`)}, // Skip more frames than necessary to have empty callers slice } @@ -186,11 +187,9 @@ func TestErrors(t *testing.T) { t.Run(c.desc, func(t *testing.T) { res, err := json.Marshal(c.err) if c.expectedErr { - if !assert.Error(t, err) { - return - } - } else if !assert.NoError(t, err) { - return + require.Error(t, err) + } else { + require.NoError(t, err) } assert.Equal(t, c.expected, string(res)) }) @@ -203,7 +202,7 @@ func TestErrors(t *testing.T) { assert.Equal(t, "map[key:value]", reason.Error()) res, err := reason.MarshalJSON() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, `{"key":"value"}`, string(res)) }) diff --git a/util/fsutil/fsutil_test.go b/util/fsutil/fsutil_test.go index 6382f3cc..6b10900f 100644 --- a/util/fsutil/fsutil_test.go +++ b/util/fsutil/fsutil_test.go @@ -19,10 +19,9 @@ import ( _ "embed" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5/util/errors" "goyave.dev/goyave/v5/util/fsutil/osfs" - - stderrors "errors" ) func deleteFile(path string) { @@ -95,36 +94,34 @@ func TestGetMIMEType(t *testing.T) { mime, size, err := GetMIMEType(&osfs.FS{}, toAbsolutePath("resources/img/logo/goyave_16.png")) assert.Equal(t, "image/png", mime) assert.Equal(t, int64(716), size) - assert.NoError(t, err) + require.NoError(t, err) mime, _, err = GetMIMEType(&osfs.FS{}, toAbsolutePath("resources/test_script.sh")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "text/plain; charset=utf-8", mime) mime, _, err = GetMIMEType(&osfs.FS{}, toAbsolutePath(".gitignore")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "application/octet-stream", mime) mime, _, err = GetMIMEType(&osfs.FS{}, toAbsolutePath("config/config.test.json")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "application/json", mime) mime, _, err = GetMIMEType(&osfs.FS{}, toAbsolutePath("resources/test_script.js")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "text/javascript; charset=utf-8", mime) cssPath := toAbsolutePath("util/fsutil/test.css") err = os.WriteFile(cssPath, []byte("body{ margin:0; }"), 0644) - if err != nil { - panic(err) - } + require.NoError(t, err) mime, _, err = GetMIMEType(&osfs.FS{}, cssPath) assert.Equal(t, "text/css", mime) - assert.NoError(t, err) + require.NoError(t, err) deleteFile(cssPath) _, _, err = GetMIMEType(&osfs.FS{}, toAbsolutePath("doesn't exist")) - assert.Error(t, err) + require.Error(t, err) t.Run("empty_file", func(t *testing.T) { filename := "empty_GetMIMEType.json" @@ -140,7 +137,7 @@ func TestGetMIMEType(t *testing.T) { assert.Equal(t, "application/json", mime) assert.Equal(t, int64(0), size) - assert.NoError(t, err) + require.NoError(t, err) }) } @@ -295,19 +292,17 @@ func TestEmbed(t *testing.T) { e := NewEmbed(resources) stat, err := e.Stat("osfs/osfs.go") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.False(t, stat.IsDir()) assert.Equal(t, "osfs.go", stat.Name()) stat, err = e.Stat("notadir/osfs.go") assert.Nil(t, stat) - if assert.NotNil(t, err) { + if assert.Error(t, err) { e, ok := err.(*errors.Error) if assert.True(t, ok) { var fsErr *fs.PathError - if assert.True(t, stderrors.As(e, &fsErr)) { + if assert.ErrorAs(t, e, &fsErr) { assert.Equal(t, "open", fsErr.Op) assert.Equal(t, "notadir/osfs.go", fsErr.Path) } @@ -317,9 +312,7 @@ func TestEmbed(t *testing.T) { // Make it so the underlying FS implements e.FS = testStatFS{resources} stat, err = e.Stat("osfs/osfs.go") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) _, ok := stat.(*mockFileInfo) assert.True(t, ok) @@ -327,7 +320,7 @@ func TestEmbed(t *testing.T) { e := NewEmbed(&mockFS{}) f, err := e.Open("") - assert.NoError(t, err) + require.NoError(t, err) _, ok := f.(*mockFile) assert.True(t, ok) }) @@ -335,11 +328,10 @@ func TestEmbed(t *testing.T) { e := NewEmbed(&mockFS{}) f, err := e.ReadDir("") - assert.NoError(t, err) - if assert.Len(t, f, 1) { - _, ok := f[0].(*mockDirEntry) - assert.True(t, ok) - } + require.NoError(t, err) + require.Len(t, f, 1) + _, ok := f[0].(*mockDirEntry) + assert.True(t, ok) }) } diff --git a/util/fsutil/osfs/osfs_test.go b/util/fsutil/osfs/osfs_test.go index 58acfcd0..94d71362 100644 --- a/util/fsutil/osfs/osfs_test.go +++ b/util/fsutil/osfs/osfs_test.go @@ -10,6 +10,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5/util/fsutil" ) @@ -35,41 +36,31 @@ func TestOSFS(t *testing.T) { t.Run("Open", func(t *testing.T) { fs := &FS{} file, err := fs.Open("resources/test_file.txt") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer func() { assert.NoError(t, file.Close()) }() contents, err := io.ReadAll(file) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) assert.Equal(t, append([]byte{0xef, 0xbb, 0xbf}, []byte("utf-8 with BOM content")...), contents) }) t.Run("OpenFile", func(t *testing.T) { fs := &FS{} file, err := fs.OpenFile("resources/test_file.txt", os.O_RDONLY, 0660) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer func() { assert.NoError(t, file.Close()) }() contents, err := io.ReadAll(file) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) assert.Equal(t, append([]byte{0xef, 0xbb, 0xbf}, []byte("utf-8 with BOM content")...), contents) }) t.Run("ReadDir", func(t *testing.T) { osfs := &FS{} entries, err := osfs.ReadDir("resources/lang") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) type result struct { name string @@ -90,9 +81,7 @@ func TestOSFS(t *testing.T) { t.Run("Stat", func(t *testing.T) { fs := &FS{} info, err := fs.Stat("resources/test_file.txt") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.False(t, info.IsDir()) assert.Equal(t, "test_file.txt", info.Name()) @@ -101,9 +90,7 @@ func TestOSFS(t *testing.T) { t.Run("Getwd", func(t *testing.T) { fs := &FS{} wd, err := fs.Getwd() - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.NotEmpty(t, wd) }) @@ -131,7 +118,7 @@ func TestOSFS(t *testing.T) { } }) - assert.NoError(t, fs.Mkdir(path, 0770)) + require.NoError(t, fs.Mkdir(path, 0770)) assert.True(t, fs.IsDirectory(path)) }) @@ -145,7 +132,7 @@ func TestOSFS(t *testing.T) { } }) - assert.NoError(t, fs.MkdirAll(path, 0770)) + require.NoError(t, fs.MkdirAll(path, 0770)) assert.True(t, fs.IsDirectory(path)) }) diff --git a/util/session/session_test.go b/util/session/session_test.go index f16cc619..5eea220c 100644 --- a/util/session/session_test.go +++ b/util/session/session_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gorm.io/gorm" "gorm.io/gorm/clause" "gorm.io/gorm/utils/tests" @@ -44,9 +45,7 @@ func TestGormSession(t *testing.T) { t.Run("New", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) opts := &sql.TxOptions{ Isolation: sql.LevelReadCommitted, @@ -63,9 +62,7 @@ func TestGormSession(t *testing.T) { t.Run("Manual", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) committer := &testCommitter{} db.Statement.ConnPool = committer opts := &sql.TxOptions{ @@ -76,25 +73,23 @@ func TestGormSession(t *testing.T) { ctx := context.WithValue(context.Background(), testKey{}, "testvalue") tx, err := session.Begin(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, session, tx) assert.Equal(t, opts, tx.(Gorm).TxOptions) assert.Equal(t, tx.(Gorm).ctx, tx.Context()) assert.Equal(t, "testvalue", tx.Context().Value(testKey{})) assert.Equal(t, tx.(Gorm).db, tx.Context().Value(dbKey{})) - assert.NoError(t, tx.Commit()) + require.NoError(t, tx.Commit()) assert.True(t, committer.committed) - assert.NoError(t, tx.Rollback()) + require.NoError(t, tx.Rollback()) assert.True(t, committer.rolledback) }) t.Run("Begin_error", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) beginErr := fmt.Errorf("begin error") committer := &testCommitter{ beginError: beginErr, @@ -103,20 +98,18 @@ func TestGormSession(t *testing.T) { session := GORM(db, nil) tx, err := session.Begin(context.Background()) - assert.ErrorIs(t, err, beginErr) + require.ErrorIs(t, err, beginErr) assert.Nil(t, tx) err = session.Transaction(context.Background(), func(_ context.Context) error { return nil }) - assert.ErrorIs(t, err, beginErr) + require.ErrorIs(t, err, beginErr) }) t.Run("Nested_manual", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) committer := &testCommitter{} db.Statement.ConnPool = committer session := GORM(db, nil) @@ -124,20 +117,18 @@ func TestGormSession(t *testing.T) { ctx := context.WithValue(context.Background(), testKey{}, "testvalue") tx, err := session.Begin(ctx) tx.(Gorm).db.Statement.Clauses["testclause"] = clause.Clause{} // Use this to check the nested db is based on the parent DB - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tx) subtx, err := session.Begin(tx.Context()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "testvalue", subtx.(Gorm).db.Statement.Context.Value(testKey{})) // Parent context is kept assert.Contains(t, subtx.(Gorm).db.Statement.Clauses, "testclause") // Parent DB is used }) t.Run("Transaction", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) committer := &testCommitter{} db.Statement.ConnPool = committer session := GORM(db, nil) @@ -152,7 +143,7 @@ func TestGormSession(t *testing.T) { assert.True(t, ok) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "testvalue", ctxValue) assert.True(t, committer.committed) assert.False(t, committer.rolledback) @@ -160,9 +151,7 @@ func TestGormSession(t *testing.T) { t.Run("Nested_Transaction", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) committer := &testCommitter{} db.Statement.ConnPool = committer session := GORM(db, nil) @@ -170,7 +159,7 @@ func TestGormSession(t *testing.T) { ctx := context.WithValue(context.Background(), testKey{}, "testvalue") tx, err := session.Begin(ctx) tx.(Gorm).db.Statement.Clauses["testclause"] = clause.Clause{} // Use this to check the nested db is based on the parent DB - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tx) err = session.Transaction(tx.Context(), func(ctx context.Context) error { @@ -179,14 +168,12 @@ func TestGormSession(t *testing.T) { assert.Contains(t, db.Statement.Clauses, "testclause") // Parent DB is used return nil }) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("TransactionError", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) committer := &testCommitter{} db.Statement.ConnPool = committer session := GORM(db, nil) @@ -197,7 +184,7 @@ func TestGormSession(t *testing.T) { ctxValue = ctx.Value(testKey{}) return fmt.Errorf("test err") }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, errors.New(fmt.Errorf("test err")).Error(), err.Error()) assert.Equal(t, "testvalue", ctxValue) assert.True(t, committer.rolledback) @@ -206,9 +193,7 @@ func TestGormSession(t *testing.T) { t.Run("Transaction_Commit_error", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) commitErr := fmt.Errorf("commit error") committer := &testCommitter{ commitError: commitErr, @@ -219,14 +204,12 @@ func TestGormSession(t *testing.T) { err = session.Transaction(context.Background(), func(_ context.Context) error { return nil }) - assert.ErrorIs(t, err, commitErr) + require.ErrorIs(t, err, commitErr) }) t.Run("DB", func(t *testing.T) { db, err := database.NewFromDialector(cfg, nil, tests.DummyDialector{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) fallback := &gorm.DB{} cases := []struct { diff --git a/util/testutil/logger_test.go b/util/testutil/logger_test.go index 48af4685..4d60769a 100644 --- a/util/testutil/logger_test.go +++ b/util/testutil/logger_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type mockT struct { @@ -24,7 +25,7 @@ func TestLogWriter(t *testing.T) { } n, err := writerLogger.Write([]byte("logs")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 4, n) assert.Equal(t, "logs", buf.String()) diff --git a/util/testutil/testutil_test.go b/util/testutil/testutil_test.go index cd7c3bd5..1234f1ed 100644 --- a/util/testutil/testutil_test.go +++ b/util/testutil/testutil_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/goyave/v5" "goyave.dev/goyave/v5/config" "goyave.dev/goyave/v5/slog" @@ -49,7 +50,7 @@ func TestTestServer(t *testing.T) { }) t.Run("NewTestServer_AutoConfig", func(t *testing.T) { - assert.NoError(t, os.Setenv("GOYAVE_ENV", "test")) + require.NoError(t, os.Setenv("GOYAVE_ENV", "test")) server := NewTestServerWithOptions(t, goyave.Options{}) assert.NotNil(t, server.Lang) @@ -57,7 +58,7 @@ func TestTestServer(t *testing.T) { assert.Panics(t, func() { // Config file not found - assert.NoError(t, os.Setenv("GOYAVE_ENV", "")) + require.NoError(t, os.Setenv("GOYAVE_ENV", "")) NewTestServerWithOptions(t, goyave.Options{}) }) }) @@ -73,10 +74,8 @@ func TestTestServer(t *testing.T) { resp := server.TestRequest(httptest.NewRequest(http.MethodGet, "/route", nil)) assert.Equal(t, http.StatusOK, resp.StatusCode) respBody, err := io.ReadAll(resp.Body) - assert.NoError(t, resp.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, "OK", string(respBody)) }) @@ -108,10 +107,8 @@ func TestTestServer(t *testing.T) { }) assert.Equal(t, http.StatusOK, resp.StatusCode) respBody, err := io.ReadAll(resp.Body) - assert.NoError(t, resp.Body.Close()) - if !assert.NoError(t, err) { - return - } + require.NoError(t, resp.Body.Close()) + require.NoError(t, err) assert.Equal(t, "OK", string(respBody)) }) @@ -125,7 +122,7 @@ func TestTestServer(t *testing.T) { assert.NotNil(t, req.Extra) b, err := io.ReadAll(req.Body()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "body", string(b)) assert.Equal(t, server.Lang.GetDefault(), req.Lang) }) @@ -138,8 +135,8 @@ func TestTestServer(t *testing.T) { resp.String(http.StatusOK, "hello") result := recorder.Result() b, err := io.ReadAll(result.Body) - assert.NoError(t, result.Body.Close()) - assert.NoError(t, err) + require.NoError(t, result.Body.Close()) + require.NoError(t, err) assert.Equal(t, "hello", string(b)) assert.NotPanics(t, func() { // No panics because the server is accessible so the ErrLogger.Println succeeds @@ -162,7 +159,7 @@ func TestNewTestRequest(t *testing.T) { assert.NotNil(t, req.Extra) b, err := io.ReadAll(req.Body()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "body", string(b)) } @@ -174,41 +171,38 @@ func TestNewTestResponse(t *testing.T) { resp.String(http.StatusOK, "hello") result := recorder.Result() b, err := io.ReadAll(result.Body) - assert.NoError(t, result.Body.Close()) - assert.NoError(t, err) + require.NoError(t, result.Body.Close()) + require.NoError(t, err) assert.Equal(t, "hello", string(b)) } func TestReadJSONBody(t *testing.T) { body := bytes.NewBufferString(`{"key":"value"}`) jsonBody, err := ReadJSONBody[map[string]string](body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]string{"key": "value"}, jsonBody) jsonBodyError, err := ReadJSONBody[string](body) - assert.Error(t, err) + require.Error(t, err) assert.Empty(t, jsonBodyError) } func TestWriteMultipartFile(t *testing.T) { body := &bytes.Buffer{} writer := multipart.NewWriter(body) - assert.NoError(t, WriteMultipartFile(writer, &osfs.FS{}, "../../resources/img/logo/goyave_16.png", "profile_picture", "goyave_16.png")) - assert.NoError(t, writer.Close()) + require.NoError(t, WriteMultipartFile(writer, &osfs.FS{}, "../../resources/img/logo/goyave_16.png", "profile_picture", "goyave_16.png")) + require.NoError(t, writer.Close()) req := NewTestRequest(http.MethodPost, "/uri", body) req.Header().Set("Content-Type", writer.FormDataContentType()) - assert.NoError(t, req.Request().ParseMultipartForm(1024*1024*1024)) + require.NoError(t, req.Request().ParseMultipartForm(1024*1024*1024)) files := req.Request().MultipartForm.File - if !assert.Len(t, files, 1) || !assert.Contains(t, files, "profile_picture") { - return - } + require.Len(t, files, 1) + require.Contains(t, files, "profile_picture") file := files["profile_picture"] - if !assert.Len(t, file, 1) { - return - } + require.Len(t, file, 1) assert.Equal(t, "goyave_16.png", file[0].Filename) assert.Equal(t, int64(716), file[0].Size) assert.Equal(t, textproto.MIMEHeader{"Content-Type": []string{"application/octet-stream"}, "Content-Disposition": []string{"form-data; name=\"profile_picture\"; filename=\"goyave_16.png\""}}, file[0].Header) @@ -216,9 +210,8 @@ func TestWriteMultipartFile(t *testing.T) { func TestCreateTestFiles(t *testing.T) { files, err := CreateTestFiles(&osfs.FS{}, "../../resources/img/logo/goyave_16.png", "../../resources/test_file.txt") - if !assert.NoError(t, err) || !assert.Len(t, files, 2) { - return - } + require.NoError(t, err) + require.Len(t, files, 2) assert.Equal(t, "goyave_16.png", files[0].Header.Filename) assert.Equal(t, int64(716), files[0].Header.Size) @@ -233,7 +226,7 @@ func TestCreateTestFiles(t *testing.T) { func TestToJSON(t *testing.T) { reader := ToJSON(map[string]any{"key": "value"}) result, err := io.ReadAll(reader) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, `{"key":"value"}`, string(result)) assert.Panics(t, func() { diff --git a/util/typeutil/typeutil_test.go b/util/typeutil/typeutil_test.go index 06788941..dfabfac7 100644 --- a/util/typeutil/typeutil_test.go +++ b/util/typeutil/typeutil_test.go @@ -5,6 +5,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConvert(t *testing.T) { @@ -52,11 +53,11 @@ func TestConvert(t *testing.T) { res, err := Convert[*TestStruct](c.value) assert.Equal(t, c.want, res) if c.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) - + require.NoError(t, err) } + assert.Equal(t, c.want, res) }) } @@ -64,46 +65,46 @@ func TestConvert(t *testing.T) { t.Run("string", func(t *testing.T) { res, err := Convert[string]("hello") assert.Equal(t, "hello", res) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("int", func(t *testing.T) { res, err := Convert[int](123) assert.Equal(t, 123, res) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("float", func(t *testing.T) { res, err := Convert[float64](0.3) - assert.Equal(t, 0.3, res) - assert.NoError(t, err) + assert.InEpsilon(t, 0.3, res, 0) + require.NoError(t, err) }) t.Run("bool", func(t *testing.T) { res, err := Convert[bool](true) - assert.Equal(t, true, res) - assert.NoError(t, err) + assert.True(t, res) + require.NoError(t, err) }) t.Run("mismatching types", func(t *testing.T) { res, err := Convert[bool]("true") - assert.Equal(t, false, res) - assert.Error(t, err) + assert.False(t, res) + require.Error(t, err) }) t.Run("[]string", func(t *testing.T) { res, err := Convert[[]string]([]string{"a", "b", "c"}) assert.Equal(t, []string{"a", "b", "c"}, res) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("[]any", func(t *testing.T) { res, err := Convert[[]any]([]string{"a", "4", "c"}) assert.Equal(t, []any{"a", "4", "c"}, res) - assert.NoError(t, err) + require.NoError(t, err) res, err = Convert[[]any]([]any{"a", 4, 4.0, true, []any{"a", "b"}}) assert.Equal(t, []any{"a", 4, 4.0, true, []any{"a", "b"}}, res) - assert.NoError(t, err) + require.NoError(t, err) }) } func TestMustConvert(t *testing.T) { - assert.Equal(t, 0.3, MustConvert[float64](0.3)) + assert.InEpsilon(t, 0.3, MustConvert[float64](0.3), 0) assert.Panics(t, func() { MustConvert[float64]("0.3") diff --git a/util/typeutil/undefined_test.go b/util/typeutil/undefined_test.go index ebf10053..9661211c 100644 --- a/util/typeutil/undefined_test.go +++ b/util/typeutil/undefined_test.go @@ -10,6 +10,7 @@ import ( "github.com/samber/lo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "goyave.dev/copier" ) @@ -54,25 +55,25 @@ func TestUndefined(t *testing.T) { t.Run("UnmarshalJSON", func(t *testing.T) { u := &Undefined[int64]{} - assert.NoError(t, json.Unmarshal([]byte("123456789"), u)) + require.NoError(t, json.Unmarshal([]byte("123456789"), u)) assert.Equal(t, &Undefined[int64]{Val: 123456789, Present: true}, u) u = &Undefined[int64]{} - assert.Error(t, json.Unmarshal([]byte("\"notint\""), u)) + require.Error(t, json.Unmarshal([]byte("\"notint\""), u)) assert.Equal(t, &Undefined[int64]{Val: 0, Present: false}, u) }) t.Run("UnmarshalText", func(t *testing.T) { u := &Undefined[int64]{} // Not a text unmarshaler - assert.Error(t, u.UnmarshalText([]byte("123456789"))) + require.Error(t, u.UnmarshalText([]byte("123456789"))) assert.Equal(t, &Undefined[int64]{Val: 0, Present: true}, u) u2 := &Undefined[testInt64]{} - assert.NoError(t, u2.UnmarshalText([]byte("123456789"))) + require.NoError(t, u2.UnmarshalText([]byte("123456789"))) assert.Equal(t, &Undefined[testInt64]{Val: testInt64{Val: 123456789}, Present: true}, u2) u3 := &Undefined[testInt64]{} - assert.Error(t, u3.UnmarshalText([]byte("notint"))) + require.Error(t, u3.UnmarshalText([]byte("notint"))) assert.Equal(t, &Undefined[testInt64]{Val: testInt64{Val: 0}, Present: true}, u3) }) @@ -111,11 +112,10 @@ func TestUndefined(t *testing.T) { v, err := c.undefined.Value() assert.Equal(t, c.want, v) if c.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } - } }) @@ -156,7 +156,7 @@ func TestUndefined(t *testing.T) { c := c err := c.undefined.Scan(c.value) if c.wantErr != nil { - assert.ErrorContains(t, err, c.wantErr.Error()) + require.ErrorContains(t, err, c.wantErr.Error()) } assert.Equal(t, c.want, c.undefined) diff --git a/util/walk/walk_test.go b/util/walk/walk_test.go index 93017806..ed16b6fe 100644 --- a/util/walk/walk_test.go +++ b/util/walk/walk_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func strPtr(s string) *string { @@ -87,7 +88,7 @@ func testPathScanner(t *testing.T, path string, expected []string) { } assert.Equal(t, expected, result) - assert.Nil(t, scanner.Err()) + require.NoError(t, scanner.Err()) } func testPathScannerError(t *testing.T, path string) { @@ -98,11 +99,8 @@ func testPathScannerError(t *testing.T, path string) { } err := scanner.Err() - if assert.NotNil(t, err) { - assert.Contains(t, err.Error(), "illegal syntax: ") - } else { - fmt.Printf("%#v\n", result) - } + require.Error(t, err, fmt.Sprintf("%#v", result)) + assert.Contains(t, err.Error(), "illegal syntax: ") } func TestPathScanner(t *testing.T) { @@ -129,7 +127,7 @@ func TestPathScanner(t *testing.T) { func TestParse(t *testing.T) { path, err := Parse("object.array[].field") - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, &Path{ Name: strPtr("object"), Type: PathTypeObject, @@ -147,7 +145,7 @@ func TestParse(t *testing.T) { }, path) path, err = Parse("array[][]") - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, &Path{ Name: strPtr("array"), Type: PathTypeArray, @@ -160,7 +158,7 @@ func TestParse(t *testing.T) { }, path) path, err = Parse("object.field") - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, &Path{ Name: strPtr("object"), Type: PathTypeObject, @@ -171,7 +169,7 @@ func TestParse(t *testing.T) { }, path) path, err = Parse("array[][].field") - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, &Path{ Name: strPtr("array"), Type: PathTypeArray, @@ -188,7 +186,7 @@ func TestParse(t *testing.T) { }, path) path, err = Parse("array[][].field[]") - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, &Path{ Name: strPtr("array"), Type: PathTypeArray, @@ -208,7 +206,7 @@ func TestParse(t *testing.T) { }, path) path, err = Parse("object.*.prop") - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, &Path{ Name: strPtr("object"), Type: PathTypeObject, @@ -223,7 +221,7 @@ func TestParse(t *testing.T) { }, path) path, err = Parse("") - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, &Path{ Name: strPtr(""), Type: PathTypeElement, @@ -232,7 +230,7 @@ func TestParse(t *testing.T) { path, err = Parse(".invalid[]path") assert.Nil(t, path) - assert.NotNil(t, err) + require.Error(t, err) } func TestMustParse(t *testing.T) { @@ -262,9 +260,7 @@ func testWalk(t *testing.T, data map[string]any, p string) []*Context { matches := make([]*Context, 0, 5) path, err := Parse(p) - if !assert.Nil(t, err) { - assert.FailNow(t, err.Error()) - } + require.NoError(t, err) path.Walk(data, func(c *Context) { matches = append(matches, c) @@ -277,9 +273,7 @@ func testWalkBreak(t *testing.T, data map[string]any, p string) []*Context { matches := make([]*Context, 0, 5) path, err := Parse(p) - if !assert.Nil(t, err) { - assert.FailNow(t, err.Error()) - } + require.NoError(t, err) path.Walk(data, func(c *Context) { matches = append(matches, c) @@ -1412,18 +1406,18 @@ func TestPathSetAllMissingIndexes(t *testing.T) { func TestPathDepth(t *testing.T) { path, _ := Parse("a.b.c") - assert.Equal(t, path.Depth(), uint(3)) + assert.Equal(t, uint(3), path.Depth()) path, _ = Parse("a[].b.c") - assert.Equal(t, path.Depth(), uint(4)) + assert.Equal(t, uint(4), path.Depth()) path, _ = Parse("a") - assert.Equal(t, path.Depth(), uint(1)) + assert.Equal(t, uint(1), path.Depth()) path, _ = Parse("") - assert.Equal(t, path.Depth(), uint(1)) + assert.Equal(t, uint(1), path.Depth()) - assert.Equal(t, Depth(""), uint(1)) - assert.Equal(t, Depth("a"), uint(1)) - assert.Equal(t, Depth("a.b.c"), uint(3)) - assert.Equal(t, Depth("a[].b.c"), uint(4)) + assert.Equal(t, uint(1), Depth("")) + assert.Equal(t, uint(1), Depth("a")) + assert.Equal(t, uint(3), Depth("a.b.c")) + assert.Equal(t, uint(4), Depth("a[].b.c")) } func TestPathTruncate(t *testing.T) { diff --git a/websocket/websocket_test.go b/websocket/websocket_test.go index cab19242..ac7e8948 100644 --- a/websocket/websocket_test.go +++ b/websocket/websocket_test.go @@ -224,9 +224,7 @@ func TestDefaultUpgradeErrorHandler(t *testing.T) { assert.Equal(t, http.StatusBadRequest, result.StatusCode) body, err := testutil.ReadJSONBody[map[string]string](result.Body) assert.NoError(t, result.Body.Close()) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) c.expect(t, body) }) } @@ -308,26 +306,22 @@ func TestUpgrade(t *testing.T) { conn, resp, err := ws.DefaultDialer.Dial(routeURL, nil) assert.Equal(t, "Value", resp.Header.Get("X-Test")) - if !assert.NoError(t, err) { - fmt.Println("RESPONSE STATUS:", resp.StatusCode) - fmt.Println("RESPONSE HEADERS:", resp.Header) - return - } + assert.NoError(t, err, fmt.Sprintf("RESPONSE STATUS: %d, RESPONSE HEADERS: %v", resp.StatusCode, resp.Header)) assert.NoError(t, resp.Body.Close()) defer func() { assert.NoError(t, conn.Close()) }() message := []byte("hello world") - assert.Nil(t, conn.WriteMessage(ws.TextMessage, message)) + assert.NoError(t, conn.WriteMessage(ws.TextMessage, message)) messageType, data, err := conn.ReadMessage() - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, ws.TextMessage, messageType) assert.Equal(t, message, data) m := ws.FormatCloseMessage(ws.CloseNormalClosure, "Connection closed by client") - assert.Nil(t, conn.WriteControl(ws.CloseMessage, m, time.Now().Add(time.Second))) + assert.NoError(t, conn.WriteControl(ws.CloseMessage, m, time.Now().Add(time.Second))) }) go func() { @@ -356,9 +350,7 @@ func TestUpgradeError(t *testing.T) { body, err := testutil.ReadJSONBody[map[string]string](resp.Body) assert.NoError(t, resp.Body.Close()) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) assert.Equal(t, map[string]string{"error": http.StatusText(http.StatusBadRequest)}, body) } @@ -417,19 +409,15 @@ func TestCloseHandshakeTimeout(t *testing.T) { routeURL = "ws" + strings.TrimPrefix(route.BuildURL(), "http") conn, resp, err := ws.DefaultDialer.Dial(routeURL, nil) - if !assert.NoError(t, err) { - fmt.Println("RESPONSE STATUS:", resp.StatusCode) - fmt.Println("RESPONSE HEADERS:", resp.Header) - return - } assert.NoError(t, resp.Body.Close()) + assert.NoError(t, err, fmt.Sprintf("RESPONSE STATUS: %d, RESPONSE HEADERS: %v", resp.StatusCode, resp.Header)) defer func() { assert.NoError(t, conn.Close()) }() time.Sleep(1500 * time.Millisecond) messageType, _, err := conn.ReadMessage() - assert.NotNil(t, err) + assert.Error(t, err) // The server has sent the close handshake payload with NormalClosureMessage assert.Equal(t, &ws.CloseError{Code: ws.CloseNormalClosure, Text: NormalClosureMessage}, err) @@ -446,7 +434,7 @@ func TestCloseHandshakeTimeout(t *testing.T) { func TestCloseHandler(t *testing.T) { c := newConn(&ws.Conn{}, 1*time.Second) - assert.Nil(t, c.closeHandler(ws.CloseNormalClosure, "")) + assert.NoError(t, c.closeHandler(ws.CloseNormalClosure, "")) select { case <-c.waitClose: default: @@ -556,12 +544,8 @@ func TestGracefulClose(t *testing.T) { func testGracefulClose(t *testing.T, routeURL string, expectedError *ws.CloseError) { conn, resp, err := ws.DefaultDialer.Dial(routeURL, nil) - if !assert.NoError(t, err) { - fmt.Println("RESPONSE STATUS:", resp.StatusCode) - fmt.Println("RESPONSE HEADERS:", resp.Header) - return - } assert.NoError(t, resp.Body.Close()) + assert.NoError(t, err, fmt.Sprintf("RESPONSE STATUS: %d, RESPONSE HEADERS: %v", resp.StatusCode, resp.Header)) defer func() { assert.NoError(t, conn.Close()) }() @@ -591,16 +575,14 @@ func TestCloseConnectionClosed(t *testing.T) { r.Subrouter("/websocket").Get("", func(response *goyave.Response, request *goyave.Request) { defer wg.Done() c, err := upgrader.makeUpgrader(request).Upgrade(response, request.Request(), nil) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) response.Status(http.StatusSwitchingProtocols) conn := newConn(c, time.Second) - assert.Nil(t, conn.Conn.Close()) // Connection closed right away, server wont be able to write anymore + assert.NoError(t, conn.Conn.Close()) // Connection closed right away, server wont be able to write anymore err = conn.CloseNormal() - assert.NotNil(t, err) + assert.Error(t, err) assert.Contains(t, err.Error(), "use of closed network connection") }) }) @@ -614,18 +596,14 @@ func TestCloseConnectionClosed(t *testing.T) { routeURL = "ws" + strings.TrimPrefix(route.BuildURL(), "http") conn, resp, err := ws.DefaultDialer.Dial(routeURL, nil) - if !assert.NoError(t, err) { - fmt.Println("RESPONSE STATUS:", resp.StatusCode) - fmt.Println("RESPONSE HEADERS:", resp.Header) - return - } assert.NoError(t, resp.Body.Close()) + assert.NoError(t, err, fmt.Sprintf("RESPONSE STATUS: %d, RESPONSE HEADERS: %v", resp.StatusCode, resp.Header)) defer func() { assert.NoError(t, conn.Close()) }() _, _, err = conn.ReadMessage() - assert.NotNil(t, err) + assert.Error(t, err) assert.Equal(t, &ws.CloseError{Code: ws.CloseAbnormalClosure, Text: "unexpected EOF"}, err) }) @@ -654,16 +632,14 @@ func TestCloseWriteTimeout(t *testing.T) { r.Subrouter("/websocket").Get("", func(response *goyave.Response, request *goyave.Request) { defer wg.Done() c, err := upgrader.makeUpgrader(request).Upgrade(response, request.Request(), nil) - if !assert.NoError(t, err) { - return - } + assert.NoError(t, err) response.Status(http.StatusSwitchingProtocols) conn := newConn(c, time.Second) conn.closeTimeout = -1 * time.Second // No error expected, the connection should close as normal without waiting - assert.Nil(t, conn.CloseNormal()) + assert.NoError(t, conn.CloseNormal()) }) }) @@ -676,12 +652,8 @@ func TestCloseWriteTimeout(t *testing.T) { routeURL = "ws" + strings.TrimPrefix(route.BuildURL(), "http") conn, resp, err := ws.DefaultDialer.Dial(routeURL, nil) - if !assert.NoError(t, err) { - fmt.Println("RESPONSE STATUS:", resp.StatusCode) - fmt.Println("RESPONSE HEADERS:", resp.Header) - return - } assert.NoError(t, resp.Body.Close()) + assert.NoError(t, err, fmt.Sprintf("RESPONSE STATUS: %d, RESPONSE HEADERS: %v", resp.StatusCode, resp.Header)) assert.NoError(t, conn.Close()) })