lint
Some checks failed
Check / checks (push) Failing after 3m48s

This commit is contained in:
Gustavo Maronato 2024-03-09 05:53:28 -05:00
parent 4fef573447
commit be39b22ace
No known key found for this signature in database
19 changed files with 68 additions and 63 deletions

View File

@ -111,7 +111,7 @@ func newRootCmd(version string) (*ffcli.Command, *config.Config) {
ShortUsage: "goshort <subcommand> [flags]",
ShortHelp: "goshort is a tiny URL shortener",
FlagSet: fs,
Exec: func(ctx context.Context, args []string) error {
Exec: func(_ context.Context, args []string) error {
// If the user didn't provide any subcommand, then
// we'll just show the help message.
if len(args) == 0 {
@ -152,7 +152,7 @@ func newRootCmd(version string) (*ffcli.Command, *config.Config) {
Name: "version",
ShortUsage: "version",
ShortHelp: "Show version information",
Exec: func(ctx context.Context, args []string) error {
Exec: func(_ context.Context, _ []string) error {
fmt.Printf("goshort version %s\n", version)
return nil
@ -203,7 +203,7 @@ func NewConfigCmd(cfg *config.Config) *ffcli.Command {
ShortUsage: "goshort config [flags]",
ShortHelp: "Prints the current config",
FlagSet: fs,
Exec: func(ctx context.Context, args []string) error {
Exec: func(_ context.Context, _ []string) error {
cfg.PrettyPrint()
return nil

View File

@ -4,14 +4,14 @@ import (
"errors"
"testing"
. "git.maronato.dev/maronato/goshort/internal/errs"
"git.maronato.dev/maronato/goshort/internal/errs"
"github.com/stretchr/testify/assert"
)
func TestErrorf(t *testing.T) {
ErrMyError := errors.New("my error") //nolint:goerr113 // This is a test error
err := Errorf("my message", ErrMyError)
err := errs.Errorf("my message", ErrMyError)
assert.ErrorIs(t, err, ErrMyError, "Errorf should return an error with the same error type as the one passed as argument")
assert.Equal(t, "my message: my error", err.Error(), "Errorf should return an error with the same message as the one passed as argument")

View File

@ -103,8 +103,6 @@ func (s *Server) Start(ctx context.Context) error {
eg, egCtx := errgroup.WithContext(uiCtx)
eg.Go(func() error {
// Execute the command
// Start the command execution
if err := cmd.Run(); err != nil {
return fmt.Errorf("error starting the server: %w", err)
}

View File

@ -26,12 +26,14 @@ func Auth(userService *userservice.UserService, tokenService *tokenservice.Token
// Authenticate user
authMethod := TokenAuth
user, err := authenticateViaToken(r, tokenService)
span.AddEvent("queried token auth")
if err != nil {
// Failed to authenticate via token. Try to authenticate via session.
authMethod = SessionAuth
user, err = authenticateUserViaSession(r, userService)
span.AddEvent("queried session auth")
if err != nil {

View File

@ -154,7 +154,6 @@ func ListUserSessions(ctx context.Context, user *models.User) (sessions []Sessio
return nil
})
if err != nil {
return []Session{}, fmt.Errorf("error listing user sessions: %w", err)
}
@ -177,6 +176,7 @@ func DeleteUserSession(ctx context.Context, user *models.User, sessionToken stri
if err != nil {
return fmt.Errorf("error destroying session: %w", err)
}
found = true
// Since we found the session, we can stop iterating
return errStopIteration

View File

@ -11,7 +11,7 @@ import (
func Tracer() func(http.Handler) http.Handler {
middleware := otelhttp.NewMiddleware("serve",
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
otelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {
return fmt.Sprintf("%s %s", r.Method, r.URL.Path)
}),
)

View File

@ -124,6 +124,7 @@ func TestEndpointFindShort(t *testing.T) {
// Check if the access was logged
<-debugCh
logs, err := shortLogs.ListLogs(ctx, short)
assert.Nil(t, err)

View File

@ -16,7 +16,7 @@ func NewShortRouter(h *ShortHandler) http.Handler {
// so chi doesn't respond with a 404 by default.
// We do this so that the next handler, the static handler,
// can receive non-matching requests and handle them.
mux.Get("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
mux.Get("/*", http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))
return mux
}

View File

@ -7,7 +7,7 @@ import (
"git.maronato.dev/maronato/goshort/internal/config"
"git.maronato.dev/maronato/goshort/internal/storage"
. "git.maronato.dev/maronato/goshort/internal/storage/bun"
bunstorage "git.maronato.dev/maronato/goshort/internal/storage/bun"
storagetesting "git.maronato.dev/maronato/goshort/internal/storage/testing"
randomutil "git.maronato.dev/maronato/goshort/internal/util/random"
"github.com/stretchr/testify/assert"
@ -37,7 +37,7 @@ func TestNewBunDB(t *testing.T) {
func TestNewBunStorage(t *testing.T) {
db := newNewBunDBHelper()
bs := NewBunStorage(&config.Config{}, db)
bs := bunstorage.NewBunStorage(&config.Config{}, db)
assert.NotNil(t, bs, "Storage should not be nil")
assert.Implements(t, (*storage.Storage)(nil), bs, "Storage should implement the Storage interface")
@ -46,7 +46,7 @@ func TestNewBunStorage(t *testing.T) {
func TestStorageInterface(t *testing.T) {
getStg := func() storage.Storage {
db := newNewBunDBHelper()
bs := NewBunStorage(&config.Config{}, db)
bs := bunstorage.NewBunStorage(&config.Config{}, db)
return bs
}
@ -57,7 +57,7 @@ func TestStorageInterface(t *testing.T) {
func BenchmarkStorageInterface(b *testing.B) {
getStg := func() storage.Storage {
db := newNewBunDBHelper()
bs := NewBunStorage(&config.Config{}, db)
bs := bunstorage.NewBunStorage(&config.Config{}, db)
return bs
}
@ -68,7 +68,7 @@ func BenchmarkStorageInterface(b *testing.B) {
func TestBunStorage_Start(t *testing.T) {
ctx := context.Background()
db := newNewBunDBHelper()
bs := NewBunStorage(&config.Config{}, db)
bs := bunstorage.NewBunStorage(&config.Config{}, db)
var tables []string
@ -99,7 +99,7 @@ func TestBunStorage_Start(t *testing.T) {
func TestBunStorage_Stop(t *testing.T) {
ctx := context.Background()
db := newNewBunDBHelper()
bs := NewBunStorage(&config.Config{}, db)
bs := bunstorage.NewBunStorage(&config.Config{}, db)
_ = bs.Start(ctx)
@ -116,11 +116,11 @@ func TestBunStorage_Stop(t *testing.T) {
func TestBunStorage_RegisterStartHook(t *testing.T) {
ctx := context.Background()
db := newNewBunDBHelper()
bs := NewBunStorage(&config.Config{}, db)
bs := bunstorage.NewBunStorage(&config.Config{}, db)
var called bool
bs.RegisterStartHook(func(ctx context.Context, db *bun.DB) error {
bs.RegisterStartHook(func(_ context.Context, _ *bun.DB) error {
called = true
return nil
@ -137,13 +137,13 @@ func TestBunStorage_RegisterStartHook(t *testing.T) {
func TestBunStorage_RegisterStopHook(t *testing.T) {
ctx := context.Background()
db := newNewBunDBHelper()
bs := NewBunStorage(&config.Config{}, db)
bs := bunstorage.NewBunStorage(&config.Config{}, db)
_ = bs.Start(ctx)
var called bool
bs.RegisterStopHook(func(ctx context.Context, db *bun.DB) error {
bs.RegisterStopHook(func(_ context.Context, _ *bun.DB) error {
called = true
return nil

View File

@ -3,16 +3,16 @@ package models_test
import (
"testing"
. "git.maronato.dev/maronato/goshort/internal/storage/models"
models "git.maronato.dev/maronato/goshort/internal/storage/models"
"github.com/stretchr/testify/assert"
)
func TestNewID(t *testing.T) {
id1 := NewID()
id1 := models.NewID()
assert.Len(t, id1, IDLength, "NewID must generate an ID with length IDLength")
assert.Len(t, id1, models.IDLength, "NewID must generate an ID with length IDLength")
id2 := NewID()
id2 := models.NewID()
assert.NotEqual(t, id1, id2, "NewID must genereate a different ID every time")
}

View File

@ -4,13 +4,13 @@ import (
"testing"
"time"
. "git.maronato.dev/maronato/goshort/internal/storage/models"
models "git.maronato.dev/maronato/goshort/internal/storage/models"
bcryptpasswords "git.maronato.dev/maronato/goshort/internal/util/passwords/bcrypt"
"github.com/stretchr/testify/assert"
)
func TestNewAuthenticatableUser(t *testing.T) {
u := &User{
u := &models.User{
ID: "myid",
Username: "myusername",
CreatedAt: time.Now(),
@ -18,7 +18,7 @@ func TestNewAuthenticatableUser(t *testing.T) {
assert.Empty(t, u.GetPasswordHash(), "Default password should be empty")
au := NewAuthenticatableUser(u, "myhash")
au := models.NewAuthenticatableUser(u, "myhash")
assert.NotSame(t, u, au, "User and Auth user should not be the same object")
assert.Equal(t, u.ID, au.ID, "IDs should be the same")
@ -28,13 +28,13 @@ func TestNewAuthenticatableUser(t *testing.T) {
}
func TestGetPasswordHash(t *testing.T) {
au := NewAuthenticatableUser(&User{}, "myhash")
au := models.NewAuthenticatableUser(&models.User{}, "myhash")
assert.Equal(t, au.GetPasswordHash(), "myhash", "Password hash must've been set")
}
func TestSetPassword(t *testing.T) {
u := &User{}
u := &models.User{}
bh := bcryptpasswords.NewBcryptHasher()
pass := "myrandompasswordx"

View File

@ -72,6 +72,7 @@ func NewSQLiteStorage(_ context.Context, cfg *config.Config) *bunstorage.BunStor
// This will delay the shutdown of the storage, but it'll be for a good cause.
// The user can force the shutdown by using SIGINT or SIGTERM.
noCancelCtx := context.WithoutCancel(ctx)
_, err := activeDB.NewRaw("PRAGMA optimize").Exec(noCancelCtx)
if err != nil {
return errs.Errorf("failed to optimize database: %w", err)

View File

@ -126,6 +126,7 @@ func ITestComplete(t *testing.T, getStg func() storage.Storage) {
if !test.dontStart {
_ = stg.Start(context.Background())
}
test.test(t, stg)
})
}
@ -639,6 +640,7 @@ func ITestCreateUser(t *testing.T, stg storage.Storage) {
if test.password != "" {
_ = test.user.SetPassword(bh, test.password)
}
newUser, err := stg.CreateUser(ctx, test.user)
if errors.Is(test.err, ErrPlaceholder) {
@ -654,6 +656,7 @@ func ITestCreateUser(t *testing.T, stg storage.Storage) {
assert.NotZero(t, newUser.CreatedAt, "Should return a non-zero CreatedAt")
assert.NotZero(t, newUser.ID, "Should return a non-zero ID")
assert.Equal(t, test.newUser.Username, newUser.Username, "Should return the same Username")
if test.password != "" {
v, _ := bh.Verify(test.password, newUser.GetPasswordHash())
assert.True(t, v, "Should have the same password")

View File

@ -4,7 +4,7 @@ import (
"net/http"
"testing"
. "git.maronato.dev/maronato/goshort/internal/util/handler"
handler "git.maronato.dev/maronato/goshort/internal/util/handler"
"github.com/stretchr/testify/assert"
)
@ -14,7 +14,7 @@ func TestChainHandler(t *testing.T) {
// Makes a chain handler factory that writes the status code whrn
// it's n value matches the value of `stopAt`
makeHandler := func(n int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if stopAt == n {
w.WriteHeader(200 + n)
@ -28,7 +28,7 @@ func TestChainHandler(t *testing.T) {
h2 := makeHandler(2)
h3 := makeHandler(3)
ch := NewChainedHandler(h1, h2, h3)
ch := handler.NewChainedHandler(h1, h2, h3)
stopAt = 2

View File

@ -19,10 +19,10 @@ func (h *NoOpHandler) Handle(_ context.Context, _ slog.Record) error { //nolint:
return nil
}
func (h *NoOpHandler) WithAttrs(_ []slog.Attr) slog.Handler { //nolint:ireturn // This is the signature of the interface.
func (h *NoOpHandler) WithAttrs(_ []slog.Attr) slog.Handler {
return NewNoOpHandler()
}
func (h *NoOpHandler) WithGroup(_ string) slog.Handler { //nolint:ireturn // This is the signature of the interface.
func (h *NoOpHandler) WithGroup(_ string) slog.Handler {
return NewNoOpHandler()
}

View File

@ -4,17 +4,17 @@ import (
"testing"
"git.maronato.dev/maronato/goshort/internal/util/passwords"
. "git.maronato.dev/maronato/goshort/internal/util/passwords/argon"
argon "git.maronato.dev/maronato/goshort/internal/util/passwords/argon"
"github.com/stretchr/testify/assert"
)
func TestNewArgonHasher(t *testing.T) {
ah := NewArgonHasher()
ah := argon.NewArgonHasher()
assert.Implements(t, (*passwords.PasswordHasher)(nil), ah, "NewArgonHasher should return a PasswordHasher")
}
func TestArgonHash(t *testing.T) {
ah := NewArgonHasher()
ah := argon.NewArgonHasher()
hash, err := ah.Hash("mypassword")
@ -27,7 +27,7 @@ func TestArgonHash(t *testing.T) {
}
func TestArgonVerify(t *testing.T) {
ah := NewArgonHasher()
ah := argon.NewArgonHasher()
hash, _ := ah.Hash("mypassword")
@ -47,7 +47,7 @@ func TestArgonVerify(t *testing.T) {
}
func TestArgonWasteTime(t *testing.T) {
ah := NewArgonHasher()
ah := argon.NewArgonHasher()
err := ah.WasteTime()

View File

@ -4,17 +4,17 @@ import (
"testing"
"git.maronato.dev/maronato/goshort/internal/util/passwords"
. "git.maronato.dev/maronato/goshort/internal/util/passwords/bcrypt"
bcrypt "git.maronato.dev/maronato/goshort/internal/util/passwords/bcrypt"
"github.com/stretchr/testify/assert"
)
func TestNewBcryptHasher(t *testing.T) {
bh := NewBcryptHasher()
bh := bcrypt.NewBcryptHasher()
assert.Implements(t, (*passwords.PasswordHasher)(nil), bh, "NewBcryptHasher should return a PasswordHasher")
}
func TestBcryptHash(t *testing.T) {
bh := NewBcryptHasher()
bh := bcrypt.NewBcryptHasher()
hash, err := bh.Hash("mypassword")
@ -27,7 +27,7 @@ func TestBcryptHash(t *testing.T) {
}
func TestBcryptVerify(t *testing.T) {
bh := NewBcryptHasher()
bh := bcrypt.NewBcryptHasher()
hash, _ := bh.Hash("mypassword")
@ -47,7 +47,7 @@ func TestBcryptVerify(t *testing.T) {
}
func TestBcryptWasteTime(t *testing.T) {
bh := NewBcryptHasher()
bh := bcrypt.NewBcryptHasher()
err := bh.WasteTime()

View File

@ -3,33 +3,33 @@ package passwords_test
import (
"testing"
. "git.maronato.dev/maronato/goshort/internal/util/passwords"
passwords "git.maronato.dev/maronato/goshort/internal/util/passwords"
"github.com/stretchr/testify/assert"
)
func TestGenerateSalt(t *testing.T) {
r1 := GenerateSalt(8)
r1 := passwords.GenerateSalt(8)
assert.Len(t, r1, 8, "GenerateSalt should return a slice with the length passed as argument")
r2 := GenerateSalt(8)
r2 := passwords.GenerateSalt(8)
assert.NotEqual(t, r1, r2, "GenerateSalt should return different results for different calls")
}
func TestAreEqual(t *testing.T) {
assert.True(t, AreEqual([]byte("abc"), []byte("abc")), "AreEqual should return true for equal byte slices")
assert.False(t, AreEqual([]byte("abc"), []byte("def")), "AreEqual should return false for different byte slices")
assert.True(t, passwords.AreEqual([]byte("abc"), []byte("abc")), "AreEqual should return true for equal byte slices")
assert.False(t, passwords.AreEqual([]byte("abc"), []byte("def")), "AreEqual should return false for different byte slices")
}
func TestEncodePasswordHash(t *testing.T) {
r1 := EncodePasswordHash("myalg", "mysalt", "myhash", map[string]string{"mykey": "myvalue"})
r1 := passwords.EncodePasswordHash("myalg", "mysalt", "myhash", map[string]string{"mykey": "myvalue"})
assert.Equal(t, "myalg$mykey=myvalue$mysalt$myhash", r1, "EncodePasswordHash should return a string with the correct format")
}
func TestDecodePasswordHash(t *testing.T) {
alg, salt, hash, params, err := DecodePasswordHash("myalg$mykey=myvalue$mysalt$myhash")
alg, salt, hash, params, err := passwords.DecodePasswordHash("myalg$mykey=myvalue$mysalt$myhash")
assert.Nil(t, err, "DecodePasswordHash should not return an error for a valid hash")
assert.Equal(t, "myalg", alg, "DecodePasswordHash should return the correct algorithm")
@ -37,7 +37,7 @@ func TestDecodePasswordHash(t *testing.T) {
assert.Equal(t, "myhash", hash, "DecodePasswordHash should return the correct hash")
assert.Equal(t, map[string]string{"mykey": "myvalue"}, params, "DecodePasswordHash should return the correct params")
_, _, _, _, err = DecodePasswordHash("myalg$mykey=myvalue$mysalt") //nolint:dogsled // This is a test
_, _, _, _, err = passwords.DecodePasswordHash("myalg$mykey=myvalue$mysalt") //nolint:dogsled // This is a test
assert.NotNil(t, err, "DecodePasswordHash should return an error for an invalid hash")
}

View File

@ -3,25 +3,25 @@ package randomutil_test
import (
"testing"
. "git.maronato.dev/maronato/goshort/internal/util/random"
random "git.maronato.dev/maronato/goshort/internal/util/random"
"github.com/stretchr/testify/assert"
)
func TestGenerateRandomBytes(t *testing.T) {
r1, err := GenerateRandomBytes(10)
r1, err := random.GenerateRandomBytes(10)
if err != nil {
t.Errorf("Error testing GenerateRandomBytes: %v", err)
}
assert.Len(t, r1, 10, "GenerateRandomBytes should return a slice with the length passed as argument")
r2, _ := GenerateRandomBytes(10)
r2, _ := random.GenerateRandomBytes(10)
assert.NotEqual(t, r1, r2, "GenerateRandomBytes should return different results for different calls")
}
func TestGenerateFromCharset(t *testing.T) {
r1 := GenerateFromCharset("abc", 10)
r1 := random.GenerateFromCharset("abc", 10)
assert.Len(t, r1, 10, "GenerateFromCharset should return a string with the length passed as argument")
@ -29,35 +29,35 @@ func TestGenerateFromCharset(t *testing.T) {
assert.Contains(t, "abc", string(char), "GenerateFromCharset should return a string with the characters passed as argument")
}
r2 := GenerateFromCharset("abc", 10)
r2 := random.GenerateFromCharset("abc", 10)
assert.NotEqual(t, r1, r2, "GenerateFromCharset should return different results for different calls")
}
func TestGenerateSecureToken(t *testing.T) {
r1 := GenerateSecureToken(10)
r1 := random.GenerateSecureToken(10)
assert.Len(t, r1, 10, "GenerateSecureToken should return a string with the length passed as argument")
for _, char := range r1 {
assert.Contains(t, SecureTokenCharset, string(char), "GenerateSecureToken should return a token with the characters from SecureTokenCharset")
assert.Contains(t, random.SecureTokenCharset, string(char), "GenerateSecureToken should return a token with the characters from SecureTokenCharset")
}
r2 := GenerateSecureToken(10)
r2 := random.GenerateSecureToken(10)
assert.NotEqual(t, r1, r2, "GenerateSecureToken should return different results for different calls")
}
func TestGenerateRandomShort(t *testing.T) {
r1 := GenerateRandomShort(10)
r1 := random.GenerateRandomShort(10)
assert.Len(t, r1, 10, "GenerateRandomShort should return a string with the length passed as argument")
for _, char := range r1 {
assert.Contains(t, ShortCharset, string(char), "GenerateRandomShort should return a short with the characters from ShortCharset")
assert.Contains(t, random.ShortCharset, string(char), "GenerateRandomShort should return a short with the characters from ShortCharset")
}
r2 := GenerateRandomShort(10)
r2 := random.GenerateRandomShort(10)
assert.NotEqual(t, r1, r2, "GenerateRandomShort should return different results for different calls")
}